diff --git a/.travis.yml b/.travis.yml index 07914721a9..9bd31bda14 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - node + - 8 sudo: false diff --git a/README.md b/README.md index b826bf5ad5..7e543c937a 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with These can be used by TypeScript 1.0. * [Typings](https://github.com/typings/typings) -* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) +* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) * Manually download from the `master` branch of this repository You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). diff --git a/notNeededPackages.json b/notNeededPackages.json index 498e2e1c4a..306865851b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -186,6 +186,12 @@ "sourceRepoURL": "https://github.com/loopline-systems/electron-builder", "asOfVersion": "2.8.0" }, + { + "libraryName": "error-stack-parser", + "typingsPackageName": "error-stack-parser", + "sourceRepoURL": "https://github.com/stacktracejs/error-stack-parser", + "asOfVersion": "2.0.0" + }, { "libraryName": "eventemitter2", "typingsPackageName": "eventemitter2", @@ -330,6 +336,12 @@ "sourceRepoURL": "https://github.com/tdegrunt/jsonschema", "asOfVersion": "1.1.1" }, + { + "libraryName": "jsplumb", + "typingsPackageName": "jsplumb", + "sourceRepoURL": "https://github.com/jsplumb/jsPlumb", + "asOfVersion": "2.5.7" + }, { "libraryName": "knockout-paging", "typingsPackageName": "knockout-paging", diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 456727756c..822c394a32 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -345,18 +345,47 @@ declare namespace AceAjax { insert(position: Position, text: string): any; /** - * Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event. - * @param row The index of the row to insert at - * @param lines An array of strings - **/ + * @deprecated Use the insertFullLines method instead. + */ insertLines(row: number, lines: string[]): any; /** - * Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event. - * @param position The position to insert at - **/ + * Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertFullLines(row: number, lines: string[]): any; + + /** + * @deprecated Use insertMergedLines(position, ['', '']) instead. + */ insertNewLine(position: Position): any; + /** + * Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertMergedLines(row: number, lines: string[]): any; + /** * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. * @param position The position to insert at @@ -379,12 +408,19 @@ declare namespace AceAjax { removeInLine(row: number, startColumn: number, endColumn: number): any; /** - * Removes a range of full lines. This method also triggers the `'change'` event. - * @param firstRow The first row to be removed - * @param lastRow The last row to be removed - **/ + * @deprecated Use the removeFullLines method instead. + */ removeLines(firstRow: number, lastRow: number): string[]; + /** + * Removes a range of full lines. This method also triggers the `"change"` event. + * @param {Number} firstRow The first row to be removed + * @param {Number} lastRow The last row to be removed + * @returns {[String]} Returns all the removed lines. + * + **/ + removeFullLines(firstRow: number, lastRow: number): string[]; + /** * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. * @param row The row to check @@ -474,9 +510,9 @@ declare namespace AceAjax { removeFold(arg: any): void; expandFold(arg: any): void; - + foldAll(startRow?: number, endRow?: number, depth?: number): void - + unfold(arg1: any, arg2: boolean): void; screenToDocumentColumn(row: number, column: number): void; @@ -2659,9 +2695,9 @@ declare namespace AceAjax { characterWidth: number; lineHeight: number; - + setScrollMargin(top:number, bottom:number, left: number, right: number): void; - + screenToTextCoordinates(left: number, top: number): void; /** diff --git a/types/acorn/acorn-tests.ts b/types/acorn/acorn-tests.ts index 72ca71d2f6..7574df2481 100644 --- a/types/acorn/acorn-tests.ts +++ b/types/acorn/acorn-tests.ts @@ -1,13 +1,13 @@ import acorn = require('acorn'); import * as ESTree from 'estree'; -declare var token: acorn.Token; -declare var tokens: acorn.Token[]; -declare var comment: acorn.Comment; -declare var comments: acorn.Comment[]; -declare var program: ESTree.Program; -var any: any; -var string: string; +declare let token: acorn.Token; +declare let tokens: acorn.Token[]; +declare let comment: acorn.Comment; +declare let comments: acorn.Comment[]; +declare let program: ESTree.Program; +let any: any; +let string: string; // acorn string = acorn.version; @@ -32,16 +32,12 @@ const parser = new acorn.Parser({}, 'export default ""', 0); const node = new acorn.Node(parser, 1, 1); class LooseParser { - constructor(input: string, options = {}) { - - } + constructor(input: string, options = {}) {} // this means you can extend LooseParser - test() { - - } + test() {} } -acorn.addLooseExports(function () { +acorn.addLooseExports(() => { return { type: 'Program', sourceType: 'script', @@ -50,7 +46,7 @@ acorn.addLooseExports(function () { type: 'EmptyStatement' } ] - } + }; }, LooseParser, {}); acorn.parseExpressionAt('string', 2); @@ -63,8 +59,7 @@ acorn.isIdentifierChar(56); acorn.getLineInfo('string', 56); -acorn.plugins['test'] = function (p: acorn.Parser, config: any) { -} +acorn.plugins['test'] = (p: acorn.Parser, config: any) => {}; acorn.tokenizer('console.log("hello world)', {locations: true}).getToken(); acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next(); diff --git a/types/acorn/index.d.ts b/types/acorn/index.d.ts index ce7da6d368..5d02bd716c 100644 --- a/types/acorn/index.d.ts +++ b/types/acorn/index.d.ts @@ -1,10 +1,8 @@ -// Type definitions for Acorn v4.0.3 +// Type definitions for Acorn 4.0 // Project: https://github.com/marijnh/acorn // Definitions by: RReverser , e-cloud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - export as namespace acorn; export = acorn; import * as ESTree from 'estree'; @@ -181,7 +179,7 @@ declare namespace acorn { _typeof: TokenType; _void: TokenType; _delete: TokenType; - } + }; class TokContext { constructor(token: string, isExpr: boolean, preserveSpace: boolean, override: (p: Parser) => void); @@ -230,19 +228,18 @@ declare namespace acorn { const version: string; - interface IParse { - (input: string, options?: Options): ESTree.Program; - } + // TODO: rename type. + type IParse = (input: string, options?: Options) => ESTree.Program; const parse: IParse; function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression; interface ITokenizer { - getToken() : Token, - [Symbol.iterator](): Iterator + getToken(): Token; + [Symbol.iterator](): Iterator; } - + function tokenizer(input: string, options: Options): ITokenizer; let parse_dammit: IParse | undefined; @@ -250,12 +247,10 @@ declare namespace acorn { let pluginsLoose: PluginsObject | undefined; interface ILooseParserClass { - new (input: string, options?: Options): ILooseParser + new (input: string, options?: Options): ILooseParser; } - interface ILooseParser { - - } + interface ILooseParser {} function addLooseExports(parse: IParse, parser: ILooseParserClass, plugins: PluginsObject): void; } diff --git a/types/acorn/tslint.json b/types/acorn/tslint.json index a41bf5d19a..2d05b8507c 100644 --- a/types/acorn/tslint.json +++ b/types/acorn/tslint.json @@ -1,79 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, "export-just-namespace": false, - "import-spacing": false, "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "no-unnecessary-class": false } } diff --git a/types/actions-on-google/NOTICE b/types/actions-on-google/NOTICE new file mode 100644 index 0000000000..262b08db36 --- /dev/null +++ b/types/actions-on-google/NOTICE @@ -0,0 +1,13 @@ +License Notices: + +The API definitions are from Actions on Google reference site [1] and actions-on-google library [2]. +The actions-on-google library is licensed under the Apache 2.0 License [3]. + +The code documentation is reproduced from work created and shared by Google [4] +and used according to terms described in the Creative Commons 3.0 Attribution License [5]. + +[1] https://developers.google.com/actions/ +[2] https://github.com/actions-on-google/actions-on-google-nodejs +[3] http://www.apache.org/licenses/LICENSE-2.0 +[4] https://developers.google.com/readme/policies/ +[5] http://creativecommons.org/licenses/by/3.0/ diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts new file mode 100644 index 0000000000..e57e1e8d98 --- /dev/null +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -0,0 +1,33 @@ +import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp, + Responses, Transactions } from 'actions-on-google'; +import * as express from 'express'; + +function testActionsSdk(request: express.Request, response: express.Response) { + const app = new ActionsSdkApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const richResponse: Responses.RichResponse = app.buildRichResponse() + .addSimpleResponse('Hello world') + .addSuggestions(['foo', 'bar']); + app.ask(richResponse); + }); + app.handleRequest(actionMap); +} + +function testDialogflow(request: express.Request, response: express.Response) { + const app = new DialogflowApp({request, response}); + const actionMap = new Map(); + actionMap.set(app.StandardIntents.MAIN, () => { + const order: Transactions.Order = app.buildOrder('foo'); + app.askForTransactionDecision(order, { + type: app.Transactions.PaymentType.PAYMENT_CARD, + displayName: 'VISA-1234', + deliveryAddressRequired: true + }); + }); + app.handleRequest(actionMap); +} + +const expressApp = express(); +expressApp.get('/actionssdk', testActionsSdk); +expressApp.get('/dialogflow', testDialogflow); diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts new file mode 100644 index 0000000000..09a4fbe0ad --- /dev/null +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -0,0 +1,415 @@ +import * as express from 'express'; + +import { AssistantApp } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; + +// --------------------------------------------------------------------------- +// Actions SDK support +// --------------------------------------------------------------------------- + +export interface ActionsSdkAppOptions { + /** Express HTTP request object. */ + request: express.Request; + /** Express HTTP response object. */ + response: express.Response; + /** Function callback when session starts. */ + sessionStarted?(): any; +} + +/** + * This is the class that handles the conversation API directly from Assistant, + * providing implementation for all the methods available in the API. + */ +export class ActionsSdkApp extends AssistantApp { + /** + * Constructor for ActionsSdkApp object. + * To be used in the Actions SDK HTTP endpoint logic. + * + * @example + * const ActionsSdkApp = require('actions-on-google').ActionsSdkApp; + * const app = new ActionsSdkApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @actionssdk + */ + constructor(options: ActionsSdkAppOptions); + + /** + * @deprecated + * Validates whether request is from Assistant through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromAssistant('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromAssistant(projectId: string): Promise; + + /** + * Validates whether request is from Google through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromGoogle('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromGoogle(projectId: string): Promise; + + /** + * Gets the request Conversation API version. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const apiVersion = app.getApiVersion(); + * + * @return Version value or null if no value. + * @actionssdk + */ + getApiVersion(): string; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return User's raw query or null if no value. + * @actionssdk + */ + getRawInput(): string; + + /** + * Gets previous JSON dialog state that the app sent to Assistant. + * Alternatively, use the app.data field to store JSON values between requests. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const dialogState = app.getDialogState(); + * + * @return JSON object provided to the Assistant in the previous + * user turn or {} if no value. + * @actionssdk + */ + getDialogState(): any; + + /** + * Gets the "versionLabel" specified inside the Action Package. + * Used by app to do version control. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const actionVersionLabel = app.getActionVersionLabel(); + * + * @return The specified version label or null if unspecified. + * @actionssdk + */ + getActionVersionLabel(): string; + + /** + * Gets the unique conversation ID. It's a new ID for the initial query, + * and stays the same until the end of the conversation. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * const conversationId = app.getConversationId(); + * + * @return Conversation ID or null if no value. + * @actionssdk + */ + getConversationId(): string; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, the client library will + * automatically handle the incoming intents. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case app.StandardIntents.MAIN: + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.'); + * app.ask(inputPrompt); + * break; + * + * case app.StandardIntents.TEXT: + * app.tell('You said ' + app.getRawInput()); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return Intent id or null if no value. + * @actionssdk + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is not a text argument, the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @actionssdk + */ + getArgument(argName: string): string; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, pickOption); + * actionMap.set(app.StandardIntents.OPTION, optionPicked); + * + * app.handleRequest(actionMap); + * + * @return Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @actionssdk + */ + getSelectedOption(): string; + + /** + * Asks to collect user's input; all user's queries need to be sent to + * the app. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by App. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): express.Response | null; + + /** + * Asks to collect user's input with a list. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithlist('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param list List built with {@link AssistantApp#buildList|buildList}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): express.Response | null; + + /** + * Asks to collect user's input with a carousel. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.TEXT, welcomeIntent); + * actionMap.set(app.StandardIntents.OPTION, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt Holding initial and + * no-input prompts. Cannot contain basic card. + * @param carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return The response that is sent to Assistant to ask user to provide input. + * @actionssdk + */ + askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): express.Response | null; + + /** + * Tells Assistant to render the speech response and close the mic. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * @param textToSpeech Final response. + * Spoken response can be SSML. + * @return The HTTP response that is sent back to Assistant. + * @actionssdk + */ + tell(textToSpeech: string | SimpleResponse | RichResponse): express.Response | null; + + /** + * Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object} + * from initial prompt and no-input prompts. + * + * The App needs one initial prompt to start the conversation. If there is no user response, + * the App re-opens the mic and renders the no-input prompts three times + * (one for each no-input prompt that was configured) to help the user + * provide the right response. + * + * Note: we highly recommend app to provide all the prompts required here in order to ensure a + * good user experience. + * + * @example + * const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'What is the number?']); + * app.ask(inputPrompt); + * + * @param isSsml Indicates whether the text to speech is SSML or not. + * @param initialPrompt The initial prompt the App asks the user. + * @param noInputs Array of re-prompts when the user does not respond (max 3). + * @return. + * @actionssdk + */ + buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs?: string[]): object; +} diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts new file mode 100644 index 0000000000..caed5cf6cb --- /dev/null +++ b/types/actions-on-google/assistant-app.d.ts @@ -0,0 +1,1475 @@ +import * as express from 'express'; + +import { BasicCard, Carousel, List, OptionItem, RichResponse } from './response-builder'; +import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, LineItem, + Location, Order, OrderUpdate, TransactionDecision, TransactionValues } from './transactions'; + +/** + * List of standard intents that the app provides. + * @actionssdk + * @dialogflow + */ +export enum StandardIntents { + /** App fires MAIN intent for queries like [talk to $app]. */ + MAIN, + /** App fires TEXT intent when action issues ask intent. */ + TEXT, + /** App fires PERMISSION intent when action invokes askForPermission. */ + PERMISSION, + /** App fires OPTION intent when user chooses from options provided. */ + OPTION, + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ + TRANSACTION_REQUIREMENTS_CHECK, + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ + DELIVERY_ADDRESS, + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ + TRANSACTION_DECISION, + /** App fires CONFIRMATION intent when requesting affirmation from user. */ + CONFIRMATION, + /** App fires DATETIME intent when requesting date/time from user. */ + DATETIME, + /** App fires SIGN_IN intent when requesting sign-in from user. */ + SIGN_IN, + /** App fires NO_INPUT intent when user doesn't provide input. */ + NO_INPUT, + /** App fires CANCEL intent when user exits app mid-dialog. */ + CANCEL, + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ + NEW_SURFACE, + /** App fires REGISTER_UPDATE intent when requesting the user to register for proactive updates. */ + REGISTER_UPDATE, + /** App receives CONFIGURE_UPDATES intent to indicate a custom REGISTER_UPDATE intent should be sent. */ + CONFIGURE_UPDATES +} + +/** + * List of supported permissions the app supports. + * @actionssdk + * @dialogflow + */ +export enum SupportedPermissions { + /** + * The user's name as defined in the + * {@link https://developers.google.com/actions/reference/conversation#UserProfile|UserProfile object} + */ + NAME, + /** + * The location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_PRECISE_LOCATION, + /** + * City and zipcode corresponding to the location of the user's current device, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. + */ + DEVICE_COARSE_LOCATION, + /** + * Confirmation to receive proactive content at any time from the app. + */ + UPDATE +} + +/** + * List of built-in argument names. + * @actionssdk + * @dialogflow + */ +export enum BuiltInArgNames { + /** + * Permission granted argument. + */ + PERMISSION_GRANTED, + /** + * Option selected argument. + */ + OPTION, + /** + * Transaction requirements check result argument. + */ + TRANSACTION_REQ_CHECK_RESULT, + /** + * Delivery address value argument. + */ + DELIVERY_ADDRESS_VALUE, + /** + * Transactions decision argument. + */ + TRANSACTION_DECISION_VALUE, + /** + * Confirmation argument. + */ + CONFIRMATION, + /** + * DateTime argument. + */ + DATETIME, + /** + * Sign in status argument. + */ + SIGN_IN, + /** + * Reprompt count for consecutive NO_INPUT intents. + */ + REPROMPT_COUNT, + /** + * Flag representing finality of NO_INPUT intent. + */ + IS_FINAL_REPROMPT, + /** + * New surface value argument. + */ + NEW_SURFACE, + /** Update registration value argument. */ + REGISTER_UPDATE +} + +/** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. + */ +export type ConversationStages = ConversationTypes; + +/** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ +export enum ConversationTypes { + /** + * Unspecified conversation state. + */ + UNSPECIFIED, + /** + * A new conversation. + */ + NEW, + /** + * An active (ongoing) conversation. + */ + ACTIVE, +} + +/** + * List of surface capabilities supported by the app. + * @actionssdk + * @dialogflow + */ +export enum SurfaceCapabilities { + /** + * The ability to output audio. + */ + AUDIO_OUTPUT, + /** + * The ability to output on a screen + */ + SCREEN_OUTPUT, +} + +/** + * List of possible user input types. + * @actionssdk + * @dialogflow + */ +export enum InputTypes { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Input given by touch. + */ + TOUCH, + /** + * Input given by voice (spoken). + */ + VOICE, + /** + * Input given by keyboard (typed). + */ + KEYBOARD +} + +/** + * List of possible sign in result status values. + * @actionssdk + * @dialogflow + */ +export enum SignInStatus { + /** + * Unknown status. + */ + UNSPECIFIED, + /** + * User successfully completed the account linking. + */ + OK, + /** + * Cancelled or dismissed account linking. + */ + CANCELLED, + /** + * System or network error. + */ + ERROR +} + +/** + * Possible update trigger time context frequencies. + */ +export enum TimeContextFrequency { + DAILY +} + +/** + * User provided date/time info. + */ +export interface DateTime { + date: { + year: number; + month: number; + day: number; + }; + time: { + hours: number; + minutes: number; + seconds: number; + nanos: number; + }; +} + +/** + * User's permissioned name info. + */ +export interface UserName { + /** User's display name. */ + displayName: string; + /** User's given name. */ + givenName: string; + /** User's family name. */ + familyName: string; +} + +/** + * User's permissioned device location. + */ +export interface DeviceLocation { + /** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + coordinates: object; + /** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + address: string; + /** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + zipCode: string; + /** Device city. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ + city: string; +} + +/** + * User object. + */ +export interface User { + /** Random string ID for Google user. */ + userId: string; + /** User name information. Null if not requested with {@link AssistantApp#askForPermission|askForPermission(SupportedPermissions.NAME)}. */ + userName: UserName; + /** Unique Oauth2 token. Only available with account linking. */ + accessToken: string; + /** + * Timestamp for the last access from the user. + * Retrieve using app.getLastSeen() to get a Date object or null if never seen. + */ + lastSeen: string; + /** + * A string persistent across sessions. + * Retrieved and set using app.userStorage which allows you to store it like an JSON object + * which is abstracted for convenience by the client library. + */ + userStorage: string; +} + +/** + * Actions on Google Surface. + */ +export interface Surface { + /** Capabilities of the surface. */ + capabilities: Capability[]; +} + +/** + * Surface capability. + */ +export interface Capability { + /** Name of the capability. */ + name: string; +} + +/** + * Intent Argument. For incoming intents, the argument value can be retrieved + * using {@link AssistantApp#getArgument}. + */ +export interface IntentArgument { + /** Name of the argument. */ + name: string; + /** Text value of the argument. */ + textValue: string; +} + +/** + * The Actions on Google client library AssistantApp base class. + * + * This class contains the methods that are shared between platforms to support the conversation API + * protocol from Assistant. It also exports the 'State' class as a helper to represent states by + * name. + */ +export class AssistantApp { + /** + * The session state. + */ + state: string; + + /** + * The session data in JSON format. + */ + data: object; + + /** + * The data persistent across sessions in JSON format. + * It exists in the same context as getUser().userId + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + * // Dialogflow + * const app = new DialogflowApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + */ + userStorage: object; + + /** + * List of standard intents that the app provides. + * @actionssdk + * @dialogflow + */ + readonly StandardIntents: typeof StandardIntents; + + /** + * List of supported permissions the app supports. + * @actionssdk + * @dialogflow + */ + readonly SupportedPermissions: typeof SupportedPermissions; + + /** + * List of built-in argument names. + * @actionssdk + * @dialogflow + */ + readonly BuiltInArgNames: typeof BuiltInArgNames; + + /** + * List of possible conversation stages, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. + */ + readonly ConversationStages: typeof ConversationTypes; + + /** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ + readonly ConversationTypes: typeof ConversationTypes; + + /** + * List of surface capabilities supported by the app. + * @actionssdk + * @dialogflow + */ + readonly SurfaceCapabilities: typeof SurfaceCapabilities; + + /** + * List of possible user input types. + * @actionssdk + * @dialogflow + */ + readonly InputTypes: typeof InputTypes; + + /** + * List of possible sign in result status values. + * @actionssdk + * @dialogflow + */ + readonly SignInStatus: typeof SignInStatus; + + /** + * Values related to supporting {@link Transactions}. + */ + readonly Transactions: typeof TransactionValues; + + /** + * Possible update trigger time context frequencies. + */ + readonly TimeContextFrequency: typeof TimeContextFrequency; + + // --------------------------------------------------------------------------- + // Public APIs + // --------------------------------------------------------------------------- + + /** + * Handles the incoming Assistant request using a handler or Map of handlers. + * Each handler can be a function callback or Promise. + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * + * function mainIntent (app) { + * const inputPrompt = app.buildInputPrompt(true, 'Hi! ' + + * 'I can read out an ordinal like ' + + * '123. Say a number.', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * + * function rawInput (app) { + * if (app.getRawInput() === 'bye') { + * app.tell('Goodbye!'); + * } else { + * const inputPrompt = app.buildInputPrompt(true, 'You said, ' + + * app.getRawInput() + '', + * ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']); + * app.ask(inputPrompt); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, mainIntent); + * actionMap.set(app.StandardIntents.TEXT, rawInput); + * + * app.handleRequest(actionMap); + * + * // Dialogflow + * const app = new DialogflowApp({request: req, response: res}); + * const NAME_ACTION = 'make_name'; + * const COLOR_ARGUMENT = 'color'; + * const NUMBER_ARGUMENT = 'number'; + * + * function makeName (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * const color = app.getArgument(COLOR_ARGUMENT); + * app.tell('Alright, your silly name is ' + + * color + ' ' + number + + * '! I hope you like it. See you next time.'); + * } + * + * const actionMap = new Map(); + * actionMap.set(NAME_ACTION, makeName); + * app.handleRequest(actionMap); + * + * @param handler The handler (or Map of handlers) for the request. + * @actionssdk + * @dialogflow + */ + handleRequest(handler: ((app: AssistantApp) => any) | (Map any>)): void; + + /** + * Equivalent to {@link AssistantApp#askForPermission|askForPermission}, + * but allows you to prompt the user for more than one permission at once. + * + * Notes: + * + * * The order in which you specify the permission prompts does not matter - + * it is controlled by the Assistant to provide a consistent user experience. + * * The user will be able to either accept all permissions at once, or none. + * If you wish to allow them to selectively accept one or other, make several + * dialog turns asking for each permission independently with askForPermission. + * * Asking for DEVICE_COARSE_LOCATION and DEVICE_PRECISE_LOCATION at once is + * equivalent to just asking for DEVICE_PRECISE_LOCATION + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]; + * app.askForPermissions('To pick you up', permissions); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * const address = app.getDeviceLocation().address; + * app.tell('I will tell your driver to pick up ' + displayName + + * ' at ' + address); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out where to pick you up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param context Context why the permission is being asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param permissions Array of permissions App supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermissions(context: string, permissions: string[], dialogState?: object): express.Response | null; + + /** + * Prompts the user for permission to send proactive updates at any time. + * + * @example + * const app = new DialogflowApp({request, response}); + * const REQUEST_PERMISSION_ACTION = 'request.permission'; + * const PERMISSION_REQUESTED = 'permission.requested'; + * const SHOW_IMAGE = 'show.image'; + * + * function requestPermission (app) { + * app.askForUpdatePermission('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function checkPermission (app) { + * if (app.isPermissionGranted()) { + * app.tell(`Great, I'll send an update whenever I notice a change`); + * } else { + * // Response shows that user did not grant permission + * app.tell('Alright, just let me know whenever you need the weather!'); + * } + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(PERMISSION_REQUESTED, checkPermission); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForUpdatePermission(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + + /** + * Checks whether user is in transactable state. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_REQ_COMPLETE = 'txn.req.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * function welcomeIntent (app) { + * app.askForTransactionRequirements(transactionConfig); + * } + * + * function txnReqCheck (app) { + * if (app.getTransactionRequirementsResult() === app.Transactions.ResultType.OK) { + * // continue cart building flow + * } else { + * // don't continue cart building + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_REQ_COMPLETE, txnReqCheck); + * app.handleRequest(actionMap); + * + * @param + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. Optional if order has no payment or + * delivery. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForTransactionRequirements(transactionConfig?: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): express.Response | null; + + /** + * Asks user to confirm transaction information. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const TXN_COMPLETE = 'txn.complete'; + * + * let transactionConfig = { + * deliveryAddressRequired: false, + * type: app.Transactions.PaymentType.BANK, + * displayName: 'Checking-1234' + * }; + * + * let order = app.buildOrder(); + * // fill order cart + * + * function welcomeIntent (app) { + * app.askForTransaction(order, transactionConfig); + * } + * + * function txnComplete (app) { + * // respond with order update + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(TXN_COMPLETE, txnComplete); + * app.handleRequest(actionMap); + * + * @param order Order built with buildOrder(). + * @param + * transactionConfig Configuration for the transaction. Includes payment + * options and order options. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response + * @dialogflow + */ + askForTransactionDecision(order: Order, transactionConfig: ActionPaymentTransactionConfig | GooglePaymentTransactionConfig, dialogState?: object): express.Response | null; + + /** + * Asks the Assistant to guide the user to grant a permission. For example, + * if you want your app to get access to the user's name, you would invoke + * the askForPermission method with a context containing the reason for the request, + * and the AssistantApp.SupportedPermissions.NAME permission. With this, the Assistant will ask + * the user, in your agent's voice, the following: '[Context with reason for the request], + * I'll just need to get your name from Google, is that OK?'. + * + * Once the user accepts or denies the request, the Assistant will fire another intent: + * assistant.intent.action.PERMISSION with a boolean argument: AssistantApp.BuiltInArgNames.PERMISSION_GRANTED + * and, if granted, the information that you requested. + * + * Read more: + * + * * {@link https://developers.google.com/actions/reference/conversation#ExpectedIntent|Supported Permissions} + * * Check if the permission has been granted with {@link AssistantApp#isPermissionGranted|isPermissionsGranted} + * * {@link AssistantApp#getDeviceLocation|getDeviceLocation} + * * {@link AssistantApp#getUserName|getUserName} + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const GET_RIDE_ACTION = 'get_ride'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To pick you up', permission); + * } + * + * function sendRide (app) { + * if (app.isPermissionGranted()) { + * const displayName = app.getUserName().displayName; + * app.tell('I will tell your driver to pick up ' + displayName); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not figure out who to pick up.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(GET_RIDE_ACTION, sendRide); + * app.handleRequest(actionMap); + * + * @param context Context why permission is asked; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param permission One of the permissions Assistant supports, each of + * which comes from AssistantApp.SupportedPermissions. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return A response is sent to the Assistant to ask for the user's permission; + * for any invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForPermission(context: string, permission: string, dialogState?: object): express.Response | null; + + /** + * Returns true if the request follows a previous request asking for + * permission from the user and the user granted the permission(s). Otherwise, + * false. Use with {@link AssistantApp#askForPermissions|askForPermissions}. + * + * @example + * const app = new ActionsSdkApp({request: request, response: response}); + * // or + * const app = new DialogflowApp({request: request, response: response}); + * app.askForPermissions("To get you a ride", [ + * app.SupportedPermissions.NAME, + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION + * ]); + * // ... + * // In response handler for subsequent intent: + * if (app.isPermissionGranted()) { + * // Use the requested permission(s) to get the user a ride + * } + * + * @return true if permissions granted. + * @dialogflow + * @actionssdk + */ + isPermissionGranted(): boolean; + + /** + * Asks user for delivery address. + * + * @example + * // For DialogflowApp: + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const DELIVERY_INTENT = 'delivery.address'; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * // For ActionsSdkApp: + * const app = new ActionsSdkApp({request, response}); + * const WELCOME_INTENT = app.StandardIntents.MAIN; + * const DELIVERY_INTENT = app.StandardIntents.DELIVERY_ADDRESS; + * + * function welcomeIntent (app) { + * app.askForDeliveryAddress('To make sure I can deliver to you'); + * } + * + * function addressIntent (app) { + * const postalCode = app.getDeliveryAddress().postalAddress.postalCode; + * if (isInDeliveryZone(postalCode)) { + * app.tell('Great looks like you\'re in our delivery area!'); + * } else { + * app.tell('I\'m sorry it looks like we can\'t deliver to you.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DELIVERY_INTENT, addressIntent); + * app.handleRequest(actionMap); + * + * @param reason Reason given to user for asking delivery address. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForDeliveryAddress(reason: string, dialogState?: object): express.Response | null; + + /** + * Asks user for a confirmation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const CONFIRMATION = 'confirmation'; + * + * function welcomeIntent (app) { + * app.askForConfirmation('Are you sure you want to do that?'); + * } + * + * function confirmation (app) { + * if (app.getUserConfirmation()) { + * app.tell('Great! I\'m glad you want to do it!'); + * } else { + * app.tell('That\'s okay. Let\'s not do it now.'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(CONFIRMATION, confirmation); + * app.handleRequest(actionMap); + * + * @param prompt The confirmation prompt presented to the user to + * query for an affirmative or negative response. If undefined or null, + * Google will use a generic yes/no prompt. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForConfirmation(prompt?: string, dialogState?: object): express.Response | null; + + /** + * Asks user for a timezone-agnostic date and time. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const DATETIME = 'datetime'; + * + * function welcomeIntent (app) { + * app.askForDateTime('When do you want to come in?', + * 'Which date works best for you?', + * 'What time of day works best for you?'); + * } + * + * function datetime (app) { + * app.tell({speech: 'Great see you at your appointment!', + * displayText: 'Great, we will see you on ' + * + app.getDateTime().date.month + * + '/' + app.getDateTime().date.day + * + ' at ' + app.getDateTime().time.hours + * + (app.getDateTime().time.minutes || '')}); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(DATETIME, datetime); + * app.handleRequest(actionMap); + * + * @param initialPrompt The initial prompt used to ask for a + * date and time. If undefined or null, Google will use a generic + * prompt. + * @param datePrompt The prompt used to specifically ask for the + * date if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param timePrompt The prompt used to specifically ask for the + * time if not provided by user. If undefined or null, Google will use a + * generic prompt. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForDateTime(initialPrompt?: string, datePrompt?: string, timePrompt?: string, dialogState?: object): express.Response | null; + + /** + * Hands the user off to a web sign in flow. App sign in and OAuth credentials + * are set in the {@link https://console.actions.google.com|Actions Console}. + * Retrieve the access token in subsequent intents using + * app.getUser().accessToken. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SIGN_IN = 'sign.in'; + * + * function welcomeIntent (app) { + * app.askForSignIn(); + * } + * + * function signIn (app) { + * if (app.getSignInStatus() === app.SignInstatus.OK) { + * let accessToken = app.getUser().accessToken; + * app.ask('Great, thanks for signing in!'); + * } else { + * app.ask('I won\'t be able to save your data, but let\'s continue!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SIGN_IN, signIn); + * app.handleRequest(actionMap); + * + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @actionssdk + * @dialogflow + */ + askForSignIn(dialogState?: object): express.Response | null; + + /** + * Requests the user to switch to another surface during the conversation. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * showPicture(app); + * } else if (app.hasAvailableSurfaceCapabilities(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askForNewSurface('To show you an image', + * 'Check out this image', + * [app.SurfaceCapabilities.SCREEN_OUTPUT] + * ); + * } else { + * app.tell('This part of the app only works on screen devices. Sorry about that'); + * } + * } + * + * function showImage (app) { + * if (!app.isNewSurface()) { + * app.tell('Ok, I understand. You don't want to see pictures. Bye'); + * } else { + * showPicture(app, pictureType); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param context Context why new surface is requested; it's the TTS + * prompt prefix (action phrase) we ask the user. + * @param notificationTitle Title of the notification appearing on + * new surface device. + * @param capabilities The list of capabilities required in + * the surface. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askForNewSurface(context: string, notificationTitle: string, capabilities: SurfaceCapabilities[], dialogState?: object): express.Response | null; + + /** + * Requests the user to register for daily updates. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * app.askToRegisterDailyUpdate('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + + /** + * Gets the {@link User} object. + * The user object contains information about the user, including + * a string identifier and personal information (requires requesting permissions, + * see {@link AssistantApp#askForPermissions|askForPermissions}). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * // or + * const app = new ActionsSdkApp({request: request, response: response}); + * const userId = app.getUser().userId; + * + * @return Null if no value. + * @actionssdk + * @dialogflow + */ + getUser(): User; + + /** + * If granted permission to user's name in previous intent, returns user's + * display name, family name, and given name. If name info is unavailable, + * returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const REQUEST_PERMISSION_ACTION = 'request_permission'; + * const SAY_NAME_ACTION = 'get_name'; + * + * function requestPermission (app) { + * const permission = app.SupportedPermissions.NAME; + * app.askForPermission('To know who you are', permission); + * } + * + * function sayName (app) { + * if (app.isPermissionGranted()) { + * app.tell('Your name is ' + app.getUserName().displayName)); + * } else { + * // Response shows that user did not grant permission + * app.tell('Sorry, I could not get your name.'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(SAY_NAME_ACTION, sayName); + * app.handleRequest(actionMap); + * @return Null if name permission is not granted. + * @actionssdk + * @dialogflow + */ + getUserName(): UserName; + + /** + * Gets the user locale. Returned string represents the regional language + * information of the user set in their Assistant settings. + * For example, 'en-US' represents US English. + * + * @example + * const app = new DialogflowApp({request, response}); + * const locale = app.getUserLocale(); + * + * @return User's locale, e.g. 'en-US'. Null if no locale given. + * @actionssdk + * @dialogflow + */ + getUserLocale(): string; + + /** + * Get the user's last seen time as a Date object. + * Not supported in V1. + * + * @example + * const app = new DialogflowApp({request, response}); + * const lastSeen = app.getLastSeen(); + * + * @return User's last seen date or null if never seen + */ + getLastSeen(): Date | null; + + /** + * If granted permission to device's location in previous intent, returns device's + * location (see {@link AssistantApp#askForPermissions|askForPermissions}). + * If device info is unavailable, returns null. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * // or + * const app = new ActionsSdkApp({request: req, response: res}); + * app.askForPermission("To get you a ride", + * app.SupportedPermissions.DEVICE_PRECISE_LOCATION); + * // ... + * // In response handler for permissions fallback intent: + * if (app.isPermissionGranted()) { + * sendCarTo(app.getDeviceLocation().coordinates); + * } + * + * @return Null if location permission is not granted. + * @actionssdk + * @dialogflow + */ + getDeviceLocation(): DeviceLocation; + + /** + * Gets type of input used for this request. + * @return One of AssistantApp.InputTypes. + * Null if no input type given. + * @dialogflow + * @actionssdk + */ + getInputType(): number | string; + + /** + * Get the argument value by name from the current intent. + * If the argument is included in originalRequest, and is not a text argument, + * the entire argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @dialogflow + * @actionssdk + */ + getArgumentCommon(argName: string): object; + + /** + * Gets transactability of user. Only use after calling + * askForTransactionRequirements. Null if no result given. + * + * @return One of Transactions.ResultType. + * @dialogflow + * @actionssdk + */ + getTransactionRequirementsResult(): string; + + /** + * Gets order delivery address. Only use after calling askForDeliveryAddress. + * + * @return Delivery address information. Null if user + * denies permission, or no address given. + * @dialogflow + * @actionssdk + */ + getDeliveryAddress(): Location; + + /** + * Gets transaction decision information. Only use after calling + * askForTransactionDecision. + * + * @return Transaction decision data. Returns object with + * userDecision only if user declines. userDecision will be one of + * Transactions.ConfirmationDecision. Null if no decision given. + * @dialogflow + * @actionssdk + */ + getTransactionDecision(): TransactionDecision; + + /** + * Gets confirmation decision. Use after askForConfirmation. + * + * @return False if user replied with negative response. Null if no user + * confirmation decision given. + * @dialogflow + * @actionssdk + */ + getUserConfirmation(): boolean | null; + + /** + * Gets user provided date and time. Use after askForDateTime. + * + * @return Date and time given by the user. Null if no user + * date and time given. + * @dialogflow + * @actionssdk + */ + getDateTime(): DateTime; + + /** + * Gets status of user sign in request. + * + * @return Result of user sign in request. One of + * DialogflowApp.SignInStatus or ActionsSdkApp.SignInStatus + * Null if no sign in status. + * @dialogflow + * @actionssdk + */ + getSignInStatus(): string; + + /** + * Returns true if user device has a given surface capability. + * + * @param requestedCapability Must be one of {@link SurfaceCapabilities}. + * @return True if user device has the given capability. + * + * @example + * const app = new DialogflowApp({request: req, response: res}); + * const DESCRIBE_SOMETHING = 'DESCRIBE_SOMETHING'; + * + * function describe (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.tell(richResponseWithBasicCard); + * } else { + * app.tell('Let me tell you about ...'); + * } + * } + * const actionMap = new Map(); + * actionMap.set(DESCRIBE_SOMETHING, describe); + * app.handleRequest(actionMap); + * + * @dialogflow + * @actionssdk + */ + hasSurfaceCapability(requestedCapability: SurfaceCapabilities): boolean; + + /** + * Gets surface capabilities of user device. + * + * @return Supported surface capabilities, as defined in + * AssistantApp.SurfaceCapabilities. + * @dialogflow + * @actionssdk + */ + getSurfaceCapabilities(): string[]; + + /** + * Returns the set of other available surfaces for the user. + * + * @return Empty if no available surfaces. + * @actionssdk + * @dialogflow + */ + getAvailableSurfaces(): Surface[]; + + /** + * Returns true if user has an available surface which includes all given + * capabilities. Available surfaces capabilities may exist on surfaces other + * than that used for an ongoing conversation. + * + * @param capabilities Must be one of + * {@link SurfaceCapabilities}. + * @return True if user has a capability available on some surface. + * + * @dialogflow + * @actionssdk + */ + hasAvailableSurfaceCapabilities(capabilities: SurfaceCapabilities | SurfaceCapabilities[]): boolean; + + /** + * Returns the result of the AskForNewSurface helper. + * + * @return True if user has triggered conversation on a new device + * following the NEW_SURFACE intent. + * @actionssdk + * @dialogflow + */ + isNewSurface(): boolean; + + /** + * Returns true if the app is being tested in sandbox mode. Enable sandbox + * mode in the (Actions console)[console.actions.google.com] to test + * transactions. + * + * @return True if app is being used in Sandbox mode. + * @dialogflow + * @actionssdk + */ + isInSandbox(): boolean; + + /** + * Returns the number of subsequent reprompts related to silent input from the + * user. This should be used along with the NO_INPUT intent to reprompt the + * user for input in cases where the Google Assistant could not pick up any + * speech. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return The current reprompt count. Null if no reprompt count + * available (e.g. not in the NO_INPUT intent). + * @dialogflow + * @actionssdk + */ + getRepromptCount(): number; + + /** + * Returns true if it is the final reprompt related to silent input from the + * user. This should be used along with the NO_INPUT intent to give the final + * response to the user after multiple silences and should be an app.tell + * which ends the conversation. + * + * @example + * const app = new ActionsSdkApp({request, response}); + * + * function welcome (app) { + * app.ask('Welcome to your app!'); + * } + * + * function noInput (app) { + * if (app.getRepromptCount() === 0) { + * app.ask(`What was that?`); + * } else if (app.getRepromptCount() === 1) { + * app.ask(`Sorry I didn't catch that. Could you repeat yourself?`); + * } else if (app.isFinalReprompt()) { + * app.tell(`Okay let's try this again later.`); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(app.StandardIntents.MAIN, welcome); + * actionMap.set(app.StandardIntents.NO_INPUT, noInput); + * app.handleRequest(actionMap); + * + * @return True if in a NO_INPUT intent and this is the final turn + * of dialog. + * @dialogflow + * @actionssdk + */ + isFinalReprompt(): boolean; + + /** + * Returns true if user accepted update registration request. Used with + * {@link AssistantApp#askToRegisterDailyUpdate} + * + * @return True if user accepted update registration request. + * @dialogflow + * @actionssdk + */ + isUpdateRegistered(): boolean; + + // --------------------------------------------------------------------------- + // Response Builders + // --------------------------------------------------------------------------- + + /** + * Constructs RichResponse with chainable property setters. + * + * @param richResponse RichResponse to clone. + * @return Constructed RichResponse. + */ + buildRichResponse(richResponse?: RichResponse): RichResponse; + + /** + * Constructs BasicCard with chainable property setters. + * + * @param bodyText Body text of the card. Can be set using setTitle + * instead. + * @return Constructed BasicCard. + */ + buildBasicCard(bodyText?: string): BasicCard; + + /** + * Constructs List with chainable property setters. + * + * @param title A title to set for a new List. + * @return Constructed List. + */ + buildList(title?: string): List; + + /** + * Constructs Carousel with chainable property setters. + * + * @return Constructed Carousel. + */ + buildCarousel(): Carousel; + + /** + * Constructs OptionItem with chainable property setters. + * + * @param key A unique key to identify this option. This key will + * be returned as an argument in the resulting actions.intent.OPTION + * intent. + * @param synonyms A list of synonyms which the user may + * use to identify this option instead of the option key. + * @return Constructed OptionItem. + */ + buildOptionItem(key?: string, synonyms?: string | string[]): OptionItem; + + // --------------------------------------------------------------------------- + // Transaction Builders + // --------------------------------------------------------------------------- + + /** + * Constructs Order with chainable property setters. + * + * @param orderId Unique identifier for the order. + * @return Constructed Order. + */ + buildOrder(orderId: string): Order; + + /** + * Constructs Cart with chainable property setters. + * + * @param cartId Unique identifier for the cart. + * @return Constructed Cart. + */ + buildCart(cartId?: string): Cart; + + /** + * Constructs LineItem with chainable property setters. + * Because of a previous bug, the parameters are swapped compared to + * the LineItem constructor to prevent a breaking change. + * + * @param name Name of the line item. + * @param id Unique identifier for the item. + * @return Constructed LineItem. + */ + buildLineItem(name: string, id: string): LineItem; + + /** + * Constructs OrderUpdate with chainable property setters. + * + * @param orderId Unique identifier of the order. + * @param isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + * @return Constructed OrderUpdate. + */ + buildOrderUpdate(orderId: string, isGoogleOrderId: boolean): OrderUpdate; +} diff --git a/types/actions-on-google/dialogflow-app.d.ts b/types/actions-on-google/dialogflow-app.d.ts new file mode 100644 index 0000000000..ab768241c2 --- /dev/null +++ b/types/actions-on-google/dialogflow-app.d.ts @@ -0,0 +1,571 @@ +import * as express from 'express'; + +import { AssistantApp } from './assistant-app'; +import { Carousel, List, RichResponse, SimpleResponse } from './response-builder'; + +// --------------------------------------------------------------------------- +// Dialogflow support +// --------------------------------------------------------------------------- + +/** + * Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}. + */ +export interface Context { + /** Full name of the context. */ + name: string; + /** + * Parameters carried within this context. + * See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}. + */ + parameters: object; + /** Remaining number of intents */ + lifespan: number; +} + +export interface DialogflowAppOptions { + /** Express HTTP request object. */ + request: express.Request; + /** Express HTTP response object. */ + response: express.Response; + /** + * Function callback when session starts. + * Only called if webhook is enabled for welcome/triggering intents, and + * called from Web Simulator or Google Home device (i.e., not Dialogflow simulator). + */ + sessionStarted?(): any; +} + +/** + * This is the class that handles the communication with Dialogflow's fulfillment API. + */ +export class DialogflowApp extends AssistantApp { + /** + * Constructor for DialogflowApp object. + * To be used in the Dialogflow fulfillment webhook logic. + * + * @example + * const DialogflowApp = require('actions-on-google').DialogflowApp; + * const app = new DialogflowApp({request: request, response: response, + * sessionStarted:sessionStarted}); + * + * @dialogflow + */ + constructor(options: DialogflowAppOptions); + + /** + * @deprecated + * Verifies whether the request comes from Dialogflow. + * + * @param key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param value The private value specified by the developer inside the + * fulfillment header. + * @return True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromApiAi(key: string, value: string): boolean; + + /** + * Verifies whether the request comes from Dialogflow. + * + * @param key The header key specified by the developer in the + * Dialogflow Fulfillment settings of the app. + * @param value The private value specified by the developer inside the + * fulfillment header. + * @return True if the request comes from Dialogflow. + * @dialogflow + */ + isRequestFromDialogflow(key: string, value: string): boolean; + + /** + * Get the current intent. Alternatively, using a handler Map with + * {@link AssistantApp#handleRequest|handleRequest}, + * the client library will automatically handle the incoming intents. + * 'Intent' in the Dialogflow context translates into the current action. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * + * function responseHandler (app) { + * const intent = app.getIntent(); + * switch (intent) { + * case WELCOME_INTENT: + * app.ask('Welcome to action snippets! Say a number.'); + * break; + * + * case NUMBER_INTENT: + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * break; + * } + * } + * + * app.handleRequest(responseHandler); + * + * @return Intent id or null if no value (action name). + * @dialogflow + */ + getIntent(): string; + + /** + * Get the argument value by name from the current intent. If the argument + * is included in originalRequest, and is not a text argument, the entire + * argument object is returned. + * + * Note: If incoming request is using an API version under 2 (e.g. 'v1'), + * the argument object will be in Proto2 format (snake_case, etc). + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param argName Name of the argument. + * @return Argument value matching argName + * or null if no matching argument. + * @dialogflow + */ + getArgument(argName: string): object; + + /** + * Get the context argument value by name from the current intent. Context + * arguments include parameters collected in previous intents during the + * lifespan of the given context. If the context argument has an original + * value, usually representing the underlying entity value, that will be given + * as part of the return object. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * const OUT_CONTEXT = 'output_context'; + * const NUMBER_ARG = 'myNumberArg'; + * + * function welcomeIntent (app) { + * const parameters = {}; + * parameters[NUMBER_ARG] = '42'; + * app.setContext(OUT_CONTEXT, 1, parameters); + * app.ask('Welcome to action snippets! Ask me for your number.'); + * } + * + * function numberIntent (app) { + * const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG); + * // number === { value: 42 } + * app.tell('Your number is ' + number.value); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param contextName Name of the context. + * @param argName Name of the argument. + * @return Object containing value property and optional original + * property matching context argument. Null if no matching argument. + * @dialogflow + */ + getContextArgument(contextName: string, argName: string): object; + + /** + * Returns the RichResponse constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function tellFact (app) { + * let fact = 'Google was founded in 1998'; + * + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' + + * 'fact for you. ' + fact + ' Which one do you want to hear about ' + + * 'next, Google\'s history or headquarters?')); + * } else { + * app.ask('Here\'s a fact for you. ' + fact + ' Which one ' + + * 'do you want to hear about next, Google\'s history or headquarters?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('tell.fact', tellFact); + * + * app.handleRequest(actionMap); + * + * @return RichResponse created in Dialogflow. If no RichResponse was + * created, an empty RichResponse is returned. + * @dialogflow + */ + getIncomingRichResponse(): RichResponse; + + /** + * Returns the List constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithList('Which of these looks good?', + * app.getIncomingList().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return List created in Dialogflow. If no List was created, an empty + * List is returned. + * @dialogflow + */ + getIncomingList(): List; + + /** + * Returns the Carousel constructed in Dialogflow response builder. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * + * app.handleRequest(actionMap); + * + * @return Carousel created in Dialogflow. If no Carousel was created, + * an empty Carousel is returned. + * @dialogflow + */ + getIncomingCarousel(): Carousel; + + /** + * Returns the option key user chose from options response. + * + * @example + * const app = new App({request: req, response: res}); + * + * function pickOption (app) { + * if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) { + * app.askWithCarousel('Which of these looks good?', + * app.getIncomingCarousel().addItems( + * app.buildOptionItem('another_choice', ['Another choice']). + * setTitle('Another choice').setDescription('Choose me!'))); + * } else { + * app.ask('What would you like?'); + * } + * } + * + * function optionPicked (app) { + * app.ask('You picked ' + app.getSelectedOption()); + * } + * + * const actionMap = new Map(); + * actionMap.set('pick.option', pickOption); + * actionMap.set('option.picked', optionPicked); + * + * app.handleRequest(actionMap); + * + * @return Option key of selected item. Null if no option selected or + * if current intent is not OPTION intent. + * @dialogflow + */ + getSelectedOption(): string; + + /** + * Asks to collect the user's input. + * {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}. + * + * NOTE: Due to a bug, if you specify the no-input prompts, + * the mic is closed after the 3rd prompt, so you should use the 3rd prompt + * for a bye message until the bug is fixed. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.', + * ['Say any number', 'Pick a number', 'We can stop here. See you soon.']); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param noInputs Array of re-prompts when the user does not respond (max 3). + * @return HTTP response. + * @dialogflow + */ + ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): express.Response | null; + + /** + * Asks to collect the user's input with a list. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithList('Which of these looks good?', + * app.buildList('List title') + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Title of First List Item'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Title of Second List Item'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param.list List built with {@link AssistantApp#buildList|buildList} + * @return HTTP response. + * @dialogflow + */ + askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): express.Response | null; + + /** + * Asks to collect the user's input with a carousel. + * + * @example + * const app = new DialogflowApp({request, response}); + * const WELCOME_INTENT = 'input.welcome'; + * const OPTION_INTENT = 'option.select'; + * + * function welcomeIntent (app) { + * app.askWithCarousel('Which of these looks good?', + * app.buildCarousel() + * .addItems([ + * app.buildOptionItem(SELECTION_KEY_ONE, + * ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2']) + * .setTitle('Number one'), + * app.buildOptionItem(SELECTION_KEY_TWO, + * ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2']) + * .setTitle('Number two'), + * ])); + * } + * + * function optionIntent (app) { + * if (app.getSelectedOption() === SELECTION_KEY_ONE) { + * app.tell('Number one is a great choice!'); + * } else { + * app.tell('Number two is a great choice!'); + * } + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(OPTION_INTENT, optionIntent); + * app.handleRequest(actionMap); + * + * @param inputPrompt The input prompt + * response. + * @param carousel Carousel built with + * {@link AssistantApp#buildCarousel|buildCarousel}. + * @return HTTP response. + * @dialogflow + */ + askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): express.Response | null; + + /** + * Tells the Assistant to render the speech response and close the mic. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const WELCOME_INTENT = 'input.welcome'; + * const NUMBER_INTENT = 'input.number'; + * + * function welcomeIntent (app) { + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param speechResponse Final response. + * Spoken response can be SSML. + * @return The response that is sent back to Assistant. + * @dialogflow + */ + tell(speechResponse: string | SimpleResponse | RichResponse): express.Response | null; + + /** + * Set a new context for the current intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param name Name of the context. Dialogflow converts to lowercase. + * @param [lifespan=1] Context lifespan. + * @param parameters Context JSON parameters. + * @return Null if the context name is not defined. + * @dialogflow + */ + setContext(name: string, lifespan?: number, parameters?: any): null | undefined; + + /** + * Returns the incoming contexts for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let contexts = app.getContexts(); + * // contexts === [{ + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // }] + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @return Empty if no active contexts. + * @dialogflow + */ + getContexts(): Context[]; + + /** + * Returns the incoming context by name for this intent. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * const CONTEXT_NUMBER = 'number'; + * const NUMBER_ARGUMENT = 'myNumber'; + * + * function welcomeIntent (app) { + * app.setContext(CONTEXT_NUMBER); + * app.ask('Welcome to action snippets! Say a number.'); + * } + * + * function numberIntent (app) { + * let context = app.getContext(CONTEXT_NUMBER); + * // context === { + * // name: 'number', + * // lifespan: 0, + * // parameters: { + * // myNumber: '23', + * // myNumber.original: '23' + * // } + * // } + * const number = app.getArgument(NUMBER_ARGUMENT); + * app.tell('You said ' + number); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(NUMBER_INTENT, numberIntent); + * app.handleRequest(actionMap); + * + * @param name The name of the Context to retrieve. + * @return Context value matching name + * or null if no matching context. + * @dialogflow + */ + getContext(name: string): object; + + /** + * Gets the user's raw input query. + * + * @example + * const app = new DialogflowApp({request: request, response: response}); + * app.tell('You said ' + app.getRawInput()); + * + * @return User's raw query or null if no value. + * @dialogflow + */ + getRawInput(): string; +} diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts new file mode 100644 index 0000000000..378604411f --- /dev/null +++ b/types/actions-on-google/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for actions-on-google 1.6 +// Project: https://github.com/actions-on-google/actions-on-google-nodejs +// Definitions by: Joel Hegg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/** + * The Actions on Google client library. + * https://developers.google.com/actions/ + */ + +import * as Transactions from './transactions'; +import * as Responses from './response-builder'; + +export { AssistantApp } from './assistant-app'; +export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app'; +export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app'; +export { Transactions }; +export { Responses }; +// Backwards compatibility +export { AssistantApp as Assistant } from './assistant-app'; +export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app'; +export { DialogflowApp as ApiAiAssistant } from './dialogflow-app'; +export { DialogflowApp as ApiAiApp } from './dialogflow-app'; diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts new file mode 100644 index 0000000000..5b6e3d7522 --- /dev/null +++ b/types/actions-on-google/response-builder.d.ts @@ -0,0 +1,404 @@ +/** + * A collection of response builders. + */ + +import { OrderUpdate } from './transactions'; + +/** + * Simple Response type. + */ +export interface SimpleResponse { + /** Speech to be spoken to user. SSML allowed. */ + speech: string; + /** Optional text to be shown to user */ + displayText?: string; +} + +/** + * Suggestions to show with response. + */ +export interface Suggestion { + /** Text of the suggestion. */ + title: string; +} + +/** + * Link Out Suggestion. Used in rich response as a suggestion chip which, when + * selected, links out to external URL. + */ +export interface LinkOutSuggestion { + /** Text shown on the suggestion chip. */ + title: string; + /** String URL to open. */ + url: string; +} + +/** + * Image type shown on visual elements. + */ +export interface Image { + /** Image source URL. */ + url: string; + /** Text to replace for image for accessibility. */ + accessibilityText: string; + /** Width of the image. */ + width: number; + /** Height of the image. */ + height: number; +} + +/** + * Basic Card Button. Shown below basic cards. Open a URL when selected. + */ +export interface Button { + /** Text shown on the button. */ + title: string; + /** Action to take when selected. */ + openUrlAction: { + /** String URL to open. */ + url: string; + }; +} + +/** + * Option info. Provides unique identifier for a given OptionItem. + */ +export interface OptionInfo { + /** Unique string ID for this option. */ + key: string; + /** Synonyms that can be used by the user to indicate this option if they do not use the key. */ + synonyms: string[]; +} + +export interface StructuredResponse { + orderUpdate: OrderUpdate; +} + +export interface RichResponseItemBasicCard { + basicCard: BasicCard; +} + +export interface RichResponseItemSimpleResponse { + simpleResponse: SimpleResponse; +} + +export interface RichResponseItemStructuredResponse { + structuredResponse: StructuredResponse; +} + +export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse; + +/** + * Class for initializing and constructing Rich Responses with chainable interface. + */ +export class RichResponse { + /** + * Constructor for RichResponse. Accepts optional RichResponse to clone. + * + * @param richResponse Optional RichResponse to clone. + */ + constructor(richResponse?: RichResponse); + + /** + * Ordered list of either SimpleResponse objects or BasicCard objects. + * First item must be SimpleResponse. There can be at most one card. + */ + items: RichResponseItem[]; + + /** + * Ordered list of text suggestions to display. Optional. + */ + suggestions: Suggestion[]; + + /** + * Link Out Suggestion chip for this rich response. Optional. + */ + linkOutSuggestion?: LinkOutSuggestion; + + /** + * Adds a SimpleResponse to list of items. + * + * @param simpleResponse Simple response to present to + * user. If just a string, display text will not be set. + * @return Returns current constructed RichResponse. + */ + addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse; + + /** + * Adds a BasicCard to list of items. + * + * @param basicCard Basic card to include in response. + * @return Returns current constructed RichResponse. + */ + addBasicCard(basicCard: BasicCard): RichResponse; + + /** + * Adds a single suggestion or list of suggestions to list of items. + * + * @param suggestions Either a single string suggestion + * or list of suggestions to add. + * @return Returns current constructed RichResponse. + */ + addSuggestions(suggestions: string | string[]): RichResponse; + + /** + * Returns true if the given suggestion text is valid to be added to the suggestion list. A valid + * text string is not longer than 25 characters. + * @param suggestionText Text to validate as suggestion. + * @return True if the text is valid, false otherwise.s + */ + isValidSuggestionText(suggestionText: string): boolean; + + /** + * Sets the suggestion link for this rich response. + * + * @param destinationName Name of the link out destination. + * @param suggestionUrl - String URL to open when suggestion is used. + * @return Returns current constructed RichResponse. + */ + addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse; + + /** + * Adds an order update to this response. Use after a successful transaction + * decision to confirm the order. + * + * @param orderUpdate OrderUpdate object to add. + * @return Returns current constructed RichResponse. + */ + addOrderUpdate(orderUpdate: OrderUpdate): RichResponse; +} + +/** + * Class for initializing and constructing Basic Cards with chainable interface. + */ +export class BasicCard { + /** + * Constructor for BasicCard. Accepts optional BasicCard to clone. + * + * @param basicCard Optional BasicCard to clone. + */ + constructor(basicCard?: BasicCard); + + /** + * Title of the card. Optional. + */ + title?: string; + + /** + * Body text to show on the card. Required, unless image is present. + */ + formattedText: string; + + /** + * Subtitle of the card. Optional. + */ + subtitle?: string; + + /** + * Image to show on the card. Optional. + */ + image?: Image; + + /** + * Ordered list of buttons to show below card. Optional. + */ + buttons: Button[]; + + /** + * Sets the title for this Basic Card. + * + * @param title Title to show on card. + * @return Returns current constructed BasicCard. + */ + setTitle(title: string): BasicCard; + + /** + * Sets the subtitle for this Basic Card. + * + * @param subtitle Subtitle to show on card. + * @return Returns current constructed BasicCard. + */ + setSubtitle(subtitle: string): BasicCard; + + /** + * Sets the body text for this Basic Card. + * + * @param bodyText Body text to show on card. + * @return Returns current constructed BasicCard. + */ + setBodyText(bodyText: string): BasicCard; + + /** + * Sets the image for this Basic Card. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed BasicCard. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard; + + /** + * Adds a button below card. + * + * @param text Text to show on button. + * @param url URL to open when button is selected. + * @return Returns current constructed BasicCard. + */ + addButton(text: string, url: string): BasicCard; +} + +/** + * Class for initializing and constructing Lists with chainable interface. + */ +export class List { + /** + * Constructor for List. Accepts optional List to clone, string title, or + * list of items to copy. + * + * @param list Either a list to clone, a title + * to set for a new List, or an array of OptionItem to initialize a new + * list. + */ + constructor(list?: List | string | OptionItem[]); + + /** + * Title of the list. Optional. + */ + title?: string; + + /** + * List of 2-20 items to show in this list. Required. + */ + items: OptionItem[]; + + /** + * Sets the title for this List. + * + * @param title Title to show on list. + * @return Returns current constructed List. + */ + setTitle(title: string): List; + + /** + * Adds a single item or list of items to the list. + * + * @param optionItems OptionItems to add. + * @return Returns current constructed List. + */ + addItems(optionItems: OptionItem | OptionItem[]): List; +} + +/** + * Class for initializing and constructing Carousel with chainable interface. + */ +export class Carousel { + /** + * Constructor for Carousel. Accepts optional Carousel to clone or list of + * items to copy. + * + * @param carousel Either a carousel to clone + * or an array of OptionItem to initialize a new carousel + */ + constructor(carousel?: Carousel | OptionItem[]); + + /** + * List of 2-20 items to show in this carousel. Required. + */ + items: OptionItem[]; + + /** + * Adds a single item or list of items to the carousel. + * + * @param optionItems OptionItems to add. + * @return Returns current constructed Carousel. + */ + addItems(optionItems: OptionItem | OptionItem[]): Carousel; +} + +/** + * Class for initializing and constructing Option Items with chainable interface. + */ +export class OptionItem { + /** + * Constructor for OptionItem. Accepts optional OptionItem to clone. + * + * @param optionItem Optional OptionItem to clone. + */ + constructor(optionItem?: OptionItem); + + /** + * Option info of the option item. Required. + */ + optionInfo: OptionInfo; + + /** + * Title of the option item. Required. + */ + title: string; + + /** + * Description text of the item. Optional. + */ + description?: string; + + /** + * Image to show on item. Optional. + */ + image?: Image; + + /** + * Sets the title for this Option Item. + * + * @param title Title to show on item. + * @return Returns current constructed OptionItem. + */ + setTitle(title: string): OptionItem; + + /** + * Sets the description for this Option Item. + * + * @param description Description to show on item. + * @return Returns current constructed OptionItem. + */ + setDescription(description: string): OptionItem; + + /** + * Sets the image for this Option Item. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed OptionItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem; + + /** + * Sets the key for the OptionInfo of this Option Item. This will be returned + * as an argument in the resulting actions.intent.OPTION intent. + * + * @param key Key to uniquely identify this item. + * @return Returns current constructed OptionItem. + */ + setKey(key: string): OptionItem; + + /** + * Adds a single synonym or list of synonyms to item. + * + * @param synonyms Either a single string synonyms + * or list of synonyms to add. + * @return Returns current constructed OptionItem. + */ + addSynonyms(synonyms: string | string[]): OptionItem; +} + +/** + * Check if given text contains SSML. + * @param text Text to check. + * @return True if text contains SSML, false otherwise. + */ +export function isSsml(text: string): boolean; diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts new file mode 100644 index 0000000000..b4a4285fe9 --- /dev/null +++ b/types/actions-on-google/transactions.d.ts @@ -0,0 +1,1113 @@ +/** + * A collection of Transaction related constants, utility functions, and + * builders. + */ + +import { Image } from './response-builder'; + +/** + * Price type. + */ +export interface Price { + /** One of Transaction.PriceType. */ + type: PriceType; + amount: { + /** Currency code of price. */ + currencyCode: string; + /** Unit count of price. */ + units: number; + /** Partial unit count of price. */ + nanos?: number; + }; +} + +/** + * Order rejection info. + */ +export interface RejectionInfo { + /** One of Transaction.ReasonType. */ + type: ReasonType; + /** Reason for the order rejection. */ + reason: string; +} + +/** + * Order receipt info. + */ +export interface ReceiptInfo { + /** Action provided order ID. Used when the order has been received by the integrator. */ + confirmedActionOrderId: string; +} + +/** + * Order cancellation info. + */ +export interface CancellationInfo { + /** Reason for the cancellation. */ + reason: string; +} + +/** + * Order transit info. + */ +export interface TransitInfo { + /** UTC timestamp of the transit update as an RFC 3339 string. */ + updatedTime: string; +} + +/** + * Order fulfillment info. + */ +export interface FulfillmentInfo { + /** UTC timestamp of the fulfillment update as an RFC 3339 string. */ + deliveryTime: string; +} + +/** + * Order return info. + */ +export interface ReturnInfo { + /** Reason for the return. */ + reason: string; +} + +/** + * Transaction config for transactions not involving a Google provided + * payment instrument. + */ +export interface ActionPaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** One of Transactions.PaymentType. */ + type: PaymentType; + /** The name of the instrument displayed on receipt. For example, for card payment, could be "VISA-1234". */ + displayName: string; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Transaction config for transactions involving a Google provided payment + * instrument. + */ +export interface GooglePaymentTransactionConfig { + /** True if delivery address is required for the transaction. */ + deliveryAddressRequired: boolean; + /** Tokenization parameters provided by payment gateway. */ + tokenizationParameters: object; + /** List of accepted card networks. Must be any number of Transactions.CardNetwork. */ + cardNetworks: CardNetwork[]; + /** True if prepaid cards are not allowed for transaction. */ + prepaidCardDisallowed: boolean; + customerInfoOptions?: CustomerInfoOptions; +} + +/** + * Customer information requested as part of the transaction + */ +export interface CustomerInfoOptions { + customerInfoProperties: string[]; +} + +/** + * Generic Location type. + */ +export interface Location { + postalAddress: { + regionCode: string; + languageCode: string; + postalCode: string; + administrativeArea: string; + locality: string; + addressLines: string[]; + recipients: string; + }; + phoneNumber: string; + notes: string; +} + +/** + * Decision and order information returned when calling getTransactionDecision(). + */ +export interface TransactionDecision { + /** One of Transactions.ConfirmationDecision. */ + userDecision: TransactionUserDecision; + checkResult: { + /** One of Transactions.ResultType. */ + resultType: ResultType; + }; + order: { + /** The proposed order used in the transaction decision. */ + finalOrder: Order; + /** Order ID assigned by Google. */ + googleOrderId: string; + /** User visible order ID set in proposed order. */ + actionOrderId: string; + orderDate: { + seconds: string; + nanos: number; + }; + paymentInfo: object; + customerInfo: { + /** Customer email. */ + email: string; + }; + }; + /** + * The delivery address if user requested. + * Will appear if userDecision is Transactions.DELIVERY_ADDRESS_UPDATED. + */ + deliveryAddress: Location; +} + +/** + * Values related to supporting transactions + */ +export const TransactionValues: { + /** List of transaction card networks available when paying with Google. */ + readonly CardNetwork: typeof CardNetwork; + /** + * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. + */ + readonly ItemType: typeof LineItemType; + /** List of possible item types. */ + readonly LineItemType: typeof LineItemType; + /** List of price types. */ + readonly PriceType: typeof PriceType; + /** List of possible item types. */ + readonly PaymentType: typeof PaymentType; + /** List of customer information properties that can be requested. */ + readonly CustomerInfoProperties: typeof CustomerInfoProperties; + /** + * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. + */ + readonly ConfirmationDecision: typeof TransactionUserDecision; + /** List of possible order confirmation user decisions */ + readonly TransactionUserDecision: typeof TransactionUserDecision; + /** List of possible order states. */ + readonly OrderState: typeof OrderState; + /** + * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. + */ + readonly OrderAction: typeof ActionType; + /** List of possible actions to take on the order. */ + readonly ActionType: typeof ActionType; + /** + * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. + */ + readonly RejectionType: typeof ReasonType; + /** List of possible types of order rejection. */ + readonly ReasonType: typeof ReasonType; + /** List of possible order state objects. */ + readonly OrderStateInfo: typeof OrderStateInfo; + /** List of possible order transaction requirements check result types. */ + readonly ResultType: typeof ResultType; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressDecision: typeof DeliveryAddressUserDecision; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressUserDecision: typeof DeliveryAddressUserDecision; + /** + * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. + */ + readonly LocationType: typeof OrderLocationType; + /** List of possible order location types. */ + readonly OrderLocationType: typeof OrderLocationType; + /** List of possible order time types. */ + readonly TimeType: typeof TimeType; + /** List of possible tokenization types for the payment method */ + readonly PaymentMethodTokenizationType: typeof PaymentMethodTokenizationType; +}; + +/** + * List of transaction card networks available when paying with Google. + */ +export enum CardNetwork { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * American Express. + */ + AMEX, + /** + * Discover. + */ + DISCOVER, + /** + * Master Card. + */ + MASTERCARD, + /** + * Visa. + */ + VISA, + /** + * JCB. + */ + JCB +} + +/** + * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. + */ +export type ItemType = LineItemType; + +/** + * List of possible item types. + */ +export enum LineItemType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Regular. + */ + REGULAR, + /** + * Tax. + */ + TAX, + /** + * Discount + */ + DISCOUNT, + /** + * Gratuity + */ + GRATUITY, + /** + * Delivery + */ + DELIVERY, + /** + * Subtotal + */ + SUBTOTAL, + /** + * Fee. For everything else, there's fee. + */ + FEE +} + +/** + * List of price types. + */ +export enum PriceType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Estimate. + */ + ESTIMATE, + /** + * Actual. + */ + ACTUAL +} + +/** + * List of possible item types. + */ +export enum PaymentType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * Payment card. + */ + PAYMENT_CARD, + /** + * Bank. + */ + BANK, + /** + * Loyalty program. + */ + LOYALTY_PROGRAM, + /** + * On order fulfillment, such as cash on delivery. + */ + ON_FULFILLMENT, + /** + * Gift card. + */ + GIFT_CARD +} + +/** + * List of customer information properties that can be requested. + */ +export enum CustomerInfoProperties { + CUSTOMER_INFO_PROPERTY_UNSPECIFIED, + EMAIL +} + +/** + * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. + */ +export type ConfirmationDecision = TransactionUserDecision; + +/** + * List of possible order confirmation user decisions + */ +export enum TransactionUserDecision { + /** + * Unspecified user decision. + */ + UNKNOWN_USER_DECISION, + /** + * Order was approved by user. + */ + ACCEPTED, + /** + * Order was declined by user. + */ + REJECTED, + /** + * Order was not declined, but the delivery address was updated during + * confirmation. + */ + DELIVERY_ADDRESS_UPDATED, + /** + * Order was not declined, but the cart was updated during confirmation. + */ + CART_CHANGE_REQUESTED +} + +/** + * List of possible order states. + */ +export enum OrderState { + /** + * Order was created at the integrator's system. + */ + CREATED, + /** + * Order was rejected. + */ + REJECTED, + /** + * Order was confirmed by integrator and is active. + */ + CONFIRMED, + /** + * User cancelled the order. + */ + CANCELLED, + /** + * Order is being delivered. + */ + IN_TRANSIT, + /** + * User performed a return. + */ + RETURNED, + /** + * User received what was ordered. + */ + FULFILLED +} + +/** + * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. + */ +export type OrderAction = ActionType; + +/** + * List of possible actions to take on the order. + */ +export enum ActionType { + /** + * Unknown action. + */ + UNKNOWN, + /** + * View details. + */ + VIEW_DETAILS, + /** + * Modify order. + */ + MODIFY, + /** + * Cancel order. + */ + CANCEL, + /** + * Return order. + */ + RETURN, + /** + * Exchange order. + */ + EXCHANGE, + /** + * Email. + */ + EMAIL, + /** + * Call. + */ + CALL, + /** + * Reorder. + */ + REORDER, + /** + * Review. + */ + REVIEW, + /** + * Customer Service. + */ + CUSTOMER_SERVICE +} + +/** + * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. + */ +export type RejectionType = ReasonType; + +/** + * List of possible types of order rejection. + */ +export enum ReasonType { + /** + * Unknown + */ + UNKNOWN, + /** + * Payment was declined. + */ + PAYMENT_DECLINED +} + +/** + * List of possible order state objects. + */ +export enum OrderStateInfo { + /** + * Information about order rejection. Used with {@link RejectionInfo}. + */ + REJECTION, + /** + * Information about order receipt. Used with {@link ReceiptInfo}. + */ + RECEIPT, + /** + * Information about order cancellation. Used with {@link CancellationInfo}. + */ + CANCELLATION, + /** + * Information about in-transit order. Used with {@link TransitInfo}. + */ + IN_TRANSIT, + /** + * Information about order fulfillment. Used with {@link FulfillmentInfo}. + */ + FULFILLMENT, + /** + * Information about order return. Used with {@link ReturnInfo}. + */ + RETURN +} + +/** + * List of possible order transaction requirements check result types. + */ +export enum ResultType { + /** + * Unspecified. + */ + UNSPECIFIED, + /** + * OK to continue transaction. + */ + OK, + /** + * User is expected to take action, e.g. enable payments, to continue + * transaction. + */ + USER_ACTION_REQUIRED, + /** + * Transactions are not supported on current device/surface. + */ + ASSISTANT_SURFACE_NOT_SUPPORTED, + /** + * Transactions are not supported for current region/country. + */ + REGION_NOT_SUPPORTED +} + +/** + * List of possible user decisions to give delivery address. + * @deprecated Use {@link TransactionValues.DeliveryAddressUserDecision} instead. + */ +export type DeliveryAddressDecision = DeliveryAddressUserDecision; + +/** + * List of possible user decisions to give delivery address. + */ +export enum DeliveryAddressUserDecision { + /** + * Unknown. + */ + UNKNOWN, + /** + * User granted delivery address. + */ + ACCEPTED, + /** + * User denied to give delivery address. + */ + REJECTED +} + +/** + * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. + */ +export type LocationType = OrderLocationType; + +/** + * List of possible order location types. + */ +export enum OrderLocationType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Delivery location for an order. + */ + DELIVERY, + /** + * Business location of order provider. + */ + BUSINESS, + /** + * Origin of the order. + */ + ORIGIN, + /** + * Destination of the order. + */ + DESTINATION, + /** + * Pick up location of the order. + */ + PICK_UP +} + +/** + * List of possible order time types. + */ +export enum TimeType { + /** + * Unknown. + */ + UNKNOWN, + /** + * Date of delivery for the order. + */ + DELIVERY_DATE, + /** + * Estimated Time of Arrival for order. + */ + ETA, + /** + * Reservation time. + */ + RESERVATION_SLOT +} + +/** + * List of possible tokenization types for the payment method + */ +export enum PaymentMethodTokenizationType { + /** + * Unspecified tokenization type. + */ + UNSPECIFIED_TOKENIZATION_TYPE, + /** + * Use external payment gateway tokenization API to tokenize selected payment method. + */ + PAYMENT_GATEWAY +} + +/** + * Class for initializing and constructing Order with chainable interface. + */ +export class Order { + /** + * Constructor for Order. + * + * @param orderId Unique identifier for the order. + */ + constructor(orderId: string); + + /** + * ID for the order. Required. + */ + id: string; + + /** + * Cart for the order. + */ + cart?: Cart; + + /** + * Items not held in the order cart. + */ + otherItems: LineItem[]; + + /** + * Image for the order. + */ + image?: Image; + + /** + * TOS for the order. + */ + termsOfServiceUrl?: string; + + /** + * Total price for the order. + */ + totalPrice?: Price; + + /** + * Extensions for this order. Used for vertical-specific order attributes, + * like times and locations. + */ + extension?: object; + + /** + * Set the cart for this order. + * + * @param cart Cart for this order. + * @return Returns current constructed Order. + */ + setCart(cart: Cart): Order; + + /** + * Adds a single item or list of items to the non-cart items list. + * + * @param items Line Items to add. + * @return Returns current constructed Order. + */ + addOtherItems(items: LineItem | LineItem[]): Order; + + /** + * Sets the image for this order. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed Order. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): Order; + + /** + * Set the TOS for this order. + * + * @param url String URL of the TOS. + * @return Returns current constructed Order. + */ + setTermsOfService(url: string): Order; + + /** + * Sets the total price for this order. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed Order. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): Order; + + /** + * Adds an associated location to the order. Up to 2 locations can be added. + * + * @param type One of TransactionValues.OrderLocationType. + * @param location Location to add. + * @return Returns current constructed Order. + */ + addLocation(type: OrderLocationType, location: Location): Order; + + /** + * Sets an associated time to the order. + * + * @param type One of TransactionValues.TimeType. + * @param time Time to add. Time should be ISO 8601 representation + * of time value. Could be date, datetime, or duration. + * @return Returns current constructed Order. + */ + setTime(type: TimeType, time: string): Order; +} + +/** + * Class for initializing and constructing Cart with chainable interface. + */ +export class Cart { + /** + * Constructor for Cart. + * + * @param cartId Optional unique identifier for the cart. + */ + constructor(cartId?: string); + + /** + * ID for the cart. Optional. + */ + id?: string; + + /** + * Merchant providing the cart. + */ + merchant?: object; + + /** + * Optional notes about the cart. + */ + notes?: string; + + /** + * Items held in the order cart. + */ + lineItems: LineItem[]; + + /** + * Non-line items. + */ + otherItems: LineItem[]; + + /** + * Set the merchant for this cart. + * + * @param id Merchant ID. + * @param name Name of the merchant. + * @return Returns current constructed Cart. + */ + setMerchant(id: string, name: string): Cart; + + /** + * Set the notes for this cart. + * + * @param notes Notes. + * @return Returns current constructed Cart. + */ + setNotes(notes: string): Cart; + + /** + * Adds a single item or list of items to the cart. + * + * @param items Line Items to add. + * @return Returns current constructed Cart. + */ + addLineItems(items: LineItem | LineItem[]): Cart; + + /** + * Adds a single item or list of items to the non-items list of this cart. + * + * @param items Line Items to add. + * @return Returns current constructed Cart. + */ + addOtherItems(items: LineItem | LineItem[]): Cart; +} + +/** + * Class for initializing and constructing LineItem with chainable interface. + */ +export class LineItem { + /** + * Constructor for LineItem. + * + * @param lineItemId Unique identifier for the item. + * @param name Name of the item. + */ + constructor(lineItemId: string, name: string); + + /** + * Item ID. + */ + id: string; + + /** + * Name of the item. + */ + name: string; + + /** + * Item price. + */ + price?: Price; + + /** + * Sublines for current item. Only valid if item type is REGULAR. + */ + subLines?: Array; + + /** + * Image of the item. + */ + image?: Image; + + /** + * Type of the item. One of TransactionValues.LineItemType. + */ + type?: LineItemType; + + /** + * Quantity of the item. + */ + quantity?: number; + + /** + * Description for the item. + */ + description?: string; + + /** + * Offer ID for the item. + */ + offerId?: string; + + /** + * Adds a single item or list of items or notes to the sublines. Only valid + * if item type is REGULAR. + * + * @param items Sublines to add. + * @return Returns current constructed LineItem. + */ + addSublines(items: string | LineItem | Array): LineItem; + + /** + * Sets the image for this item. + * + * @param url Image source URL. + * @param accessibilityText Text to replace for image for + * accessibility. + * @param width Width of the image. + * @param height Height of the image. + * @return Returns current constructed LineItem. + */ + setImage(url: string, accessibilityText: string, width?: number, height?: number): LineItem; + + /** + * Sets the price of this item. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed LineItem. + */ + setPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): LineItem; + + /** + * Set the type of the item. + * + * @param type Type of the item. One of TransactionValues.LineItemType. + * @return Returns current constructed LineItem. + */ + setType(type: LineItemType): LineItem; + + /** + * Set the quantity of the item. + * + * @param quantity Quantity of the item. + * @return Returns current constructed LineItem. + */ + setQuantity(quantity: number): LineItem; + + /** + * Set the description of the item. + * + * @param description Description of the item. + * @return Returns current constructed LineItem. + */ + setDescription(description: string): LineItem; + + /** + * Set the Offer ID of the item. + * + * @param offerId Offer ID of the item. + * @return Returns current constructed LineItem. + */ + setOfferId(offerId: string): LineItem; +} + +/** + * Class for initializing and constructing OrderUpdate with chainable interface. + */ +export class OrderUpdate { + /** + * Constructor for OrderUpdate. + * + * @param orderId Unique identifier of the order. + * @param isGoogleOrderId True if the order ID is provided by + * Google. False if the order ID is app provided. + */ + constructor(orderId: string, isGoogleOrderId: boolean); + + /** + * Google provided identifier of the order. + */ + googleOrderId?: string; + + /** + * App provided identifier of the order. + */ + actionOrderId?: string; + + /** + * State of the order. + */ + orderState?: object; + + /** + * Updates for items in the order. Mapped by item id to state or price. + */ + lineItemUpdates: object; + + /** + * UTC timestamp of the order update as an RFC 3339 string. + */ + updateTime?: string; + + /** + * Actionable items presented to the user to manage the order. + */ + orderManagementActions: object[]; + + /** + * Notification content to the user for the order update. + */ + userNotification?: object; + + /** + * Updated total price of the order. + */ + totalPrice?: Price; + + /** + * Set the Google provided order ID of the order. + * + * @param orderId Google provided order ID. + * @return Returns current constructed OrderUpdate. + */ + setGoogleOrderId(orderId: string): OrderUpdate; + + /** + * Set the Action provided order ID of the order. + * + * @param orderId Action provided order ID. + * @return Returns current constructed OrderUpdate. + */ + setActionOrderId(orderId: string): OrderUpdate; + + /** + * Set the state of the order. + * + * @param state One of TransactionValues.OrderState. + * @param label Label for the order state. + * @return Returns current constructed OrderUpdate. + */ + setOrderState(state: OrderState, label: string): OrderUpdate; + + /** + * Set the update time of the order. + * + * @param seconds Seconds since Unix epoch. + * @param nanos Partial time units. It is rounded to the nearest millisecond. + * @return Returns current constructed OrderUpdate. + */ + setUpdateTime(seconds: number, nanos?: number): OrderUpdate; + + /** + * Set the user notification content of the order update. + * + * @param title Title of the notification. + * @param text Text of the notification. + * @return Returns current constructed OrderUpdate. + */ + setUserNotification(title: string, text: object): OrderUpdate; + + /** + * Sets the total price for this order. + * + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of price. + * @param units Unit count of price. + * @param nanos Partial unit count of price. + * @return Returns current constructed OrderUpdate. + */ + setTotalPrice(priceType: PriceType, currencyCode: string, units: number, nanos?: number): OrderUpdate; + + /** + * Adds an actionable item for the user to manage the order. + * + * @param type One of TransactionValues.ActionType. + * @param label Button label. + * @param url URL to open when button is clicked. + * @return Returns current constructed OrderUpdate. + */ + addOrderManagementAction(type: ActionType, label: string, url: string): OrderUpdate; + + /** + * Adds a single price update for a particular line item in the order. + * + * @param itemId Line item ID for the order item updated. + * @param priceType One of TransactionValues.PriceType. + * @param currencyCode Currency code of new price. + * @param units Unit count of new price. + * @param nanos Partial unit count of new price. + * @param reason Reason for the price change. Required unless a + * reason for this line item change was already declared in + * addLineItemStateUpdate. + * @return Returns current constructed OrderUpdate. + */ + addLineItemPriceUpdate(itemId: string, priceType: PriceType, currencyCode: string, units: number, nanos?: number, reason?: string): OrderUpdate; + + /** + * Adds a single state update for a particular line item in the order. + * + * @param itemId Line item ID for the order item updated. + * @param state One of TransactionValues.OrderState. + * @param label Label for the new item state. + * @param reason Reason for the price change. This will overwrite + * any reason given in addLineitemPriceUpdate. + * @return Returns current constructed OrderUpdate. + */ + addLineItemStateUpdate(itemId: string, state: OrderState, label: string, reason?: string): OrderUpdate; + + /** + * Sets some extra information about the order. Takes an order update info + * type, and any accompanying data. This should only be called once per + * order update. + * + * @param type One of TransactionValues.OrderStateInfo. + * @param data Proper Object matching the data necessary for the info + * type. For instance, for the TransactionValues.OrderStateInfo.RECEIPT info + * type, use the {@link ReceiptInfo} data type. + * @return Returns current constructed OrderUpdate. + */ + setInfo(type: string, data: object): OrderUpdate; +} diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json new file mode 100644 index 0000000000..6682b5c194 --- /dev/null +++ b/types/actions-on-google/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "assistant-app.d.ts", + "actions-sdk-app.d.ts", + "dialogflow-app.d.ts", + "response-builder.d.ts", + "transactions.d.ts", + "actions-on-google-tests.ts" + ] +} diff --git a/types/actions-on-google/tslint.json b/types/actions-on-google/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/actions-on-google/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/adone/glosses/datetime.d.ts b/types/adone/glosses/datetime.d.ts index 417f706d95..5ce320f613 100644 --- a/types/adone/glosses/datetime.d.ts +++ b/types/adone/glosses/datetime.d.ts @@ -731,9 +731,6 @@ declare namespace adone { */ creationData(): DatetimeCreationData; - /** - * - */ parsingFlags(): DatetimeParsingFlags; /** diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 439d314f4a..5af66a09d1 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -1,5 +1,4 @@ // Global - const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -42,9 +41,18 @@ entity.addEventListener('child-detached', (event) => { const Component = AFRAME.registerComponent('test', {}); // Scene - const scene = document.querySelector('a-scene'); scene.hasLoaded; // System const system = scene.systems['systemName']; + +// Register Custom Geometry +AFRAME.registerGeometry('a-test-geometry', { + schema: { + groupIndex: { default: 0 } + }, + init(data) { + this.geometry = new THREE.Geometry(); + } +}); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index f1f5cd7a20..803318a754 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for AFRAME 0.5 +// Type definitions for AFRAME 0.7 // Project: https://aframe.io/ // Definitions by: Paul Shannon +// Roberto Ritger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -40,7 +41,7 @@ declare namespace AFrame { primitives: { [ key: string ]: Entity }; registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometery: THREE.Geometry): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): Geometry; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; registerShader(name: string, shader: any): void; registerSystem(name: string, definition: SystemDefinition): void; @@ -101,7 +102,7 @@ declare namespace AFrame { name: string; schema: Schema; - init(): void; + init(data?: any): void; pause(): void; play(): void; remove(): void; @@ -124,7 +125,7 @@ declare namespace AFrame { multiple?: boolean; schema?: Schema; - init?(): void; + init?(data?: any): void; pause?(): void; play?(): void; remove?(): void; @@ -222,6 +223,10 @@ declare namespace AFrame { [ key: string ]: any; } + interface GeometryDefinition extends ComponentDefinition { + geometry?: THREE.Geometry; + } + interface GeometryDescriptor { Geometry: Geometry; schema: Schema; diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index d2b458de7d..f068fc4e22 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for algoliasearch-client-js 3.24.5 +// Type definitions for algoliasearch-client-js 3.24.6 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene @@ -95,6 +95,18 @@ declare namespace algoliasearch { * https://github.com/algolia/algoliasearch-client-js#keep-alive */ destroy(): void; + /** + * Add a header to be sent with all upcoming requests + */ + setExtraHeader(name: string, value: string): void; + /** + * Get the value of an extra header + */ + getExtraHeader(name: string): string; + /** + * remove an extra header for all upcoming requests + */ + unsetExtraHeader(name: string): void; /** * List all your indices along with their associated information (number of entries, disk size, etc.) * @param cb(err, res) @@ -533,6 +545,65 @@ declare namespace algoliasearch { options: SearchSynonymOptions, cb: (err: Error, res: any) => void ): void; + /** + * Save a rule object + * @param rule + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule + */ + saveRule( + rule: AlgoliaRule, + options: RuleOption, + cb: (err: Error, res: any) => void + ): void; + /** + * Save a rule object + * @param rules + * @param options + * @param cb(err, res) + */ + batchRules( + rules: AlgoliaRule[], + options: RuleOption, + cb: (err: Error, res: any) => void + ): void; + /** + * Delete a specific rule + * @param identifier + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules + */ + deleteRule( + identifier: string, + options: RuleOption, + cb: (err: Error, res: any) => void + ): void; + /** + * Clear all rules of an index + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules + */ + clearRules(options: RuleOption, cb: (err: Error, res: any) => void): void; + /** + * Get a specific rule + * @param identifier + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule + */ + getRule(identifier: string, cb: (err: Error, res: any) => void): void; + /** + * Search a rules + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules + */ + searchRules( + options: SearchRuleOptions, + cb: (err: Error, res: any) => void + ): void; /** * List index user keys * @param cb(err, res) @@ -738,8 +809,8 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - qp: AlgoliaQueryParameters; - }): Promise; + } & AlgoliaQueryParameters + ): Promise; /** * Search in an index * @param params query parameter @@ -755,8 +826,7 @@ declare namespace algoliasearch { }: { facetName: string; facetQuery: string; - qp: AlgoliaQueryParameters; - }, + } & AlgoliaQueryParameters, cb: (err: Error, res: any) => void ): void; /** @@ -846,6 +916,50 @@ declare namespace algoliasearch { * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ searchSynonyms(options: SearchSynonymOptions): Promise; + /** + * Save a rule object + * @param rule + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule + */ + saveRule(rule: AlgoliaRule, options: RuleOption): Promise; + /** + * Save a rule object + * @param rules + * @param options + * return {Promise} + */ + batchRules(rules: AlgoliaRule[], options: RuleOption): Promise; + /** + * Delete a specific rule + * @param identifier + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules + */ + deleteRule(identifier: string, options: RuleOption): Promise; + /** + * Clear all query rules of an index + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules + */ + clearRules(options: RuleOption): Promise; + /** + * Get a specific query rule + * @param identifier + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule + */ + getRule(identifier: string): Promise; + /** + * Search for query rules + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules + */ + searchRules(options: SearchRuleOptions): Promise; /** * List index user keys * return {Promise} @@ -1024,8 +1138,8 @@ Interface describing options available for gettings the logs description?: string; } /** - * Describes option used when making operation on synonyms - */ + * Describes option used when making operation on synonyms + */ interface SynonymOption { /** * You can forward all settings updates to the replicas of an index @@ -1039,8 +1153,8 @@ Interface describing options available for gettings the logs replaceExistingSynonyms?: boolean; } /** - * Describes options used when searching for synonyms - */ + * Describes options used when searching for synonyms + */ interface SearchSynonymOptions { /** * The actual search query to find synonyms @@ -1049,7 +1163,7 @@ Interface describing options available for gettings the logs query?: string; /** * The page to fetch when browsing through several pages of results - * default: 100 + * default: 0 * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ page?: number; @@ -1066,6 +1180,49 @@ Interface describing options available for gettings the logs */ hitsPerPage?: number; } + /** + * Describes option used when making operation on query rules + */ + interface RuleOption { + /** + * You can forward all settings updates to the replicas of an index + * https://github.com/algolia/algoliasearch-client-js#replica-settings + */ + forwardToReplicas?: boolean; + /** + * Replace all existing query rules on the index with the content of the batch + */ + clearExistingRules?: boolean; + } + /** + * Describes options used when searching for query rules + */ + interface SearchRuleOptions { + /** + * The actual search query to find synonyms + */ + query?: string; + /** + * When specified, restricts matches to rules with a specific anchoring type. + * When omitted, all anchoring types may match. + */ + anchoring?: string; + /** + * When specified, restricts matches to contextual rules with a specific context (exact match). + * When omitted, any generic or contextual rule (with any context) may match. + */ + context?: string; + /** + * Requested page (zero-based) + * default: 0 + */ + page?: number; + /** + * Number of hits per page + * default: 20 + */ + hitsPerPage?: number; + } interface AlgoliaBrowseResponse { cursor?: string; hits: any[]; @@ -1094,8 +1251,94 @@ Interface describing options available for gettings the logs synonyms: string[]; } /** - * Describes the options used when generating new api keys - */ + * Describes a query rule object + */ + interface AlgoliaRule { + /** + * ObjectID of the synonym + * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym + */ + objectID: string; + /** + * Condition of the rule + */ + condition: { + /** + * Query pattern + * syntax: https://www.algolia.com/doc/rest-api/query-rules/?language=php#query-pattern-syntax + */ + pattern: string; + /** + * Whether the pattern must match the beginning or the end of the query string, or both, or none. + */ + anchoring: 'is' | 'startsWith' | 'endsWith' | 'contains'; + /** + * Rule context (format: [A-Za-z0-9_-]+). + * When specified, the rule is contextual and applies only when the same context is specified + * at query time (using the ruleContexts parameter). + * When absent, the rule is generic and always applies + * (provided that its other conditions are met, of course). + */ + context?: string; + }; + /** + * Consequence of the rule. At least one of the following must be used: + */ + consequence: { + params?: { + /** + * When a string, it replaces the entire query string. + * When an object, describes incremental edits to be made to the query string. + */ + query?: + | string + | { + /** + * Tokens (literals or placeholders) from the query pattern + * that should be removed from the query string. + */ + remove: string[]; + }; + /** + * Names of facets to which automatic filtering must be applied; + * they must match the facet name of a facet value placeholder in the query pattern. + */ + automaticFacetFilters?: string[]; + /** + * Same as automaticFacetFilters, but for optionalFacetFilters. + * The same syntax as query parameters can be used to specify a score: facetName. + */ + automaticOptionalFacetFilters?: string[]; + }; + /** + * Objects to promote as hits. Each object must contain the following fields + */ + promote?: { + /** + * Unique identifier of the object to promote + */ + objectID: string; + /** + * Promoted rank for the object (zero-based) + */ + position: number; + }[]; + /** + * Custom JSON object that will be appended to the userData array in the response. + * This object is not interpreted by the API. It is limited to 1kB of minified JSON. + */ + userData?: {}; + }; + /** + * This field is intended for rule management purposes, + * in particular to ease searching for rules and presenting them to human readers. + * It is not interpreted by the API. + */ + description?: string; + } + /** + * Describes the options used when generating new api keys + */ interface AlgoliaSecuredApiOptions { /** * Filter the query with numeric, facet or/and tag filters diff --git a/types/algoliasearch/tsconfig.json b/types/algoliasearch/tsconfig.json index 3358732ba3..4d7e52dd8b 100644 --- a/types/algoliasearch/tsconfig.json +++ b/types/algoliasearch/tsconfig.json @@ -1,23 +1,16 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "algoliasearch-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "algoliasearch-tests.ts"] +} diff --git a/types/algoliasearch/tslint.json b/types/algoliasearch/tslint.json index a41bf5d19a..886f1a8b6c 100644 --- a/types/algoliasearch/tslint.json +++ b/types/algoliasearch/tslint.json @@ -1,79 +1,79 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } } diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 85abd11f5c..0dae492a76 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -2191,27 +2191,45 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val chart.addGraph(graph); */ class AmGraph { + /** Text which screen readers will read if user rolls-over the bullet/column or sets focus using tab key (this is possible only if tabIndex property of AmGraph is set to some number). Text is added as aria-label tag. Note - not all screen readers and browsers support this. + @default "[[title]] [[category]] [[value]]" + */ + accessibleLabel: string; /** Name of the alpha field in your dataProvider. */ alphaField: string; + /** If you set this to true before chart is drawn, the animation of this graph won't be played. + @default false + */ + animationPlayed: boolean; + /** Allows customizing graphs balloons individually (only when ChartCursor is used). Note: the balloon object is not created automatically, you should create it before setting properties */ + balloon: AmBalloon; /** Value balloon color. Will use graph or data item color if not set. */ balloonColor: string; - /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ + /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph objects to it. This function should return a string which will be displayed in a balloon. */ balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; - /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] or any other field name from your data provider. HTML tags can also be used. + @default [[value]] + */ balloonText: string; - /** Specifies if the line graph should be placed behind column graphs */ + /** Specifies if the line graph should be placed behind column graphs + @default false + */ behindColumns: boolean; - /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "bubble", "diamond", "xError", "yError" and "custom". + @default "none" + */ bullet: string; /** Opacity of bullets. Value range is 0 - 1. @default 1 */ bulletAlpha: number; + /** bulletAxis value is used when you are building error chart. Error chart is a regular serial or XY chart with bullet type set to "xError" or "yError". The graph should know which axis should be used to determine the size of this bullet - that's when bulletAxis should be set. Besides that, you should also set graph.errorField. You can also use other bullet types with this feature too. For example, if you set bulletAxis for XY chart, the size of a bullet will change as you zoom the chart. */ + bulletAxis: ValueAxis; /** Bullet border opacity. - @default 1 + @default 0 */ bulletBorderAlpha: number; - /** Bullet border color. Will use lineColor if not set. */ + /** Bullet border color. Will use lineColor if not set. */ bulletBorderColor: string; /** Bullet border thickness. @default 2 @@ -2221,7 +2239,11 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletColor: string; /** Name of the bullet field in your dataProvider. */ bulletField: string; - /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + /** Useful for touch devices - if you set it to 20 or so, the bullets of a graph will have invisible circle around the actual bullet (bullets should still be enabled), which will be easier to touch (bullets usually are smaller and hard to hit). */ + bulletHitAreaSize: number; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. + @default 0 + */ bulletOffset: number; /** Bullet size. @default 8 @@ -2229,17 +2251,31 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletSize: number; /** Name of the bullet size field in your dataProvider. */ bulletSizeField: string; + /** If this field is set and addClassNames is enabled, the chart will look for a class name string in data using this setting and apply additional class names to elements of the particular data points, such as bullets. */ + classNameField: string; /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ closeField: string; + /** In case you want to place this graph's columns in front of other columns, set this to false. In case "true", the columns will be clustered next to each other. + + NOTE: clustering works only for graphs of type "column". + @default true + */ + clustered: boolean; /** Color of value labels. Will use chart's color if not set. */ color: string; /** Name of the color field in your dataProvider. */ colorField: string; - /** Specifies whether to connect data points if data is missing. The default value is true. + /** You can use this property with non-stacked column graphs and specify order of columns of each category (starting from 0). Important: this feature does not work in stacked columns scenarios as well as with graph toggling enabled in legend. */ + columnIndexField: string; + /** You can specify custom column width for each graph individually. Value range is 0 - 1 (we set relative width, not pixel width here). */ + columnWidth: number; + /** Specifies whether to connect data points if data is missing. The default value is true. This feature does not work with XY chart. @default true */ connect: boolean; - /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. + @default 0 + */ cornerRadiusTop: number; /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. @default 1 @@ -2249,55 +2285,108 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val customBullet: string; /** Name of the custom bullet field in your dataProvider. */ customBulletField: string; - /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + /** Path to the image for legend marker. */ + customMarker: string; + /** Dash length. If you set it to a value greater than 0, the graph line (or columns border) will be dashed. + @default 0 + */ dashLength: number; + /** Name of the dash length field in your dataProvider. This property adds a possibility to change graphs’ line from solid to dashed on any data point. You can also make columns border dashed using this setting. Note, this won't work with smoothedLineGraph. */ + dashLengthField: string; + /** Used to format balloons if value axis is date-based. + @default "MMM DD, YYYY" + */ + dateFormat: string; /** Name of the description field in your dataProvider. */ descriptionField: string; - /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + /** Name of error value field in your data provider. */ + errorField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. + @default 0 + */ fillAlphas: number; - /** Fill color. Will use lineColor if not set. */ - fillColors: any; - /** Name of the fill colors field in your dataProvider. */ + /** Fill color. Will use lineColor if not set. You can also set array of colors here. */ + fillColors: string; + /** Name of the fill colors field in your dataProvider. This property adds a possibility to change line graphs’ fill color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ fillColorsField: string; - /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + /** XY chart only. If you set this property to id or reference of your X or Y axis, and the fillAlphas is > 0, the area between graph and axis will be filled with color, like in this demo. */ + fillToAxis: ValueAxis; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). This feature is not supported by smoothedLine graphs and Radar chart. */ fillToGraph: AmGraph; + /** Column width in pixels. If you set this property, columns will be of a fixed width and won't adjust to the available space. */ + fixedColumnWidth: number; /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + fontSize: number; + /** If this is set `true`, the graph will always break the line if the distance in time between two adjacent data points is bigger than `gapPeriod x minPeriod`, even if `connect` is set to `true`. + @default false + */ + forceGap: boolean; + /** Name of the gap field in your dataProvider. You can force graph to show gap at a desired data point using this feature. This feature does not work with XY chart. */ + gapField: string; + /** Using this property you can specify when graph should display gap - if the time difference between data points is bigger than duration of minPeriod * gapPeriod, and connect property of a graph is set to false, graph will display gap. + @default 1.1 + */ + gapPeriod: number; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". + @default "vertical" + */ gradientOrientation: string; - /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. + @default false + */ hidden: boolean; - /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. + @default 0 + */ hideBulletsCount: number; /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ highField: string; - - /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used.*/ - id?: string; - + /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used. */ + id: string; /** Whether to include this graph when calculating min and max value of the axis. @default true */ includeInMinMax: boolean; + /** Data label text anchor. + @default "auto" + */ + labelAnchor: string; /** Name of label color field in data provider. */ labelColorField: string; - /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + /** You can use it to format labels of data items in any way you want. Graph will call this function and pass reference to GraphDataItem and formatted text as attributes. This function should return string which will be displayed as label. */ + labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; + labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; + /** Offset of data label. + @default 0 + */ + labelOffset: number; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. + @default "top" + */ labelPosition: string; + /** Rotation of a data label. + @default 0 + */ + labelRotation: number; /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ labelText: string; /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ legendAlpha: number; /** Legend marker color. Will use lineColor if not set. */ legendColor: string; + /** It is called and the following attributes are passed: dataItem, formattedText, periodValues, periodPercentValues. It should return hex color code which will be used for legend marker. */ + legendColorFunction: Object; + /** The text which will be displayed in the value portion of the legend when user is not hovering above any data point. The tags should be made out of two parts - the name of a field (value / open / close / high / low) and the value of the period you want to be show - open / close / high / low / sum / average / count. For example: [[value.sum]] means that sum of all data points of value field in the selected period will be displayed. */ + legendPeriodValueText: string; /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ legendValueText: string; /** Opacity of the line (or column border). Value range is 0 - 1. @default 1 */ lineAlpha: number; - /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + /** Color of the line (or column border). If you do not set any, the color from AmCoordinateChart.colors array will be used for each subsequent graph. */ lineColor: string; - /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + /** Name of the line color field in your dataProvider. This property adds a possibility to change graphs’ line color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ lineColorField: string; /** Specifies thickness of the graph line (or column border). @default 1 @@ -2305,55 +2394,125 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val lineThickness: number; /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ lowField: string; - /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: square, circle, diamond, triangleUp, triangleDown, triangleLeft, triangleDown, bubble, line, none. */ markerType: string; /** Specifies size of the bullet which value is the biggest (XY chart). @default 50 */ maxBulletSize: number; - /** Specifies minimum size of the bullet (XY chart). */ + /** Specifies minimum size of the bullet (XY chart). + @default 4 + */ minBulletSize: number; - /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + /** It is useful if you have really lots of data points. Based on this property the graph will omit some of the lines (if the distance between points is less that minDistance, in pixels). This will not affect the bullets or indicator in anyway, so the user will not see any difference (unless you set minValue to a bigger value, let say 5), but will increase performance as less lines will be drawn. By setting value to a bigger number you can also make your lines look less jagged. + @default 1 + */ + minDistance: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. + @default 0 + */ negativeBase: number; /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ negativeFillAlphas: number; /** Fill color of negative part of the graph. Will use fillColors if not set. */ - negativeFillColors: any; //String /Array; + negativeFillColors: string; + /** Opacity of the negative portion of the line (or column border). Value range is 0 - 1. + @default 1 + */ + negativeLineAlpha: number; /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ negativeLineColor: string; - /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ - numberFormatter: Object; - /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. */ - newStack: boolean; - /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. - @default 50 + /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. + @default false */ + newStack: boolean; + /** In case you want to have a step line graph without risers, you should set this to true. + @default false + */ + noStepRisers: boolean; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ openField: string; - /**Precision of values. Will use chart's precision if not set any.*/ - precision: number; - /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + /** Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. If you want to have individual patterns for each column, define patterns in data provider and set graph.patternField property. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + pattern: Object; + /** Field name in your data provider which holds pattern information. Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + patternField: string; + /** This property can be used by step graphs - you can set how many periods one horizontal line should span. + @default 1 + */ + periodSpan: number; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start", "middle" and "end" + @default "middle" + */ pointPosition: string; - /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + /** Precision of values. Will use chart's precision if not set any. */ + precision: number; + /** If this is set to true, candlesticks will be colored in a different manner - if current close is less than current open, the candlestick will be empty, otherwise - filled with color. If previous close is less than current close, the candlestick will use positive color, otherwise - negative color. + @default false + */ + proCandlesticks: boolean; + /** Gantt chart only. Contains unmodified segment object from data provider. */ + segmentData: Object; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space or go outside plot area. If you don't want these labels to be hidden, set this to true. + @default false + */ showAllValueLabels: boolean; /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. @default true */ showBalloon: boolean; - /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". "top" and "bottom" values will glue the balloon to top/bottom of the plot area. + @default "close" + */ showBalloonAt: string; + /** Works with candlestick graph type, you can set it to open, close, high, low. If you set it to high, the events will be shown at the tip of the high line. + @default "close" + */ + showBulletsAt: string; + /** If you want mouse pointer to change to hand when hovering the graph, set this property to true. + @default false + */ + showHandOnHover: boolean; + /** It can only be used together with topRadius (when columns look like cylinders). If you set it to true, the cylinder will be lowered down so that the center of it's bottom circle would be right on category axis. + @default false + */ + showOnAxis: boolean; /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. @default true */ stackable: boolean; + /** Step graph only. Specifies to which direction step should be drawn. + @default "right" + */ + stepDirection: string; + /** If you set it to false, the graph will not be hidden when user clicks on legend entry. + @default true + */ + switchable: boolean; + /** In case you set it to some number, the chart will set focus on bullet/column (starting from first) when user clicks tab key. When a focus is set, screen readers like NVDA Screen reader will read label which is set using accessibleLabel property of AmGraph. Note, not all browsers and readers support this. */ + tabIndex: number; /** Graph title. */ title: string; - /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + /** If you set this to 1, columns will become cylinders (must set depth3D and angle properties of a chart to >0 values in order this to be visible). you can make columns look like cones (set topRadius to 0) or even like some glasses (set to bigger than 1). We strongly recommend setting grid opacity to 0 in order this to look good. */ + topRadius: number; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. + @default "line" + */ type: string; /** Name of the url field in your dataProvider. */ urlField: string; /** Target to open URLs in, i.e. _blank, _top, etc. */ urlTarget: string; - /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + /** If set to true, the bullet border will take the same color as graph line. + @default false + */ + useLineColorForBulletBorder: boolean; + /** If negativeLineColor and/or negativeFillColors are set and useNegativeColorIfDown is set to true (default is false), the line, step and column graphs will use these colors for lines, bullets or columns if previous value is bigger than current value. In case you set openField for the graph, the graph will compare current value with openField value instead of comparing to previous value. Here is a demo. + @default false + */ + useNegativeColorIfDown: boolean; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. You can use reference to the real ValueAxis object or set value axis id. + @default ValueAxis + */ valueAxis: ValueAxis; /** Name of the value field in your dataProvider. */ valueField: string; @@ -2361,11 +2520,15 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @default true */ visibleInLegend: boolean; - /** XY chart only. A horizontal value axis object to attach graph to. */ + /** XY chart only. A horizontal value axis object to attach graph to. + @default ValueAxis + */ xAxis: ValueAxis; /** XY chart only. Name of the x field in your dataProvider. */ xField: string; - /** XY chart only. A vertical value axis object to attach graph to. */ + /** XY chart only. A vertical value axis object to attach graph to. + @default ValueAxis + */ yAxis: ValueAxis; /** XY chart only. Name of the y field in your dataProvider. */ yField: string; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 91060d23b0..2d5cb3ba99 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -63,4 +63,4 @@ export interface ConfirmChannel extends Channel { waitForConfirms(): Promise; } -export function connect(url: string, socketOptions?: any): Promise; +export function connect(url: string | Options.Connect, socketOptions?: any): Promise; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 12514d7810..af90909d8c 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -21,6 +21,64 @@ export namespace Replies { } export namespace Options { + interface Connect { + /** + * The to be used protocol + * + * Default value: 'amqp' + */ + protocol?: string; + /** + * Hostname used for connecting to the server. + * + * Default value: 'localhost' + */ + hostname?: string; + /** + * Port used for connecting to the server. + * + * Default value: 5672 + */ + port?: number; + /** + * Username used for authenticating against the server. + * + * Default value: 'guest' + */ + username?: string; + /** + * Password used for authenticating against the server. + * + * Default value: 'guest' + */ + password?: string; + /** + * The desired locale for error messages. RabbitMQ only ever uses en_US + * + * Default value: 'en_US' + */ + locale?: string; + /** + * The size in bytes of the maximum frame allowed over the connection. 0 means + * no limit (but since frames have a size field which is an unsigned 32 bit integer, it’s perforce 2^32 - 1). + * + * Default value: 0x1000 (4kb) - That's the allowed minimum, it will fit many purposes + */ + frameMax?: number; + /** + * The period of the connection heartbeat in seconds. + * + * Default value: 0 + */ + heartbeat?: number; + /** + * What VHost shall be used. + * + * Default value: '/' + */ + vhost?: string; + } + interface AssertQueue { exclusive?: boolean; durable?: boolean; @@ -85,4 +143,4 @@ export interface Message { content: Buffer; fields: any; properties: any; -} \ No newline at end of file +} diff --git a/types/angular-animate/index.d.ts b/types/angular-animate/index.d.ts index 0ce96a2f2f..6a51b368c8 100644 --- a/types/angular-animate/index.d.ts +++ b/types/angular-animate/index.d.ts @@ -2,7 +2,7 @@ // Project: http://angularjs.org // Definitions by: Michel Salib , Adi Dahiya , Raphael Schweizer , Cody Schaaf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 declare var _: string; export = _; diff --git a/types/angular-file-upload/index.d.ts b/types/angular-file-upload/index.d.ts index ee1982123a..edac0ce2ad 100644 --- a/types/angular-file-upload/index.d.ts +++ b/types/angular-file-upload/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nervgh/angular-file-upload // Definitions by: Cyril Gandon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as angular from 'angular'; diff --git a/types/angular-hotkeys/README.md b/types/angular-hotkeys/README.md deleted file mode 100644 index a31ed8a936..0000000000 --- a/types/angular-hotkeys/README.md +++ /dev/null @@ -1,55 +0,0 @@ -## What is it? - -This is a typescript interface to be used with [angular-hotkeys](https://github.com/chieffancypants/angular-hotkeys/). - -## What are declaration files? - -See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). - - -## How do I get them? - -### npm - -This is the preferred method. This is only available for TypeScript 2.0+ users. For these typings: - -```sh -npm install --save-dev @types/angular-hotkeys -``` - -The types should then be automatically included by the compiler. -See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). - - -### Other methods - -These can be used by TypeScript 1.0. - -* [Typings](https://github.com/typings/typings) -* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off) -* Manually download from the `master` branch of this repository - -You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). - -## How to use - -After installing a package you can import the definition file and begin using it as so: - -```ts - -import * as hotkeys from '../../node_modules/@types/angular-hotkeys' - -class FooController { - static $inject = [ - 'hotkeys' - ]; - - constructor( - private hotkeys: ng.hotkeys.HotkeysProvider - ) { } -} - -``` - -for a detailed explanation of the behavior of angular-hotkeys please refer to [its documentation](https://github.com/chieffancypants/angular-hotkeys/) - diff --git a/types/angular-hotkeys/angular-hotkeys-tests.ts b/types/angular-hotkeys/angular-hotkeys-tests.ts index c0bd9b974d..503080e9d8 100644 --- a/types/angular-hotkeys/angular-hotkeys-tests.ts +++ b/types/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,30 +1,67 @@ -var scope: ng.IScope; -var hotkeyProvider: ng.hotkeys.HotkeysProvider; -var hotkeyObj: ng.hotkeys.Hotkey; +import { HotkeysProvider, Hotkey } from 'angular-hotkeys'; +import { module } from 'angular'; -hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} ); -hotkeyProvider.add(hotkeyObj); -hotkeyProvider.bindTo(scope); -hotkeyProvider.del("mod+s"); -hotkeyProvider.del(["mod+s"]); -hotkeyProvider.get("mod+s"); -hotkeyProvider.get(["mod+s"]); -hotkeyProvider.toggleCheatSheet(); - -hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback); - -hotkeyProvider.bindTo(scope) - .add(hotkeyObj) - .add(hotkeyObj) - .add({ - combo: 'w', - description: 'blah blah', - callback: function() {} - }) - .add({ - combo: ['w', 'mod+w'], - description: 'blah blah', - callback: function() {} +module('myApp', ['cfp.hotkeys']) + .config((hotkeysProvider: HotkeysProvider) => { + hotkeysProvider.includeCheatSheet = false; + const somehotKeyObj: Hotkey = { + combo: '', + callback: () => { } + }; }); +function someInjectionService( + scope: ng.IScope, + hotkeyProvider: ng.hotkeys.HotkeysProvider, + hotkeyObj: ng.hotkeys.Hotkey +) { + hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { }); + hotkeyProvider.add(hotkeyObj); + hotkeyProvider.bindTo(scope); + hotkeyProvider.del("mod+s"); + hotkeyProvider.del(["mod+s"]); + hotkeyProvider.get("mod+s"); + hotkeyProvider.get(["mod+s"]); + hotkeyProvider.toggleCheatSheet(); + + hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description, hotkeyObj.callback); + + hotkeyProvider.bindTo(scope) + .add(hotkeyObj) + .add(hotkeyObj) + .add({ + combo: 'w', + description: 'blah blah', + callback: () => { } + }) + .add({ + combo: ['w', 'mod+w'], + description: 'blah blah', + callback: () => { } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + callback: (event, hotkey) => { + event.preventDefault(); + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+x', + callback: (event, hotkey) => { + // + } + }); + + hotkeyProvider.add({ + combo: 'ctrl+w', + description: 'Description goes here', + allowIn: ['INPUT', 'SELECT', 'TEXTAREA'], + callback(event, hotkey) { + event.preventDefault(); + } + }); +} diff --git a/types/angular-hotkeys/index.d.ts b/types/angular-hotkeys/index.d.ts index 0f0be68d8e..360e2cefbe 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -1,12 +1,10 @@ -// Type definitions for angular-hotkeys +// Type definitions for angular-hotkeys 1.7 // Project: https://github.com/chieffancypants/angular-hotkeys -// Definitions by: Jason Zhao , Stefan Steinhart +// Definitions by: Jason Zhao +// Stefan Steinhart +// Cyril Gandon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -//readme written by David Valentine - - -/// import * as ng from 'angular'; @@ -15,46 +13,123 @@ export type HotkeysProviderChained = ng.hotkeys.HotkeysProviderChained; export type Hotkey = ng.hotkeys.Hotkey; declare module 'angular' { - export namespace hotkeys { - + namespace hotkeys { interface HotkeysProvider { - template: string; - templateTitle: string; + /** + * Configurable setting to disable the cheatsheet entirely. + * @default true + */ includeCheatSheet: boolean; + /** + * Configurable setting to disable ngRoute hooks. + */ + useNgRoute: boolean; + /** + * Configurable setting for the cheat sheet title + * @default 'Keyboard Shortcuts' + */ + templateTitle: string; + /** + * Configurable settings for the cheat sheet header in HTML. + * This overrides the normal title if specified. + * @default null + */ + templateHeader: string | null; + /** + * Configurable settings for the cheat sheet footer in HTML. + * @default null + */ + templateFooter: string | null; + /** + * Cheat sheet template in the event you want to totally customize it. + */ + template: string; + /** + * Configurable setting for the cheat sheet hotkey. + * @default '?' + */ cheatSheetHotkey: string; + /** + * Configurable setting for the cheat sheet description. + * @default 'Show / hide this help menu' + */ cheatSheetDescription: string; - add(combo: string | string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(combo: string | string[], description?: string, callback?: (event: Event, hotkey: Hotkey) => void, action?: string, allowIn?: string[], persistent?: boolean): Hotkey; - add(combo: string | string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + /** + * Creates a new Hotkey and creates the Mousetrap binding. + */ + add(hotkeyObj: Hotkey): Hotkey; - add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey; + /** + * Binds the hotkey to a particular scope. + * Useful if the scope is destroyed, we can automatically destroy the hotkey binding. + * @param scope The scope to bind to + */ + bindTo(scope: IScope): HotkeysProviderChained; - bindTo(scope: ng.IScope): ng.hotkeys.HotkeysProviderChained; + /** + * Removes and unbinds a hotkey + * @param combo The keyboard combo (shortcut) or the HotKey object + */ + del(combo: string | string[] | Hotkey): void; - del(combo: string | string[]): void; - - del(hotkeyObj: ng.hotkeys.Hotkey): void; - - get(combo: string | string[]): ng.hotkeys.Hotkey; + /** + * Returns the Hotkey object + * @param combo The keyboard combo (shortcut) + */ + get(combo: string | string[]): Hotkey; + /** + * Toggles the help menu element's visiblity + */ toggleCheatSheet(): void; - + /** + * Purges all non-persistent hotkeys (such as those defined in routes) + * + * Without this, the same hotkey would get recreated everytime + * the route is accessed. + */ purgeHotkeys(): void; } interface HotkeysProviderChained { - add(combo: string | string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + add(combo: string | string[], description: string, callback: (event: Event, hotkeys: Hotkey) => void): HotkeysProviderChained; - add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + add(hotkeyObj: Hotkey): HotkeysProviderChained; } interface Hotkey { + /** + * They keyboard combo (shortcut) you want to bind to. + */ combo: string | string[]; + /** + * The description for what the combo does and is only used for the Cheat Sheet. + * If it is not supplied, it will not show up, and in effect, allows you to have unlisted hotkeys. + */ description?: string; - callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + /** + * The function to execute when the key(s) are pressed. Passes along two arguments, event and hotkey + */ + callback(event: Event, hotkey: Hotkey): void; + /** + * The type of event to listen for, such as keypress, keydown or keyup. + * Usage of this parameter is discouraged as the underlying library will pick the most suitable option automatically. + * This should only be necessary in advanced situations. + */ action?: string; - allowIn?: Array; + /** + * An array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA') + */ + allowIn?: Array<'INPUT' | 'SELECT' | 'TEXTAREA'>; + /** + * Whether the hotkey persists navigation events + */ persistent?: boolean; } } diff --git a/types/angular-hotkeys/tsconfig.json b/types/angular-hotkeys/tsconfig.json index f277241888..acb11ff247 100644 --- a/types/angular-hotkeys/tsconfig.json +++ b/types/angular-hotkeys/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "angular-hotkeys-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/angular-hotkeys/tslint.json b/types/angular-hotkeys/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/angular-hotkeys/tslint.json +++ b/types/angular-hotkeys/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index d46a51d578..ac4a1386cd 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -5,6 +5,7 @@ interface TestScope extends ng.IScope { } myApp.config(( + $mdAriaProvider: ng.material.IAriaProvider, $mdThemingProvider: ng.material.IThemingProvider, $mdIconProvider: ng.material.IIconProvider, $mdProgressCircularProvider: ng.material.IProgressCircularProvider) => { @@ -52,6 +53,9 @@ myApp.config(( return c * Math.pow(2, (t / d - 1) * 10) + b; } }); + + // Globally disables all ARIA warnings. + $mdAriaProvider.disableWarnings(); }); myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { @@ -136,6 +140,9 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material. $scope['promptDialog'] = () => { $mdDialog.show($mdDialog.prompt().initialValue('Buddy')); }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().required(true)); + }; $scope['prerenderedDialog'] = () => { $mdDialog.show({ template: 'Hello!', diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 4bfadbf9b3..92f6d46751 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-material 1.1 // Project: https://github.com/angular/material -// Definitions by: Blake Bigelow , Peter Hajdu , Davide Donadello , Geert Jansen +// Definitions by: Blake Bigelow , Peter Hajdu , Davide Donadello , Geert Jansen , Edward Knowles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -11,6 +11,10 @@ export = _; declare module 'angular' { namespace material { + interface IAriaProvider { + disableWarnings(): void; + } + interface ResolveObject { [name: string]: Injectable<(...args: any[]) => PromiseLike>; } @@ -76,6 +80,7 @@ declare module 'angular' { interface IPromptDialog extends IPresetDialog { cancel(cancel: string): IPromptDialog; + required(required: boolean): IPromptDialog; // default: false placeholder(placeholder: string): IPromptDialog; initialValue(initialValue: string): IPromptDialog; } diff --git a/types/angular-modal/angular-modal-tests.ts b/types/angular-modal/angular-modal-tests.ts index edb4d7e6ef..1f55403490 100644 --- a/types/angular-modal/angular-modal-tests.ts +++ b/types/angular-modal/angular-modal-tests.ts @@ -45,9 +45,9 @@ function withContainerAsString() { }); } -// With container as jQuery element +// With container as jQuery/JQLite element function withContainerAsJquery() { - var container: JQuery = $('body'); + var container: JQuery = angular.element('body'); btfModal({ template: '
', container: container @@ -94,6 +94,10 @@ function callingValues() { template: '
' }); modal.activate().then(() => {}, () => {}); + // activating with random locals + modal.activate({name: 'TestName'}).then(() => {}, () => {}); + // activating with genericly typed locals + modal.activate<{name: string}>({name: 'TestName'}).then(() => {}, () => {}); modal.deactivate().then(() => {}, () => {}); var isActive: boolean = modal.active(); } diff --git a/types/angular-modal/index.d.ts b/types/angular-modal/index.d.ts index 40106e955e..e817157adb 100644 --- a/types/angular-modal/index.d.ts +++ b/types/angular-modal/index.d.ts @@ -5,7 +5,6 @@ // TypeScript Version: 2.3 /// -/// declare namespace angularModal { @@ -28,7 +27,8 @@ declare namespace angularModal { } export interface AngularModal { - activate(): angular.IPromise; + activate(locals?: {}): angular.IPromise; + activate(locals: T): angular.IPromise; deactivate(): angular.IPromise; active(): boolean; } diff --git a/types/angular-sanitize/angular-sanitize-tests.ts b/types/angular-sanitize/angular-sanitize-tests.ts index b093f2bbb0..51d48db90d 100644 --- a/types/angular-sanitize/angular-sanitize-tests.ts +++ b/types/angular-sanitize/angular-sanitize-tests.ts @@ -4,5 +4,6 @@ declare var $sanitizeService: ng.sanitize.ISanitizeService; shouldBeString = $sanitizeService(shouldBeString); declare var $linky: ng.sanitize.filter.ILinky; +shouldBeString = $linky(shouldBeString); shouldBeString = $linky(shouldBeString, "target"); shouldBeString = $linky(shouldBeString, shouldBeString); diff --git a/types/angular-sanitize/index.d.ts b/types/angular-sanitize/index.d.ts index ad42ec362e..b9d16aaeb2 100644 --- a/types/angular-sanitize/index.d.ts +++ b/types/angular-sanitize/index.d.ts @@ -36,7 +36,7 @@ declare module 'angular' { * see https://docs.angularjs.org/api/ngSanitize/filter/linky */ interface ILinky { - (text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; + (text: string, target?: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; } } diff --git a/types/angular-storage/index.d.ts b/types/angular-storage/index.d.ts index 8021ba2f5e..a5f65955f5 100644 --- a/types/angular-storage/index.d.ts +++ b/types/angular-storage/index.d.ts @@ -6,10 +6,13 @@ /// +declare var _: string; +export = _; + import * as angular from 'angular'; declare module 'angular' { - export namespace a0.storage { + namespace a0.storage { interface IStoreService extends INamespacedStoreService { /** * Returns a namespaced store diff --git a/types/angular-tooltips/index.d.ts b/types/angular-tooltips/index.d.ts index d3cf83c1ec..682737756f 100644 --- a/types/angular-tooltips/index.d.ts +++ b/types/angular-tooltips/index.d.ts @@ -2,6 +2,7 @@ // Project: http://720kb.github.io/angular-tooltips // Definitions by: Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare const AngularTooltips: '720kb.tooltips'; export = AngularTooltips; diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 6d8b11bffe..88a59bdd2a 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -644,6 +644,9 @@ isolateScope = element.find('div').isolateScope(); isolateScope = element.children().isolateScope(); let element2 = angular.element(element); let elementArray = angular.element(document.querySelectorAll('div')); +let elementReadyFn = angular.element(() => { + console.log('ready'); +}); // $timeout signature tests namespace TestTimeout { @@ -704,7 +707,7 @@ class SampleDirective implements ng.IDirective { restrict = 'A'; name = 'doh'; - compile(templateElement: ng.IAugmentedJQuery) { + compile(templateElement: JQLite) { return { post: this.link }; @@ -720,7 +723,7 @@ class SampleDirective implements ng.IDirective { class SampleDirective2 implements ng.IDirective { restrict = 'EAC'; - compile(templateElement: ng.IAugmentedJQuery) { + compile(templateElement: JQLite) { return { pre: this.link }; @@ -738,7 +741,7 @@ angular.module('SameplDirective', []).directive('sampleDirective', SampleDirecti angular.module('AnotherSampleDirective', []).directive('myDirective', ['$interpolate', '$q', ($interpolate: ng.IInterpolateService, $q: ng.IQService) => { return { restrict: 'A', - link: (scope: ng.IScope, el: ng.IAugmentedJQuery, attr: ng.IAttributes) => { + link: (scope: ng.IScope, el: JQLite, attr: ng.IAttributes) => { $interpolate(attr['test'])(scope); $interpolate('', true)(scope); $interpolate('', true, 'html')(scope); @@ -866,7 +869,7 @@ angular.module('docsTimeDirective', []) }]) .directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => { return { - link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { + link(scope: ng.IScope, element: JQLite, attrs: ng.IAttributes) { let format: any; let timeoutId: any; @@ -913,7 +916,7 @@ angular.module('docsTransclusionExample', []) transclude: true, scope: {}, templateUrl: 'my-dialog.html', - link(scope: ng.IScope, element: ng.IAugmentedJQuery) { + link(scope: ng.IScope, element: JQLite) { scope['name'] = 'Jeff'; } }; @@ -1014,7 +1017,7 @@ angular.module('docsTabsExample', []) scope: { title: '@' }, - link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, tabsCtrl: any) { + link(scope: ng.IScope, element: JQLite, attrs: ng.IAttributes, tabsCtrl: any) { tabsCtrl.addPane(scope); }, templateUrl: 'my-pane.html' @@ -1095,6 +1098,18 @@ angular.module('copyExample', []) $scope.reset(); }]); +// Extending IScope for a directive, see https://github.com/DefinitelyTyped/DefinitelyTyped/issues/21160 +interface IMyScope extends angular.IScope { + myScopeProperty: boolean; +} + +angular.module('aaa').directive('directive', () => ({ + link(scope: IMyScope) { + console.log(scope.myScopeProperty); + return; + } +})); + namespace locationTests { const $location: ng.ILocationService = null; @@ -1309,3 +1324,35 @@ function toPromise(val: T): ng.IPromise { const p: ng.IPromise = null; return p; } + +const directiveCompileFn: ng.IDirectiveCompileFn = ( + templateElement: JQLite, + templateAttributes: ng.IAttributes, + transclude: ng.ITranscludeFunction + ): ng.IDirectiveLinkFn => { + return ( + scope: ng.IScope, + instanceElement: JQLite, + instanceAttributes: ng.IAttributes + ) => { + return null; + }; +}; + +interface MyScope extends ng.IScope { + foo: string; +} + +const directiveCompileFnWithGeneric: ng.IDirectiveCompileFn = ( + templateElement: JQLite, + templateAttributes: ng.IAttributes, + transclude: ng.ITranscludeFunction + ): ng.IDirectiveLinkFn => { + return ( + scope: MyScope, + instanceElement: JQLite, + instanceAttributes: ng.IAttributes + ) => { + return null; + }; +}; diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 45b9bea058..f3b64e2136 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -9,9 +9,6 @@ /// -// NOTE: @types/angular technically doesn't require TypeScript 2.3, only TypeScript 2.1. -// It has a TypeScript 2.3 header so that merging tests with @types/jquery v3 will work. - declare var angular: angular.IAngularStatic; // Support for painless dependency injection @@ -232,8 +229,8 @@ declare namespace angular { * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) * @param directiveFactory An injectable directive factory function. */ - directive(name: string, directiveFactory: Injectable): IModule; - directive(object: {[directiveName: string]: Injectable}): IModule; + directive(name: string, directiveFactory: Injectable>): IModule; + directive(object: {[directiveName: string]: Injectable>}): IModule; /** * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. * @@ -1252,8 +1249,8 @@ declare namespace angular { } interface ICompileProvider extends IServiceProvider { - directive(name: string, directiveFactory: Injectable): ICompileProvider; - directive(object: {[directiveName: string]: Injectable}): ICompileProvider; + directive(name: string, directiveFactory: Injectable>): ICompileProvider; + directive(object: {[directiveName: string]: Injectable>}): ICompileProvider; component(name: string, options: IComponentOptions): ICompileProvider; @@ -1302,6 +1299,17 @@ declare namespace angular { */ cssClassDirectivesEnabled(): boolean; cssClassDirectivesEnabled(enabled: boolean): ICompileProvider; + + /** + * Call this method to enable/disable strict component bindings check. + * If enabled, the compiler will enforce that for all bindings of a + * component that are not set as optional with ?, an attribute needs + * to be provided on the component's HTML tag. + * Defaults to false. + * See: https://docs.angularjs.org/api/ng/provider/$compileProvider#strictComponentBindingsEnabled + */ + strictComponentBindingsEnabled(): boolean; + strictComponentBindingsEnabled(enabled: boolean): ICompileProvider; } interface ICloneAttachFunction { @@ -1961,13 +1969,13 @@ declare namespace angular { // and http://docs.angularjs.org/guide/directive /////////////////////////////////////////////////////////////////////////// - interface IDirectiveFactory { - (...args: any[]): IDirective | IDirectiveLinkFn; + interface IDirectiveFactory { + (...args: any[]): IDirective | IDirectiveLinkFn; } - interface IDirectiveLinkFn { + interface IDirectiveLinkFn { ( - scope: IScope, + scope: TScope, instanceElement: JQLite, instanceAttributes: IAttributes, controller?: IController | IController[] | {[key: string]: IController}, @@ -1975,12 +1983,12 @@ declare namespace angular { ): void; } - interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; } - interface IDirectiveCompileFn { + interface IDirectiveCompileFn { ( templateElement: JQLite, templateAttributes: IAttributes, @@ -1991,11 +1999,11 @@ declare namespace angular { * that is passed to the link function instead. */ transclude: ITranscludeFunction - ): void | IDirectiveLinkFn | IDirectivePrePost; + ): void | IDirectiveLinkFn | IDirectivePrePost; } - interface IDirective { - compile?: IDirectiveCompileFn; + interface IDirective { + compile?: IDirectiveCompileFn; controller?: string | Injectable; controllerAs?: string; /** @@ -2004,7 +2012,7 @@ declare namespace angular { * relies upon bindings inside a $onInit method on the controller, instead. */ bindToController?: boolean | {[boundProperty: string]: string}; - link?: IDirectiveLinkFn | IDirectivePrePost; + link?: IDirectiveLinkFn | IDirectivePrePost; multiElement?: boolean; priority?: number; /** @@ -2077,9 +2085,7 @@ declare namespace angular { get(name: '$xhrFactory'): IXhrFactory; has(name: string): boolean; instantiate(typeConstructor: {new(...args: any[]): T}, locals?: any): T; - invoke(inlineAnnotatedFunction: any[], context?: any, locals?: any): any; - invoke(func: (...args: any[]) => T, context?: any, locals?: any): T; - invoke(func: Function, context?: any, locals?: any): any; + invoke(func: Injectable T)>, context?: any, locals?: any): T; strictDi: boolean; } diff --git a/types/angular/jqlite.d.ts b/types/angular/jqlite.d.ts index 858201fb18..a9da89cf65 100644 --- a/types/angular/jqlite.d.ts +++ b/types/angular/jqlite.d.ts @@ -684,7 +684,7 @@ interface JQuery { } interface JQueryStatic { - (element: string | Element | Document | JQuery | ArrayLike): JQLite; + (element: string | Element | Document | JQuery | ArrayLike | (() => void)): JQLite; } /** diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 92d1e026c3..5ce810f938 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -16,7 +16,7 @@ "noImplicitAny": false, "noImplicitThis": false, "strictNullChecks": false, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -25,4 +25,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/angulartics/angulartics-tests.ts b/types/angulartics/angulartics-tests.ts index 5a5660a3f8..a130ec64b2 100644 --- a/types/angulartics/angulartics-tests.ts +++ b/types/angulartics/angulartics-tests.ts @@ -1,5 +1,5 @@ import * as angular from 'angular'; -import { angulartics } from 'angulartics'; +import * as angulartics from 'angulartics'; namespace Analytics { angular.module("angulartics.app", ["angulartics"]) diff --git a/types/angulartics/index.d.ts b/types/angulartics/index.d.ts index 0d9ba1f17f..40ff202329 100644 --- a/types/angulartics/index.d.ts +++ b/types/angulartics/index.d.ts @@ -1,11 +1,13 @@ -// Type definitions for Angulartics 1.3 +// Type definitions for Angulartics 1.4 // Project: http://luisfarzati.github.io/angulartics/ -// Definitions by: Steven Fan +// Definitions by: Bateast2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as angular from 'angular'; +export = angulartics;//AMD/Require module support +export as namespace angulartics;//UMD module support declare namespace angulartics { interface IAngularticsStatic { @@ -13,41 +15,67 @@ declare namespace angulartics { } interface IAnalyticsService { - eventTrack(eventName: string, properties?: any): any; - getOptOut(): boolean; pageTrack(path: string, location?: angular.ILocationService): any; + eventTrack(eventName: string, properties?: any): any; + exceptionTrack(error: any, cause: string): any; + transactionTrack: any; setAlias(alias: string): any; - setOptOut(value: boolean): void; setUsername(username: string): any; - setUserProperties(properties: any): any; - setSuperProperties(properties: any): any; + setUserProperties(userProperties: any): any; + setUserPropertiesOnce(userProperties: any): any; + setSuperProperties(superProperties: any): any; + setSuperPropertiesOnce(superProperties: any): any; + incrementProperty(property: string, value?: any): any; + userTimings(properties: any): any; + clearCookies: any; + + getOptOut(): boolean; + setOptOut(value: boolean): void; } interface IAnalyticsServiceProvider extends angular.IServiceProvider { virtualPageviews(value: boolean): void; + trackStates(value: boolean): void; + trackRoutes(value: boolean): void; excludeRoutes(value: string[]): void; + queryKeysWhitelist(keys: string[]): void + queryKeysBlacklist(keys: string[]): void firstPageview(value: boolean): void; withBase(value: boolean): void; withAutoBase(value: boolean): void; - developerMode(value: boolean): void; trackExceptions(value: boolean): void; - trackRoutes(value: boolean): void; - trackStates(value: boolean): void; + developerMode(value: boolean): void; registerPageTrack(callback: (path: string, location?: angular.ILocationService) => any): void; registerEventTrack(callback: (eventName: string, properties?: any) => any): void; + registerTransactionTrack(callback: any): void; registerSetAlias(callback: (alias: string) => any): void; registerSetUsername(callback: (username: string) => any): void; registerSetUserProperties(callback: (userProperties: any) => any): void; + registerSetUserPropertiesOnce(callback: (userProperties: any) => any): void; registerSetSuperProperties(callback: (superProperties: any) => any): void; + registerSetSuperPropertiesOnce(callback: (superProperties: any) => any): void; + registerIncrementProperty(callback: (property: string, value?: any) => any): void; + registerUserTimings(callback: (properties: any) => any): void; + registerClearCookies(callback: any): void; settings: { pageTracking: { autoTrackingVirtualPages: boolean, autoTrackingFirstPage: boolean, + trackRelativePath: boolean, + trackRoutes: boolean, + trackStates: boolean, + autoBasePath: boolean, basePath: string, - autoBasePath: boolean + excludedRoutes: string[], + queryKeysWhitelisted: string[], + queryKeysBlacklisted: string[] }, + eventTracking: {}, + bufferFlushDelay: number, + trackExceptions: boolean, + optOut: boolean, developerMode: boolean }; } diff --git a/types/ansi-regex/ansi-regex-tests.ts b/types/ansi-regex/ansi-regex-tests.ts new file mode 100644 index 0000000000..a5787902f0 --- /dev/null +++ b/types/ansi-regex/ansi-regex-tests.ts @@ -0,0 +1,13 @@ +import ansiRegex = require("ansi-regex"); + +ansiRegex(); // $ExpectType RegExp + +// From the ansi-regex README.md +ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean +// => true + +ansiRegex().test('cake'); // $ExpectType boolean +// => false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null +// => ['\u001B[4m', '\u001B[0m'] diff --git a/types/ansi-regex/index.d.ts b/types/ansi-regex/index.d.ts new file mode 100644 index 0000000000..34890912dc --- /dev/null +++ b/types/ansi-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for ansi-regex 3.0 +// Project: https://github.com/chalk/ansi-regex#readme +// Definitions by: Manish Vachharajani +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function r(): RegExp; +export = r; diff --git a/types/ansi-regex/tsconfig.json b/types/ansi-regex/tsconfig.json new file mode 100644 index 0000000000..cf1ac84a5c --- /dev/null +++ b/types/ansi-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ansi-regex-tests.ts" + ] +} diff --git a/types/ansi-regex/tslint.json b/types/ansi-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ansi-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/apex.js/index.d.ts b/types/apex.js/index.d.ts index 20178369dc..0998ce794c 100644 --- a/types/apex.js/index.d.ts +++ b/types/apex.js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/apex/node-apex // Definitions by: Yoriki Yamaguchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/api-error-handler/api-error-handler-tests.ts b/types/api-error-handler/api-error-handler-tests.ts index 3bc39c4a7b..67afbb0fce 100644 --- a/types/api-error-handler/api-error-handler-tests.ts +++ b/types/api-error-handler/api-error-handler-tests.ts @@ -1,4 +1,3 @@ - import * as errorHandler from 'api-error-handler'; import * as express from 'express'; diff --git a/types/api-error-handler/index.d.ts b/types/api-error-handler/index.d.ts index e9337cc448..41e91a35ea 100644 --- a/types/api-error-handler/index.d.ts +++ b/types/api-error-handler/index.d.ts @@ -2,9 +2,7 @@ // Project: https://github.com/expressjs/api-error-handler // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - - +// TypeScript Version: 2.2 import * as express from 'express'; diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 17137d67dd..4214837ddf 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -777,7 +777,7 @@ declare module Microsoft.ApplicationInsights { * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. * @param accountId {string} - An optional string to represent the account associated with the authenticated user. */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): any; /** * Clears the authenticated user id and the account id from the user context. */ diff --git a/types/arcgis-to-geojson-utils/index.d.ts b/types/arcgis-to-geojson-utils/index.d.ts index 65c78a4230..95ba8db949 100644 --- a/types/arcgis-to-geojson-utils/index.d.ts +++ b/types/arcgis-to-geojson-utils/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Esri/arcgis-to-geojson-utils // Definitions by: Jeff Jacobson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/args/args-tests.ts b/types/args/args-tests.ts new file mode 100644 index 0000000000..3430288cd3 --- /dev/null +++ b/types/args/args-tests.ts @@ -0,0 +1,67 @@ +import * as args from "args"; + +args + .option("opt1", "desc") + .option("opt2", "desc", false, (value: any): any => value) + .options([ + { + name: 'opt3', + description: 'desc', + defaultValue: 1, + init: (value: any) => { }, + }, + { + name: 'opt4', + description: 'desc', + }, + ]) + .command("cm1", "desc") + .command("cm2", "desc", (value: any): void => { }, ['a']) + .example("ex1", "desc") + .examples([ + { + usage: "ex2", + description: "desc", + }, + ]); + +args.parse(['~/bin/node', '~/dir', 'arg', '--param'], { + help: true, + name: "name", + version: true, + usageFilter: (a: any): any => a, + value: "value", + mri: { + args: ['a'], + alias: { + a: "b", + c: ['d'], + }, + boolean: ['wat'], + default: { + foo: 'bar', + }, + string: ['zulu'], + unknown: (param: string): boolean => true, + }, + minimist: { + string: ['string'], + boolean: ['string'], + alias: { + bar: 'foo', + foo: ['bar1', 'bar2'], + }, + default: { + foo: 'bar', + }, + stopEarly: true, + "--": false, + unknown: (param: string): boolean => true, + }, + mainColor: "yellow", + subColor: "dim" +}); + +args.showHelp(); + +const x: string = args.sub[0]; diff --git a/types/args/index.d.ts b/types/args/index.d.ts new file mode 100644 index 0000000000..70b784564d --- /dev/null +++ b/types/args/index.d.ts @@ -0,0 +1,72 @@ +// Type definitions for args 3.0 +// Project: https://github.com/leo/args#readme +// Definitions by: Slessi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const c: args; +export = c; + +interface args { + sub: string[]; + + option(name: string | [string, string], description: string, defaultValue?: any, init?: OptionInitFunction): args; + options(list: Option[]): args; + command(name: string, description: string, init?: (name: string, sub: string[], options: ConfigurationOptions) => void, aliases?: string[]): args; + example(usage: string, description: string): args; + examples(list: Example[]): args; + parse(argv: string[], options?: ConfigurationOptions): { [key: string]: any }; + showHelp(): void; +} + +type OptionInitFunction = (value: any) => any; + +interface MriOptions { + args?: string[]; + alias?: { + [key: string]: string | string[] + }; + boolean?: string | string[]; + default?: { + [key: string]: any + }; + string?: string | string[]; + unknown?: (param: string) => boolean; +} + +interface MinimistOptions { + string?: string | string[]; + boolean?: boolean | string | string[]; + alias?: { + [key: string]: string | string[] + }; + default?: { + [key: string]: any + }; + stopEarly?: boolean; + "--"?: boolean; + unknown?: (param: string) => boolean; +} + +interface ConfigurationOptions { + help?: boolean; + name?: string; + version?: boolean; + usageFilter?: (output: any) => any; + value?: string; + mri: MriOptions; + minimist?: MinimistOptions; + mainColor: string | string[]; + subColor: string | string[]; +} + +interface Option { + name: string | [string, string]; + description: string; + init?: OptionInitFunction; + defaultValue?: any; +} + +interface Example { + usage: string; + description: string; +} diff --git a/types/error-stack-parser/tsconfig.json b/types/args/tsconfig.json similarity index 85% rename from types/error-stack-parser/tsconfig.json rename to types/args/tsconfig.json index 98f3beb1a5..d287417769 100644 --- a/types/error-stack-parser/tsconfig.json +++ b/types/args/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "error-stack-parser-tests.ts" + "args-tests.ts" ] } \ No newline at end of file diff --git a/types/args/tslint.json b/types/args/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/args/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/arr-union/arr-union-tests.ts b/types/arr-union/arr-union-tests.ts new file mode 100644 index 0000000000..7e46a3787e --- /dev/null +++ b/types/arr-union/arr-union-tests.ts @@ -0,0 +1,7 @@ +import union = require('arr-union'); + +// $ExpectType string[] +union(['a'], ['b', 'c'], ['d', 'e', 'f']); + +// $ExpectType number[] +union([1, 1], [2, 3]); diff --git a/types/arr-union/index.d.ts b/types/arr-union/index.d.ts new file mode 100644 index 0000000000..5893a55361 --- /dev/null +++ b/types/arr-union/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for arr-union 3.1 +// Project: https://github.com/jonschlinkert/arr-union +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function union(...arrays: Array>): T[]; + +export = union; diff --git a/types/arr-union/tsconfig.json b/types/arr-union/tsconfig.json new file mode 100644 index 0000000000..64a3b1efed --- /dev/null +++ b/types/arr-union/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "arr-union-tests.ts" + ] +} diff --git a/types/arr-union/tslint.json b/types/arr-union/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/arr-union/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/artillery/index.d.ts b/types/artillery/index.d.ts index d3c00d87d7..fbc5d41917 100644 --- a/types/artillery/index.d.ts +++ b/types/artillery/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/shoreditch-ops/artillery#readme // Definitions by: Kira McCoan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as request from 'request'; import * as events from 'events'; diff --git a/types/async/index.d.ts b/types/async/index.d.ts index 80f2888a8b..f1b38e8130 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -15,6 +15,7 @@ export interface AsyncResultArrayCallback { (err?: E, results?: (T | undef export interface AsyncResultObjectCallback { (err: E | undefined, results: Dictionary): void; } export interface AsyncFunction { (callback: (err?: E, result?: T) => void): void; } +export interface AsyncFunctionEx { (callback: (err?: E, ...results: T[]) => void): void; } export interface AsyncIterator { (item: T, callback: ErrorCallback): void; } export interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } export interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } @@ -174,9 +175,9 @@ export function parallel(tasks: Dictionary>, callback? export function parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; export function parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; export function whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; +export function doWhilst(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; +export function doUntil(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; diff --git a/types/async/test/explicit.ts b/types/async/test/explicit.ts index b9ea9c84ed..0c0e1a44ee 100644 --- a/types/async/test/explicit.ts +++ b/types/async/test/explicit.ts @@ -47,13 +47,13 @@ interface NumberCallback { (err?: Error, result?: number): void; } interface AsyncNumberGetter { (callback: NumberCallback): void; } var taskDict: Lookup = { - one: function(callback){ - setTimeout(function(){ + one: function(callback) { + setTimeout(function() { callback(undefined, 1); }, 200); }, - two: function(callback){ - setTimeout(function(){ + two: function(callback) { + setTimeout(function() { callback(undefined, 2); }, 100); } diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 821ccd0650..3c6c2f5dfe 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -239,16 +239,16 @@ async.parallelLimit({ function whileFn(callback: any) { - count++; - setTimeout(callback, 1000); + setTimeout(() => callback(null, ++count), 1000); } function whileTest() { return count < 5; } +function doWhileTest(count: number) { 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.doWhilst(whileFn, doWhileTest, function (err) { }); +async.doUntil(whileFn, doWhileTest, 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) }); diff --git a/types/asynciterator/asynciterator-tests.ts b/types/asynciterator/asynciterator-tests.ts new file mode 100644 index 0000000000..bd4b62c0fe --- /dev/null +++ b/types/asynciterator/asynciterator-tests.ts @@ -0,0 +1,135 @@ +import { ArrayIterator, AsyncIterator, BufferedIterator, ClonedIterator, EmptyIterator, IntegerIterator, + MultiTransformIterator, SingletonIterator, SimpleTransformIterator, TransformIterator } from "asynciterator"; + +function test_asynciterator() { + // We can't instantiate an abstract class. + const it1: AsyncIterator = {}; + const read1: number = it1.read(); + it1.each((data: number) => console.log(data)); + it1.each((data: number) => console.log(data), {}); + it1.close(); + + const it2: AsyncIterator = {}; + const read2: string = it2.read(); + it2.each((data: string) => console.log(data)); + it2.each((data: string) => console.log(data), {}); + it2.close(); + + const it3: AsyncIterator> = {}; + const read3: AsyncIterator = it3.read(); + it3.each((data: AsyncIterator) => data.each((data: string) => console.log(data))); + it3.each((data: AsyncIterator) => data.each((data: string) => console.log(data), {}), {}); + it3.close(); + + const readable2: boolean = it1.readable; + const closed2: boolean = it1.closed; + const ended2: boolean = it1.ended; + + it1.setProperty('name1', 123); + it2.setProperty('name2', 'someValue'); + const p1: number = it1.getProperty('name1'); + const p2: string = it1.getProperty('name2'); + it1.getProperty('name1', (value: number) => console.log(value)); + it1.getProperty('name2', (value: string) => console.log(value)); + const ps1: {[id: string]: any} = it1.getProperties(); + it1.setProperties({ name1: 1234, name2: 'someOtherValue' }); + it1.copyProperties(it2, [ 'name1', 'name2' ]); + + const str: string = it1.toString(); + + const stit1: SimpleTransformIterator = it1.transform(); + const stit2: SimpleTransformIterator = it1.map((number: number) => 'i' + number); + const stit3: AsyncIterator = it1.map((number: number) => 'i' + number); + const stit4: AsyncIterator = it2.map(parseInt); + const stit5: AsyncIterator = it1.map((number: number) => number + 1); + const stit6: AsyncIterator = it1.filter((number: number) => number < 10); + const stit7: AsyncIterator = it1.prepend([0, 1, 2]); + const stit8: AsyncIterator = it1.append([0, 1, 2]); + const stit9: AsyncIterator = it1.surround([0, 1, 2], [0, 1, 2]); + const stit10: AsyncIterator = it1.skip(2); + const stit11: AsyncIterator = it1.take(2); + const stit12: AsyncIterator = it1.range(2, 20); + const stit13: AsyncIterator = it1.clone(); + + const intit1: IntegerIterator = AsyncIterator.range(10, 100, 1); + const intit2: IntegerIterator = AsyncIterator.range(10, 100); + const intit3: IntegerIterator = AsyncIterator.range(10); + const intit4: IntegerIterator = AsyncIterator.range(); +} + +function test_emptyiterator() { + const it1: AsyncIterator = new EmptyIterator(); + const it2: AsyncIterator = new EmptyIterator(); +} + +function test_singletoniterator() { + const it1: AsyncIterator = new SingletonIterator(3); + const it2: AsyncIterator = new SingletonIterator('a'); +} + +function test_arrayiterator() { + const it1: AsyncIterator = new ArrayIterator([1, 2, 3]); + const it2: AsyncIterator = new ArrayIterator(['a', 'b', 'c']); +} + +function test_integeriterator() { + const it1: IntegerIterator = new IntegerIterator(); + const it2: AsyncIterator = new IntegerIterator({}); + const it3: AsyncIterator = new IntegerIterator({ start: 0 }); + const it4: AsyncIterator = new IntegerIterator({ end: 100 }); + const it5: AsyncIterator = new IntegerIterator({ step: 10 }); +} + +function test_bufferediterator() { + const it1: BufferedIterator = new BufferedIterator(); + const it2: AsyncIterator = new BufferedIterator({}); + const it3: AsyncIterator = new BufferedIterator({ maxBufferSize: 10 }); + const it4: AsyncIterator = new BufferedIterator({ autoStart: true }); +} + +function test_transformiterator() { + const it1: TransformIterator = new TransformIterator(); + const it2: AsyncIterator = new TransformIterator(); + const it3: AsyncIterator = new TransformIterator(it1); + const it4: AsyncIterator = new TransformIterator(it1, {}); + const it5: AsyncIterator = new TransformIterator(it1, { optional: true }); + const it6: AsyncIterator = new TransformIterator({ source: it1 }); + + const source: AsyncIterator = it1.source; +} + +function test_simpletransformiterator() { + const it1: SimpleTransformIterator = new SimpleTransformIterator(); + const it2: TransformIterator = new SimpleTransformIterator(); + const it3: AsyncIterator = new SimpleTransformIterator(); + const it4: AsyncIterator = new SimpleTransformIterator(it1); + const it5: AsyncIterator = new SimpleTransformIterator(it1, {}); + const it6: AsyncIterator = new SimpleTransformIterator({}); + const it7: AsyncIterator = new SimpleTransformIterator({ optional: true }); + const it8: AsyncIterator = new SimpleTransformIterator({ source: it1 }); + const it9: AsyncIterator = new SimpleTransformIterator({ offset: 2 }); + const it10: AsyncIterator = new SimpleTransformIterator({ limit: 2 }); + const it11: AsyncIterator = new SimpleTransformIterator({ prepend: [0, 1, 2] }); + const it12: AsyncIterator = new SimpleTransformIterator({ append: [0, 1, 2] }); + const it13: AsyncIterator = new SimpleTransformIterator( + { filter: (val: number) => val > 10 }); + const it14: AsyncIterator = new SimpleTransformIterator({ map: (val: number) => val + 1 }); + const it15: AsyncIterator = new SimpleTransformIterator( + { transform: (val: number, cb: (result: number) => void) => cb(val + 1) }); +} + +function test_multitransformiterator() { + const it1: MultiTransformIterator = new MultiTransformIterator(); + const it2: TransformIterator = new MultiTransformIterator(); + const it3: AsyncIterator = new MultiTransformIterator(); + const it4: AsyncIterator = new MultiTransformIterator(it1); + const it5: AsyncIterator = new MultiTransformIterator(it1, {}); + const it6: AsyncIterator = new MultiTransformIterator({}); + const it7: AsyncIterator = new MultiTransformIterator({ optional: true }); + const it8: AsyncIterator = new MultiTransformIterator({ source: it1 }); +} + +function test_clonediterator() { + const it1: ClonedIterator = new ClonedIterator(); + const it2: ClonedIterator = new ClonedIterator(it1); +} diff --git a/types/asynciterator/index.d.ts b/types/asynciterator/index.d.ts new file mode 100644 index 0000000000..a7be809137 --- /dev/null +++ b/types/asynciterator/index.d.ts @@ -0,0 +1,164 @@ +// Type definitions for asynciterator 1.1 +// Project: https://github.com/rubenverborgh/AsyncIterator#readme +// Definitions by: Ruben Taelman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +import { EventEmitter } from "events"; + +export abstract class AsyncIterator extends NodeJS.EventEmitter { + protected static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED']; + protected static INIT: 0; + protected static OPEN: 1; + protected static CLOSING: 2; + protected static CLOSED: 3; + protected static ENDED: 4; + + protected _state: number; + protected _readable: boolean; + protected _destination?: AsyncIterator; + + readable: boolean; + closed: boolean; + ended: boolean; + + constructor(); + + read(): T; + each(callback: (data: T) => void, self?: any): void; + close(): void; + + protected _changeState(newState: number, eventAsync?: boolean): void; + private _hasListeners(eventName: string | symbol): boolean; + // tslint:disable-next-line ban-types + private _addSingleListener(eventName: string | symbol, listener: Function): void; + protected _end(): void; + + getProperty(propertyName: string, callback?: (value: any) => void): any; + setProperty(propertyName: string, value: any): void; + getProperties(): {[id: string]: any}; + setProperties(properties: {[id: string]: any}): void; + copyProperties(source: AsyncIterator, propertyNames: string[]): void; + + toString(): string; + protected _toStringDetails(): string; + + transform(options?: SimpleTransformIteratorOptions): SimpleTransformIterator; + map(mapper: (item: T) => T2, self?: object): SimpleTransformIterator; + filter(filter: (item: T) => boolean, self?: object): SimpleTransformIterator; + prepend(items: T[]): SimpleTransformIterator; + append(items: T[]): SimpleTransformIterator; + surround(prepend: T[], append: T[]): SimpleTransformIterator; + skip(offset: number): SimpleTransformIterator; + take(limit: number): SimpleTransformIterator; + range(start: number, end: number): SimpleTransformIterator; + clone(): ClonedIterator; + + static range(start?: number, end?: number, step?: number): IntegerIterator; +} + +export class EmptyIterator extends AsyncIterator { + _state: 4; +} + +export class SingletonIterator extends AsyncIterator { + constructor(item?: T); +} + +export class ArrayIterator extends AsyncIterator { + constructor(items?: T[]); +} + +export interface IntegerIteratorOptions { + step?: number; + end?: number; + start?: number; +} + +export class IntegerIterator extends AsyncIterator { + protected _step: number; + protected _last: number; + protected _next: number; + + constructor(options?: IntegerIteratorOptions); +} + +export interface BufferedIteratorOptions { + maxBufferSize?: number; + autoStart?: boolean; +} + +export class BufferedIterator extends AsyncIterator { + maxBufferSize: number; + protected _pushedCount: number; + protected _buffer: T[]; + + protected _init(autoStart: boolean): void; + protected _begin(done: () => void): void; + protected _read(count: number, done: () => void): void; + protected _push(item: T): void; + protected _fillBuffer(): void; + protected _completeClose(): void; + protected _flush(done: () => void): void; + + constructor(options?: BufferedIteratorOptions); +} + +export interface TransformIteratorOptions extends BufferedIteratorOptions { + optional?: boolean; + source?: AsyncIterator; +} + +export class TransformIterator extends BufferedIterator { + protected _optional: boolean; + source: AsyncIterator; + + protected _validateSource(source: AsyncIterator, allowDestination?: boolean): void; + protected _transform(item: S, done: (result: T) => void): void; + protected _closeWhenDone(): void; + + constructor(source?: AsyncIterator | TransformIteratorOptions, options?: TransformIteratorOptions); +} + +export interface SimpleTransformIteratorOptions extends TransformIteratorOptions { + offset?: number; + limit?: number; + prepend?: T[]; + append?: T[]; + + filter?(item: S): boolean; + map?(item: S): T; + transform?(item: S, callback: (result: T) => void): void; +} + +export class SimpleTransformIterator extends TransformIterator { + protected _offset: number; + protected _limit: number; + protected _prepender?: ArrayIterator; + protected _appender?: ArrayIterator; + + protected _filter?(item: S): boolean; + protected _map?(item: S): T; + protected _transform(item: S, done: (result: T) => void): void; + + protected _insert(inserter: AsyncIterator, done: () => void): void; + + constructor(source?: AsyncIterator | SimpleTransformIteratorOptions, + options?: SimpleTransformIteratorOptions); +} + +export class MultiTransformIterator extends TransformIterator { + _transformerQueue: S[]; + + protected _createTransformer(): AsyncIterator; + + constructor(source?: AsyncIterator | TransformIteratorOptions, options?: TransformIteratorOptions); +} + +export class ClonedIterator extends TransformIterator { + _readPosition: number; + + constructor(source?: AsyncIterator); +} diff --git a/types/asynciterator/tsconfig.json b/types/asynciterator/tsconfig.json new file mode 100644 index 0000000000..8b8b919abc --- /dev/null +++ b/types/asynciterator/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asynciterator-tests.ts" + ] +} diff --git a/types/asynciterator/tslint.json b/types/asynciterator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/asynciterator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/atom-keymap/atom-keymap-tests.ts b/types/atom-keymap/atom-keymap-tests.ts index ad886ae22a..ac013b07eb 100644 --- a/types/atom-keymap/atom-keymap-tests.ts +++ b/types/atom-keymap/atom-keymap-tests.ts @@ -1,8 +1,9 @@ +import { Disposable } from "event-kit"; import KeymapManager = require("atom-keymap"); import * as ImportTest from "atom-keymap"; declare const element: HTMLElement; -declare let sub: EventKit.Disposable; +declare let sub: Disposable; declare const event: KeyboardEvent; // NPM Examples =============================================================== diff --git a/types/atom-keymap/index.d.ts b/types/atom-keymap/index.d.ts index a0571323a9..1d67a20ba2 100644 --- a/types/atom-keymap/index.d.ts +++ b/types/atom-keymap/index.d.ts @@ -4,15 +4,17 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -/// +import { Disposable } from "event-kit"; declare global { namespace AtomKeymap { - /** The event objects that are passed into the callbacks which the user provides to + /** + * The event objects that are passed into the callbacks which the user provides to * specific API calls. */ namespace Events { - /** This custom subclass of CustomEvent exists to provide the ::abortKeyBinding + /** + * This custom subclass of CustomEvent exists to provide the ::abortKeyBinding * method, as well as versions of the ::stopPropagation methods that record the * intent to stop propagation so event bubbling can be properly simulated for * detached elements. @@ -70,12 +72,14 @@ declare global { } interface AddedKeystrokeResolver { - /** The currently resolved keystroke string. If your function returns a falsy + /** + * The currently resolved keystroke string. If your function returns a falsy * value, this is how Atom will resolve your keystroke. */ keystroke: string; - /** The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation + /** + * The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation * for more details. */ event: KeyboardEvent; @@ -83,7 +87,8 @@ declare global { /** The OS-specific name of the current keyboard layout. */ layoutName: string; - /** An object mapping DOM 3 `KeyboardEvent.code` values to objects with the + /** + * An object mapping DOM 3 `KeyboardEvent.code` values to objects with the * typed character for that key in each modifier state, based on the current * operating system layout. */ @@ -91,7 +96,8 @@ declare global { } } - /** The option objects that the user is expected to fill out and provide to + /** + * The option objects that the user is expected to fill out and provide to * specific API calls. */ namespace Options { @@ -120,7 +126,8 @@ declare global { /** Determines whether the given keystroke matches any contained within this binding. */ matches(keystroke: string): boolean; - /** Compare another KeyBinding to this instance. + /** + * Compare another KeyBinding to this instance. * Returns <= -1 if the argument is considered lesser or of lower priority. * Returns 0 if this binding is equivalent to the argument. * Returns >= 1 if the argument is considered greater or of higher priority. @@ -128,7 +135,8 @@ declare global { compare(other: KeyBinding): number; } - /** Allows commands to be associated with keystrokes in a context-sensitive way. + /** + * Allows commands to be associated with keystrokes in a context-sensitive way. * In Atom, you can access a global instance of this object via `atom.keymaps`. */ interface KeymapManager { @@ -143,29 +151,30 @@ declare global { destroy(): void; // Event Subscription - /** Invoke the given callback when one or more keystrokes completely match a key binding. */ + /** + * Invoke the given callback when one or more keystrokes completely match a + * key binding. + */ onDidMatchBinding(callback: (event: Events.FullKeybindingMatch) => void): - EventKit.Disposable; + Disposable; /** Invoke the given callback when one or more keystrokes partially match a binding. */ onDidPartiallyMatchBindings(callback: (event: Events.PartialKeybindingMatch) => - void): EventKit.Disposable; + void): Disposable; /** Invoke the given callback when one or more keystrokes fail to match any bindings. */ onDidFailToMatchBinding(callback: (event: Events.FailedKeybindingMatch) => - void): EventKit.Disposable; + void): Disposable; /** Invoke the given callback when a keymap file is reloaded. */ - onDidReloadKeymap(callback: (event: Events.KeymapLoaded) => void): - EventKit.Disposable; + onDidReloadKeymap(callback: (event: Events.KeymapLoaded) => void): Disposable; /** Invoke the given callback when a keymap file is unloaded. */ - onDidUnloadKeymap(callback: (event: Events.KeymapLoaded) => void): - EventKit.Disposable; + onDidUnloadKeymap(callback: (event: Events.KeymapLoaded) => void): Disposable; /** Invoke the given callback when a keymap file not able to be loaded. */ onDidFailToReadFile(callback: (error: Events.FailedKeymapFileRead) => void): - EventKit.Disposable; + Disposable; // Adding and Removing Bindings /** Construct KeyBindings from an object grouping them by CSS selector. */ @@ -174,7 +183,7 @@ declare global { /** Add sets of key bindings grouped by CSS selector. */ add(source: string, bindings: { [key: string]: { [key: string]: string }}, - priority?: number): EventKit.Disposable; + priority?: number): Disposable; // Accessing Bindings /** Get all current key bindings. */ @@ -192,13 +201,15 @@ declare global { loadKeymap(bindingsPath: string, options?: { watch?: boolean, priority?: number }): void; - /** Cause the keymap to reload the key bindings file at the given path whenever + /** + * Cause the keymap to reload the key bindings file at the given path whenever * it changes. */ watchKeymap(filePath: string, options?: { priority: number }): void; // Managing Keyboard Events - /** Dispatch a custom event associated with the matching key binding for the + /** + * Dispatch a custom event associated with the matching key binding for the * given `KeyboardEvent` if one can be found. */ handleKeyboardEvent(event: KeyboardEvent): void; @@ -208,9 +219,10 @@ declare global { /** Customize translation of raw keyboard events to keystroke strings. */ addKeystrokeResolver(resolver: (event: Events.AddedKeystrokeResolver) => string): - EventKit.Disposable; + Disposable; - /** Get the number of milliseconds allowed before pending states caused by + /** + * Get the number of milliseconds allowed before pending states caused by * partial matches of multi-keystroke bindings are terminated. */ getPartialMatchTimeout(): number; diff --git a/types/atom-keymap/tsconfig.json b/types/atom-keymap/tsconfig.json index f501df325f..8a17cc061c 100644 --- a/types/atom-keymap/tsconfig.json +++ b/types/atom-keymap/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/atom-keymap/tslint.json b/types/atom-keymap/tslint.json index d1318cfc63..e0508241c7 100644 --- a/types/atom-keymap/tslint.json +++ b/types/atom-keymap/tslint.json @@ -1,36 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "class-name": true, "indent": [true, "spaces", 4], - "jsdoc-format": true, - "max-line-length": [true, 110], - "quotemark": [true, "double", "avoid-escape"], - "trailing-comma": [true, { - "multiline": { "objects": "always", "arrays": "always", "functions": "never" }, - "singleline": { "objects": "never", "arrays": "never", "functions": "never" } - }], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type", - "check-typecast", - "check-rest-spread", - "check-preblock" - ], - // Soon to be defaults. - "arrow-return-shorthand": [true, "multiline"], - "no-any": true, - "no-floating-promises": true, - "no-unbound-method": true, - "no-unsafe-any": true, - "number-literal-format": true, - "restrict-plus-operands": true, - "return-undefined": true, - "switch-final-break": true + "max-line-length": [true, 100], + "no-any": true } } diff --git a/types/atom-mocha-test-runner/atom-mocha-test-runner-tests.ts b/types/atom-mocha-test-runner/atom-mocha-test-runner-tests.ts index a6f3741ca8..0bc8205095 100644 --- a/types/atom-mocha-test-runner/atom-mocha-test-runner-tests.ts +++ b/types/atom-mocha-test-runner/atom-mocha-test-runner-tests.ts @@ -1,3 +1,4 @@ +import { AtomEnvironment, TestRunnerParams } from "atom"; import { createRunner } from "atom-mocha-test-runner"; import defaultMochaRunner = require("atom-mocha-test-runner"); @@ -20,12 +21,12 @@ testRunner = createRunner({ testSuffixes: ["test.file"], }); -declare const atom: AtomCore.AtomEnvironment; +declare const atom: AtomEnvironment; declare const blob: object; declare let num: number; async function runTests(): Promise { - const runnerArgs: AtomCore.Structures.TestRunnerArgs = { + const runnerArgs: TestRunnerParams = { testPaths: ["/var/test"], logFile: "/var/log", headless: false, diff --git a/types/atom-mocha-test-runner/index.d.ts b/types/atom-mocha-test-runner/index.d.ts index e985648b02..3a842f4a5c 100644 --- a/types/atom-mocha-test-runner/index.d.ts +++ b/types/atom-mocha-test-runner/index.d.ts @@ -5,7 +5,8 @@ // TypeScript Version: 2.3 /// -/// + +import { TestRunner } from "atom"; interface AtomMochaOptions { /** Which reporter to use on the terminal. */ @@ -30,9 +31,9 @@ interface AtomMochaOptions { // module.exports = createRunner() // module.exports.createRunner = createRunner // Which is what we're trying to model here. -interface TestRunnerExport extends AtomCore.TestRunner { +interface TestRunnerExport extends TestRunner { createRunner(options?: AtomMochaOptions, mochaConfigFunction?: - (mocha: Mocha) => void): AtomCore.TestRunner; + (mocha: Mocha) => void): TestRunner; } declare const runner: TestRunnerExport; diff --git a/types/atom-mocha-test-runner/tsconfig.json b/types/atom-mocha-test-runner/tsconfig.json index 22df333ccd..c6e9fb20c0 100644 --- a/types/atom-mocha-test-runner/tsconfig.json +++ b/types/atom-mocha-test-runner/tsconfig.json @@ -9,7 +9,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/atom-mocha-test-runner/tslint.json b/types/atom-mocha-test-runner/tslint.json index 7238e43729..e0508241c7 100644 --- a/types/atom-mocha-test-runner/tslint.json +++ b/types/atom-mocha-test-runner/tslint.json @@ -1,36 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "class-name": true, "indent": [true, "spaces", 4], - "jsdoc-format": true, "max-line-length": [true, 100], - "quotemark": [true, "double", "avoid-escape"], - "trailing-comma": [true, { - "multiline": { "objects": "always", "arrays": "always", "functions": "never" }, - "singleline": { "objects": "never", "arrays": "never", "functions": "never" } - }], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type", - "check-typecast", - "check-rest-spread", - "check-preblock" - ], - // Soon to be defaults. - "arrow-return-shorthand": [true, "multiline"], - "no-any": true, - "no-floating-promises": true, - "no-unbound-method": true, - "no-unsafe-any": true, - "number-literal-format": true, - "restrict-plus-operands": true, - "return-undefined": true, - "switch-final-break": true + "no-any": true } } diff --git a/types/atom/README.md b/types/atom/README.md deleted file mode 100644 index 757c4cdeca..0000000000 --- a/types/atom/README.md +++ /dev/null @@ -1,60 +0,0 @@ -## Atom API Type Definitions - -TypeScript type definitions for the [Atom Text Editor](https://atom.io/) public API, which is used to develop packages for the editor. Documentation for the public API can be found [here](https://atom.io/docs/api/v1.21.0/). - -### Exports - -#### The "atom" Variable - -These definitions declare a global static variable named "atom" as ambient. Once these definitions have been referenced within your project, you will be able to access properties and member functions from the [AtomEnvironment](https://atom.io/docs/api/v1.21.0/AtomEnvironment) class off of this variable, as it is an instance of that class. - -```ts -if (atom.inDevMode()) {} -``` - -#### The Atom Namespace - -All of the types used by or referenced by the Atom public API have been pulled into the Atom namespace, providing a consistent and easy way to access each of them, without having to care about where that type actually lives within the Atom codebase. - -```ts -function example(buffer: Atom.TextBuffer) {} -``` - -#### The AtomCore Namespace - -All classes which are core to Atom itself have been provided under the AtomCore namespace. - -```ts -function example(cursor: AtomCore.Cursor) {} -``` - -### Service Type Definitions - -There are many services provided by other Atom packages that you may want to use within your own Atom package. We bundle type definitions for several of these services with these type definitions. All type definitions for services are available only through ES6 imports. - -```ts -import { AutocompleteProvider } from "atom/autocomplete-plus"; -let completionProvider: AutocompleteProvider; -``` - -The currently supported services are: -- [Autocomplete](https://github.com/atom/autocomplete-plus) (atom/autocomplete-plus) -- [Linter](https://github.com/atom/linter) (atom/linter) -- [Status Bar](https://github.com/atom/status-bar) (atom/status-bar) - -### Exposing Private Methods and Properties - -[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within Atom. As an example, if we wanted to reveal the private ```triggerActivationHook``` method within the PackageManager class, then we would create a file with the following contents: - -```ts -// <>.d.ts - -declare namespace AtomCore { - interface PackageManager { - triggerActivationHook(name: string): void; - triggerDeferredActivationHooks(): void; - } -} -``` - -Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the PackageManager class without TypeScript reporting errors. diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index 233d8a4e5a..e0699463b1 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -12,59 +12,59 @@ declare let regExp: RegExp; declare let element: HTMLElement; declare let elements: HTMLElement[]; declare const div: HTMLDivElement; -declare const keyboardEvent: KeyboardEvent; +declare const event: KeyboardEvent; -declare let buffer: TextBuffer.TextBuffer; -declare const color: AtomCore.Color; -declare let cursor: AtomCore.Cursor; -declare let cursors: AtomCore.Cursor[]; -declare let decoration: AtomCore.Decoration; -declare let decorations: AtomCore.Decoration[]; -declare let decorationLayerProps: AtomCore.Options.DecorationLayerProps; -declare let dir: PathWatcher.Directory; -declare let dirs: PathWatcher.Directory[]; -declare let displayMarker: TextBuffer.DisplayMarker; -declare let displayMarkers: TextBuffer.DisplayMarker[]; -declare let displayMarkerLayer: TextBuffer.DisplayMarkerLayer; -declare let dock: AtomCore.Dock; -declare let editor: AtomCore.TextEditor; -declare let editors: AtomCore.TextEditor[]; -declare let emitter: EventKit.Emitter; -declare let file: PathWatcher.File; -declare let grammar: FirstMate.Grammar; -declare let grammars: FirstMate.Grammar[]; -declare let gutter: AtomCore.Gutter; -declare let gutters: AtomCore.Gutter[]; -declare let historyPaths: AtomCore.Structures.HistoryProject[]; -declare let layerDecoration: AtomCore.LayerDecoration; -declare let marker: TextBuffer.Marker; -declare let markers: TextBuffer.Marker[]; -declare let markerLayer: TextBuffer.MarkerLayer; -declare let notification: AtomCore.Notification; -declare let notifications: AtomCore.Notification[]; -declare let pack: AtomCore.Package; -declare let packs: AtomCore.Package[]; -declare let pane: AtomCore.Pane; -declare let panes: AtomCore.Pane[]; -declare let paneContainer: AtomCore.Dock|AtomCore.WorkspaceCenter; -declare let panel: AtomCore.Panel; -declare let panels: AtomCore.Panel[]; -declare let pos: TextBuffer.Point; -declare let posArr: TextBuffer.Point[]; -declare let project: AtomCore.Project; -declare let range: TextBuffer.Range; -declare let ranges: TextBuffer.Range[]; -declare let registry: FirstMate.GrammarRegistry; -declare let repository: AtomCore.GitRepository; -declare let repositories: AtomCore.GitRepository[]; -declare let scopeDescriptor: AtomCore.ScopeDescriptor; -declare let selection: AtomCore.Selection; -declare let selections: AtomCore.Selection[]; -declare let styleManager: AtomCore.StyleManager; -declare let subscription: EventKit.Disposable; -declare let subscriptions: EventKit.CompositeDisposable; -declare let tooltips: AtomCore.Structures.Tooltip[]; -declare let workspaceCenter: AtomCore.WorkspaceCenter; +declare let buffer: Atom.TextBuffer; +declare const color: Atom.Color; +declare let cursor: Atom.Cursor; +declare let cursors: Atom.Cursor[]; +declare let decoration: Atom.Decoration; +declare let decorations: Atom.Decoration[]; +declare let decorationLayerProps: Atom.DecorationLayerOptions; +declare let dir: Atom.Directory; +declare let dirs: Atom.Directory[]; +declare let displayMarker: Atom.DisplayMarker; +declare let displayMarkers: Atom.DisplayMarker[]; +declare let displayMarkerLayer: Atom.DisplayMarkerLayer; +declare let dock: Atom.Dock; +declare let editor: Atom.TextEditor; +declare let editors: Atom.TextEditor[]; +declare let emitter: Atom.Emitter; +declare let file: Atom.File; +declare let grammar: Atom.Grammar; +declare let grammars: Atom.Grammar[]; +declare let gutter: Atom.Gutter; +declare let gutters: Atom.Gutter[]; +declare let historyPaths: Atom.ProjectHistory[]; +declare let layerDecoration: Atom.LayerDecoration; +declare let marker: Atom.Marker; +declare let markers: Atom.Marker[]; +declare let markerLayer: Atom.MarkerLayer; +declare let notification: Atom.Notification; +declare let notifications: Atom.Notification[]; +declare let pack: Atom.Package; +declare let packs: Atom.Package[]; +declare let pane: Atom.Pane; +declare let panes: Atom.Pane[]; +declare let paneContainer: Atom.Dock|Atom.WorkspaceCenter; +declare let panel: Atom.Panel; +declare let panels: Atom.Panel[]; +declare let pos: Atom.Point; +declare let posArr: Atom.Point[]; +declare let project: Atom.Project; +declare let range: Atom.Range; +declare let ranges: Atom.Range[]; +declare let registry: Atom.GrammarRegistry; +declare let repository: Atom.GitRepository; +declare let repositories: Atom.GitRepository[]; +declare let scopeDescriptor: Atom.ScopeDescriptor; +declare let selection: Atom.Selection; +declare let selections: Atom.Selection[]; +declare let styleManager: Atom.StyleManager; +declare let subscription: Atom.Disposable; +declare let subscriptions: Atom.CompositeDisposable; +declare let tooltips: Atom.Tooltip[]; +declare let workspaceCenter: Atom.WorkspaceCenter; // AtomEnvironment ============================================================ function testAtomEnvironment() { @@ -125,8 +125,8 @@ function testAtomEnvironment() { }); subscription = atom.workspace.observeTextEditors((editor) => { - subscription = editor.onDidStopChanging((keyboardEvent) => { - for (const change of keyboardEvent.changes) { + subscription = editor.onDidStopChanging((event) => { + for (const change of event.changes) { change.newExtent; } }); @@ -276,9 +276,6 @@ function testCommandRegistry() { // CompositeDisposable ======================================================== function testCompositeDisposable() { - // Properties - bool = subscriptions.disposed; - // Construction and Lifecycle subscriptions = new Atom.CompositeDisposable(); new Atom.CompositeDisposable(subscription); @@ -482,7 +479,7 @@ function testCursor() { // TestRunner ================================================================= function testTestRunner() { - const testRunner: AtomCore.TestRunner = (params) => { + const testRunner: Atom.TestRunner = (params) => { const delegate = params.buildDefaultApplicationDelegate(); const environment = params.buildAtomEnvironment({ applicationDelegate: delegate, @@ -803,7 +800,6 @@ function testDisplayMarkerLayer() { // Disposable ================================================================= function testDisposable() { - bool = subscription.disposed; if (subscription.disposalAction) subscription.disposalAction(); subscription.dispose(); } @@ -829,8 +825,12 @@ function testDock() { subscription = dock.onDidChangeActivePane(pane => pane.activate()); subscription = dock.observeActivePane(pane => pane.activate()); subscription = dock.onDidAddPaneItem(event => event.index && event.item && event.pane); - subscription = dock.onWillDestroyPaneItem(event => event.index && event.item && event.pane); - subscription = dock.onDidDestroyPaneItem(event => event.index && event.item && event.pane); + subscription = dock.onWillDestroyPaneItem(event => { + event.index && event.item && event.pane; + }); + subscription = dock.onDidDestroyPaneItem(event => { + event.index && event.item && event.pane; + }); // Pane Items objs = dock.getPaneItems(); @@ -847,8 +847,6 @@ function testDock() { function testEmitter() { emitter = new Atom.Emitter(); - bool = emitter.disposed; - emitter.clear(); emitter.dispose(); @@ -1113,7 +1111,7 @@ function testKeymapManager() { subscription = manager.add("a", {}, 0); // Accessing Bindings - let bindings: AtomKeymap.KeyBinding[] = manager.getKeyBindings(); + let bindings: Atom.KeyBinding[] = manager.getKeyBindings(); bindings = manager.findKeyBindings(); bindings = manager.findKeyBindings({ command: "a" }); bindings = manager.findKeyBindings({ keystrokes: "a" }); @@ -1127,8 +1125,8 @@ function testKeymapManager() { manager.loadKeymap("Test.file", { watch: true, priority: 0}); // Managing Keyboard Events - manager.handleKeyboardEvent(keyboardEvent); - manager.keystrokeForKeyboardEvent(keyboardEvent); + manager.handleKeyboardEvent(event); + manager.keystrokeForKeyboardEvent(event); subscription = manager.addKeystrokeResolver((event): string => { event.layoutName; @@ -1151,10 +1149,6 @@ function testLayerDecoration() { function testMarker() { // Properties num = marker.id; - bool = marker.tailed; - bool = marker.reversed; - bool = marker.valid; - str = marker.invalidate; // Lifecycle marker = marker.copy({ @@ -1301,8 +1295,8 @@ function testNotification() { }); // Event Subscription - subscription = notification.onDidDismiss(notification => notification.dismissed); - subscription = notification.onDidDisplay(notification => notification.timestamp); + subscription = notification.onDidDismiss(notification => notification.getType()); + subscription = notification.onDidDisplay(notification => notification.getMessage()); // Methods str = notification.getType(); @@ -1377,7 +1371,7 @@ function testPackageManager() { subscription = atom.packages.onDidActivatePackage(pack => pack.name); subscription = atom.packages.onDidDeactivatePackage(pack => pack.path); subscription = atom.packages.onDidLoadPackage(pack => pack.isCompatible()); - subscription = atom.packages.onDidUnloadPackage(pack => pack.bundledPackage); + subscription = atom.packages.onDidUnloadPackage(pack => pack.name); // Package system data str = atom.packages.getApmPath(); @@ -1618,7 +1612,7 @@ function testPoint() { point.isGreaterThanOrEqual([0, 0]); // Operations - const frozenPoint: Readonly = point.freeze(); + const frozenPoint: Readonly = point.freeze(); point = point.translate(point); point.translate([0, 0]); @@ -1644,7 +1638,7 @@ function testProject() { }); subscription = project.onDidAddBuffer(buffer => buffer.id); - subscription = project.observeBuffers(buffer => buffer.file); + subscription = project.observeBuffers(buffer => buffer.getUri()); // Accessing the git repository repositories = project.getRepositories(); @@ -1707,7 +1701,7 @@ function testRange() { nums = range.getRows(); // Operations - const frozenRange: Readonly = range.freeze(); + const frozenRange: Readonly = range.freeze(); range = range.union(range); range = range.translate(pos); @@ -1923,7 +1917,7 @@ function testStyleManager() { // Task ======================================================================= function testTask() { - let task: AtomCore.Task = Atom.Task.once("File.path", {}, () => {}); + let task: Atom.Task = Atom.Task.once("File.path", {}, () => {}); task = new Atom.Task("File.path"); task.start({}, () => {}); @@ -2282,7 +2276,7 @@ function testTextEditor() { subscription = editor.onDidChangeSoftWrapped(softWrapped => {}); subscription = editor.onDidChangeEncoding(encoding => {}); subscription = editor.observeGrammar(grammar => grammar.name); - subscription = editor.onDidChangeGrammar(grammar => grammar.scopeName); + subscription = editor.onDidChangeGrammar(grammar => grammar.name); subscription = editor.onDidChangeModified(modified => {}); subscription = editor.onDidConflict(() => {}); subscription = editor.onWillInsertText(event => event.cancel && event.text); @@ -2997,8 +2991,9 @@ function testWorkspace() { subscription = atom.workspace.observeActivePane(pane => pane.activate()); subscription = atom.workspace.onDidAddPaneItem(event => event.index && event.item && event.pane); - subscription = atom.workspace.onWillDestroyPaneItem(event => event.index && - event.item && event.pane); + subscription = atom.workspace.onWillDestroyPaneItem(event => { + event.index && event.item && event.pane; + }); subscription = atom.workspace.onDidDestroyPaneItem(event => event.index && event.item && event.pane); subscription = atom.workspace.onDidAddTextEditor(event => event.index && event.pane && @@ -3045,7 +3040,13 @@ function testWorkspace() { if (result) obj = result; } - atom.workspace.addOpener(() => element); + atom.workspace.addOpener((uri) => { + if (uri === "test://") { + return { + getTitle: () => "Test Title", + }; + } + }); atom.workspace.buildTextEditor(obj); diff --git a/types/atom/autocomplete-plus/config.d.ts b/types/atom/autocomplete-plus/config.d.ts new file mode 100644 index 0000000000..e4c9f3a2d4 --- /dev/null +++ b/types/atom/autocomplete-plus/config.d.ts @@ -0,0 +1,128 @@ +import "../index"; + +declare module "atom" { + interface ConfigValues { + /** + * Suggestions will show as you type if this preference is enabled. If it is + * disabled, you can still see suggestions by using the keymapping for + * 'autocomplete-plus:activate' (shown below). + */ + "autocomplete-plus.enableAutoActivation": boolean; + + /** + * If you are experiencing performance issues when typing, you should try + * increasing this value to a non-zero number (e.g. 100). + */ + "autocomplete-plus.autoActivationDelay": number; + + /** The suggestion list will only show this many suggestions. */ + "autocomplete-plus.maxVisibleSuggestions": number; + + /** + * You should use the key(s) indicated here to confirm a suggestion from the + * suggestion list and have it inserted into the file. + */ + "autocomplete-plus.confirmCompletion": + | "tab" + | "enter" + | "tab and enter" + | "tab always, enter when suggestion explicitly selected"; + + /** + * Disable this if you want to bind your own keystrokes to move around the + * suggestion list. You will also need to add definitions to your keymap. + */ + "autocomplete-plus.useCoreMovementCommands": boolean; + + /** + * Suggestions will not be provided for files matching this list, e.g. *.md + * for Markdown files. To blacklist more than one file extension, use comma + * as a separator, e.g. ["*.md", "*.txt"] (both Markdown and text files). + */ + "autocomplete-plus.fileBlacklist": string[]; + + /** Suggestions will not be provided for scopes matching this list. */ + "autocomplete-plus.scopeBlacklist": string[]; + + /** + * For grammars with no registered provider(s), the default provider will + * include completions from all buffers, instead of just the buffer you are + * currently editing. + */ + "autocomplete-plus.includeCompletionsFromAllBuffers": boolean; + + /** + * Fuzzy searching is performed if this is disabled; if it is enabled, suggestions + * must begin with the prefix from the current word. + */ + "autocomplete-plus.strictMatching": boolean; + + /** + * Only autocomplete when you've typed at least this many characters. + * Note: May not affect external providers. + */ + "autocomplete-plus.minimumWordLength": number; + + /** + * The package comes with a built-in provider that will provide suggestions + * using the words in your current buffer or all open buffers. You will get + * better suggestions by installing additional autocomplete+ providers. + * To stop using the built-in provider, disable this option. + */ + "autocomplete-plus.enableBuiltinProvider": boolean; + + /** Don't use the built-in provider for these selector(s). */ + "autocomplete-plus.builtinProviderBlacklist": string; + + /** + * If enabled, typing `backspace` will show the suggestion list if suggestions + * are available. If disabled, suggestions will not be shown while backspacing. + */ + "autocomplete-plus.backspaceTriggersAutocomplete": boolean; + + /** + * If enabled, automatically insert suggestion on manual activation with + * 'autocomplete-plus:activate' when there is only one match. + */ + "autocomplete-plus.enableAutoConfirmSingleSuggestion": boolean; + + /** + * With 'Cursor' the suggestion list appears at the cursor's position. + * With 'Word' it appears at the beginning of the word that's being completed. + */ + "autocomplete-plus.suggestionListFollows": "Word"|"Cursor"; + + /** + * If you're having trouble with autocomplete, you may consider falling back + * to the Symbol provider and filing an issue. + */ + "autocomplete-plus.defaultProvider": "Subsequence"|"Symbol"; + + /** Don't auto-activate when any of these classes are present in the editor. */ + "autocomplete-plus.suppressActivationForEditorClasses": string[]; + + /** + * Completing a suggestion consumes text following the cursor matching the + * suffix of the chosen suggestion. + */ + "autocomplete-plus.consumeSuffix": boolean; + + /** + * -EXPERIMENTAL- Prefers runs of consecutive characters, acronyms and start + * of words. + */ + "autocomplete-plus.useAlternateScoring": boolean; + + /** Gives words near the cursor position a higher score than those far away. */ + "autocomplete-plus.useLocalityBonus": boolean; + + /** Identifies non-latin alphabet characters as letters. */ + "autocomplete-plus.enableExtendedUnicodeSupport": boolean; + + /** + * Should similar suggestions be removed from the list? If so how to determine + * they are similar. + */ + "autocomplete-plus.similarSuggestionRemoval": "none"|"textOrSnippet"; + } +} diff --git a/types/atom/autocomplete-plus.d.ts b/types/atom/autocomplete-plus/index.d.ts similarity index 72% rename from types/atom/autocomplete-plus.d.ts rename to types/atom/autocomplete-plus/index.d.ts index 62f8607aea..2e91a81262 100644 --- a/types/atom/autocomplete-plus.d.ts +++ b/types/atom/autocomplete-plus/index.d.ts @@ -1,16 +1,20 @@ // Autocomplete Plus 2.x // https://atom.io/packages/autocomplete-plus +/// + +import { Point, ScopeDescriptor, TextEditor } from "../index"; + /** The parameters passed into getSuggestions by Autocomplete+. */ export interface SuggestionsRequestedEvent { /** The current TextEditor. */ - editor: AtomCore.TextEditor; + editor: TextEditor; /** The position of the cursor. */ - bufferPosition: TextBuffer.Point; + bufferPosition: Point; /** The scope descriptor for the current cursor position. */ - scopeDescriptor: AtomCore.ScopeDescriptor; + scopeDescriptor: ScopeDescriptor; /** The prefix for the word immediately preceding the current cursor position. */ prefix: string; @@ -21,26 +25,30 @@ export interface SuggestionsRequestedEvent { /** The parameters passed into onDidInsertSuggestion by Autocomplete+. */ export interface SuggestionInsertedEvent { - editor: AtomCore.TextEditor; - triggerPosition: TextBuffer.Point; + editor: TextEditor; + triggerPosition: Point; suggestion: TextSuggestion|SnippetSuggestion; } -/** An autocompletion suggestion for the user. +/** + * An autocompletion suggestion for the user. * Primary data type for the Atom Autocomplete+ service. */ export interface Suggestion { - /** A string that will show in the UI for this suggestion. + /** + * A string that will show in the UI for this suggestion. * When not set, snippet || text is displayed. */ displayText?: string; - /** The text immediately preceding the cursor, which will be replaced by the text. + /** + * The text immediately preceding the cursor, which will be replaced by the text. * If not provided, the prefix passed into getSuggestions will be used. */ replacementPrefix?: string; - /** The suggestion type. It will be converted into an icon shown against the + /** + * The suggestion type. It will be converted into an icon shown against the * suggestion. */ type?: string; @@ -51,7 +59,8 @@ export interface Suggestion { /** Use this instead of leftLabel if you want to use html for the left label. */ leftLabelHTML?: string; - /** An indicator (e.g. function, variable) denoting the "kind" of suggestion this + /** + * An indicator (e.g. function, variable) denoting the "kind" of suggestion this * represents. */ rightLabel?: string; @@ -59,22 +68,26 @@ export interface Suggestion { /** Use this instead of rightLabel if you want to use html for the right label. */ rightLabelHTML?: string; - /** Class name for the suggestion in the suggestion list. Allows you to style your + /** + * Class name for the suggestion in the suggestion list. Allows you to style your * suggestion via CSS, if desired. */ className?: string; - /** If you want complete control over the icon shown against the suggestion. + /** + * If you want complete control over the icon shown against the suggestion. * e.g. iconHTML: */ iconHTML?: string; - /** A doc-string summary or short description of the suggestion. When specified, it + /** + * A doc-string summary or short description of the suggestion. When specified, it * will be displayed at the bottom of the suggestions list. */ description?: string; - /** A url to the documentation or more information about this suggestion. + /** + * A url to the documentation or more information about this suggestion. * When specified, a More.. link will be displayed in the description area. */ descriptionMoreURL?: string; @@ -86,7 +99,8 @@ export interface TextSuggestion extends Suggestion { } export interface SnippetSuggestion extends Suggestion { - /** A snippet string. This will allow users to tab through function arguments + /** + * A snippet string. This will allow users to tab through function arguments * or other options. */ snippet: string; @@ -96,24 +110,28 @@ export type Suggestions = Array; /** The interface that all Autocomplete+ providers must implement. */ export interface AutocompleteProvider { - /** Defines the scope selector(s) (can be comma-separated) for which your provider + /** + * Defines the scope selector(s) (can be comma-separated) for which your provider * should receive suggestion requests. */ selector: string; - /** Is called when a suggestion request has been dispatched by autocomplete+ to + /** + * Is called when a suggestion request has been dispatched by autocomplete+ to * your provider. Return an array of suggestions (if any) in the order you would * like them displayed to the user. Returning a Promise of an array of suggestions * is also supported. */ getSuggestions(params: SuggestionsRequestedEvent): Suggestions|Promise; - /** Defines the scope selector(s) (can be comma-separated) for which your provider + /** + * Defines the scope selector(s) (can be comma-separated) for which your provider * should not be used. */ disableForSelector?: string; - /** A number to indicate its priority to be included in a suggestions request. + /** + * A number to indicate its priority to be included in a suggestions request. * The default provider has an inclusion priority of 0. Higher priority providers * can suppress lower priority providers with excludeLowerPriority. */ @@ -122,12 +140,14 @@ export interface AutocompleteProvider { /** Will not use lower priority providers when this provider is used. */ excludeLowerPriority?: boolean; - /** A number to determine the sort order of suggestions. The default provider has + /** + * A number to determine the sort order of suggestions. The default provider has * an suggestion priority of 1. */ suggestionPriority?: number; - /** Function that is called when a suggestion from your provider was inserted + /** + * Function that is called when a suggestion from your provider was inserted * into the buffer. */ onDidInsertSuggestion?(params: SuggestionInsertedEvent): void; diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 07614a5815..2a13373b7d 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -1,4106 +1,6566 @@ -// Type definitions for Atom 1.21 +// Type definitions for Atom 1.22 // Project: https://github.com/atom/atom -// Definitions by: GlenCFL +// Definitions by: GlenCFL , +// smhxx // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// https://github.com/atom/atom/blob/v1.21.0/exports/atom.js +// NOTE: only those classes exported within this file should be retain that status below. +// https://github.com/atom/atom/blob/v1.22.0/exports/atom.js -/// /// +/// -/// -/// -/// -/// -/// +import { ReadStream, WriteStream } from "fs"; +import { ChildProcess } from "child_process"; declare global { - namespace AtomCore { - /** The event objects that are passed into the callbacks which the user provides to - * specific API calls. - */ - namespace Events { - interface CursorPositionChanged { - oldBufferPosition: TextBuffer.Point; - oldScreenPosition: TextBuffer.Point; - newBufferPosition: TextBuffer.Point; - newScreenPosition: TextBuffer.Point; - textChanged: boolean; - Cursor: Cursor; - } - - interface DecorationPropsChanged { - /** Object the old parameters the decoration used to have. */ - oldProperties: Options.DecorationProps; - - /** Object the new parameters the decoration now has */ - newProperties: Options.DecorationProps; - } - - interface EditorChanged { - /** A Point representing where the change started. */ - start: TextBuffer.Point; - - /** A Point representing the replaced extent. */ - oldExtent: TextBuffer.Point; - - /** A Point representing the replacement extent. */ - newExtent: TextBuffer.Point; - } - - interface ExceptionThrown { - originalError: Error; - message: string; - url: string; - line: number; - column: number; - } - - type FilesystemChange = Array<{ - /** A string describing the filesystem action that occurred. */ - action: "created"|"modified"|"deleted"|"renamed"; - - /** The absolute path to the filesystem entry that was acted upon. */ - path: string; - - /** For rename events, a string containing the filesystem entry's former - * absolute path. - */ - oldPath?: string; - }>; - - interface PaneItemMoved { - /** The removed pane item. */ - item: object; - - /** A number indicating where the item was located. */ - oldIndex: number; - - /** A number indicating where the item is now located. */ - newIndex: number; - } - - interface PaneItemObserved { - item: object; - pane: Pane; - index: number; - } - - interface PaneItemOpened extends PaneItemObserved { - uri: string; - } - - interface PaneListItemShifted { - /** The pane item that was added or removed. */ - item: object; - - /** A number indicating where the item is located. */ - index: number; - } - - interface PreventableExceptionThrown extends ExceptionThrown { - preventDefault(): void; - } - - interface RepoStatusChanged { - path: string; - - /** This value can be passed to ::isStatusModified or ::isStatusNew to get more - * information. - */ - pathStatus: number; - } - - interface SelectionChanged { - oldBufferRange: TextBuffer.Range; - oldScreenRange: TextBuffer.Range; - newBufferRange: TextBuffer.Range; - newScreenRange: TextBuffer.Range; - selection: Selection; - } - - interface StyleElementObserved extends HTMLStyleElement { - sourcePath: string; - context: string; - } - - interface TextEditorObserved { - textEditor: TextEditor; - pane: Pane; - index: number; - } - } - - /** The option objects that the user is expected to fill out and provide to - * specific API calls. - */ - namespace Options { - interface BuildEnvironment { - /** An object responsible for Atom's interaction with the browser process and host OS. - * Use buildDefaultApplicationDelegate for a default instance. - */ - applicationDelegate?: object; - - /** A window global. */ - window?: Window; - - /** A document global. */ - document?: Document; - - /** A path to the configuration directory (usually ~/.atom). */ - configDirPath?: string; - - /** A boolean indicating whether the Atom environment should save or load state - * from the file system. You probably want this to be false. - */ - enablePersistence?: boolean; - } - - interface ContextMenu { - /** The menu item's label. */ - label?: string; - - /** The command to invoke on the target of the right click that invoked the - * context menu. - */ - command?: string; - - /** Whether the menu item should be clickable. Disabled menu items typically - * appear grayed out. Defaults to true. - */ - enabled?: boolean; - - /** An array of additional items. */ - submenu?: ReadonlyArray; - - /** If you want to create a separator, provide an item with type: 'separator' - * and no other keys. - */ - type?: "separator"; - - /** Whether the menu item should appear in the menu. Defaults to true. */ - visible?: boolean; - - /** A function that is called on the item each time a context menu is created - * via a right click. - */ - created?(event: Event): void; - - /** A function that is called to determine whether to display this item on a - * given context menu deployment. - */ - shouldDisplay?(event: Event): void; - } - - interface DecorationLayerProps extends SharedDecorationProps { - /** One of several supported decoration types. */ - type?: "line"|"line-number"|"highlight"|"block"; - } - - interface DecorationProps extends SharedDecorationProps { - /** One of several supported decoration types. */ - type?: "line"|"line-number"|"highlight"|"overlay"|"gutter"|"block"; - - /** The name of the gutter we're decorating, if type is "gutter". */ - gutterName?: string; - } - - interface ErrorNotification extends NotificationOptions { - stack?: string; - } - - interface Menu { - /** The menu itme's label. */ - label: string; - - /** An array of sub menus. */ - submenu?: ReadonlyArray; - - /** The command to trigger when the item is clicked. */ - command?: string; - } - - interface Notification { - buttons?: Array<{ - className?: string; - onDidClick?(event: MouseEvent): void; - text?: string; - }>; - description?: string; - detail?: string; - dismissable?: boolean; - icon?: string; - } - - interface NodeProcess { - /** The command to execute. */ - command: string; - - /** The array of arguments to pass to the command. */ - args?: ReadonlyArray; - - /** The options object to pass to Node's ChildProcess.spawn method. */ - options?: SpawnProcess; - - /** The callback that receives a single argument which contains the standard - * output from the command. - */ - stdout?(data: string): void; - - /** The callback that receives a single argument which contains the standard - * error output from the command. - */ - stderr?(data: string): void; - - /** The callback which receives a single argument containing the exit status. */ - exit?(code: number): void; - } - - interface Process extends NodeProcess { - /** Whether the command will automatically start when this BufferedProcess is - * created. - */ - autoStart?: boolean; - } - - interface SharedDecorationProps { - /** This CSS class will be applied to the decorated line number, line, highlight, - * or overlay. - */ - class?: string; - - /** An HTMLElement or a model Object with a corresponding view registered. Only - * applicable to the gutter, overlay and block types. - */ - item?: HTMLElement; - - /** If true, the decoration will only be applied to the head of the DisplayMarker. - * Only applicable to the line and line-number types. - */ - onlyHead?: boolean; - - /** If true, the decoration will only be applied if the associated DisplayMarker - * is empty. Only applicable to the gutter, line, and line-number types. - */ - onlyEmpty?: boolean; - - /** If true, the decoration will only be applied if the associated DisplayMarker - * is non-empty. Only applicable to the gutter, line, and line-number types. - */ - onlyNonEmpty?: boolean; - - /** Only applicable to decorations of type overlay and block. Controls where the - * view is positioned relative to the TextEditorMarker. Values can be - * 'head' (the default) or 'tail' for overlay decorations, and 'before' (the default) - * or 'after' for block decorations. - */ - position?: "head"|"tail"|"before"|"after"; - - /** Only applicable to decorations of type overlay. Determines whether the decoration - * adjusts its horizontal or vertical position to remain fully visible when it would - * otherwise overflow the editor. Defaults to true. - */ - avoidOverflow?: boolean; - } - - interface SpawnProcess { - /** Current working directory of the child process. */ - cwd?: string; - - /** Environment key-value pairs. */ - env?: { [key: string]: string }; - - /** The child's stdio configuration. */ - stdio?: string|Array; - - /** Prepare child to run independently of its parent process. */ - detached?: boolean; - - /** Sets the user identity of the process. */ - uid?: number; - - /** Sets the group identity of the process. */ - gid?: number; - - /** If true, runs command inside of a shell. Uses "/bin/sh" on UNIX, and - * process.env.ComSpec on Windows. A different shell can be specified as - * a string. - */ - shell?: boolean | string; - } - - interface TextInsertion { - select?: boolean; - autoIndent?: boolean; - autoIndentNewline?: boolean; - autoDecreaseIndent?: boolean; - normalizeLineEndings?: boolean; - undo?: "skip"; - } - - /** The options for a Bootstrap 3 Tooltip class, which Atom uses a variant of. */ - interface Tooltip { - /** Apply a CSS fade transition to the tooltip. */ - animation?: boolean; - - /** Appends the tooltip to a specific element. */ - container?: string|HTMLElement|false; - - /** Delay showing and hiding the tooltip (ms) - does not apply to manual - * trigger type. - */ - delay?: number|{ show: number, hide: number }; - - /** Allow HTML in the tooltip. */ - html?: boolean; - - /** How to position the tooltip. */ - placement?: "top"|"bottom"|"left"|"right"|"auto"; - - /** If a selector is provided, tooltip objects will be delegated to the - * specified targets. - */ - selector?: string; - - /** Base HTML to use when creating the tooltip. */ - template?: string; - - /** Default title value if title attribute isn't present. - * If a function is given, it will be called with its this reference set to - * the element that the tooltip is attached to. - */ - title?: string|HTMLElement|(() => string); - - /** How tooltip is triggered - click | hover | focus | manual. - * You may pass multiple triggers; separate them with a space. - */ - trigger?: string; - } - - interface WorkspaceScan { - /** An array of glob patterns to search within. */ - paths?: ReadonlyArray; - - /** A function to be periodically called with the number of paths searched. */ - onPathsSearched?(pathsSearched: number): void; - - /** The number of lines before the matched line to include in the results object. */ - leadingContextLineCount?: number; - - /** The number of lines after the matched line to include in the results object. */ - trailingContextLineCount?: number; - } - } - - /** The structures that are passed to the user by Atom following specific API calls. */ - namespace Structures { - interface CancellablePromise extends Promise { - cancel(): void; - } - - interface HistoryProject { - paths: string[]; - lastOpened: Date; - } - - interface ScandalResult { - filePath: string; - matches: Array<{ - matchText: string; - lineText: string; - lineTextOffset: number; - range: [[number, number], [number, number]]; - leadingContextLines: string[]; - trailingContextLines: string[]; - }>; - } - - interface TestRunnerArgs { - /** An array of paths to tests to run. Could be paths to files or directories. */ - testPaths: string[]; - - /** A function that can be called to construct an instance of the atom global. - * No atom global will be explicitly assigned, but you can assign one in your - * runner if desired. - */ - buildAtomEnvironment(options: Options.BuildEnvironment): AtomEnvironment; - - /** A function that builds a default instance of the application delegate, suitable - * to be passed as the applicationDelegate parameter to buildAtomEnvironment. - */ - buildDefaultApplicationDelegate(): object; - - /** An optional path to a log file to which test output should be logged. */ - logFile: string; - - /** A boolean indicating whether or not the tests are being run from the command - * line via atom --test. - */ - headless: boolean; - } - - /** This tooltip class is derived from Bootstrap 3, but modified to not require - * jQuery, which is an expensive dependency we want to eliminate. - */ - interface Tooltip { - options: Options.Tooltip; - enabled: boolean; - timeout: number; - hoverState: "in"|"out"|null; - element: JQuery|HTMLElement; - - getTitle(): string; - getTooltipElement(): HTMLElement; - getArrowElement(): HTMLElement; - enable(): void; - disable(): void; - toggleEnabled(): void; - toggle(): void; - recalculatePosition(): void; - } - - interface WindowLoadSettings { - appVersion: string; - atomHome: string; - devMode: boolean; - env: { [key: string]: string|undefined }; - profileStartup: boolean; - resourcePath: string; - safeMode: boolean; - } - } - - /** Atom global for dealing with packages, themes, menus, and the window. - * An instance of this class is always available as the atom global. - */ - interface AtomEnvironment { - // Properties - /** A CommandRegistry instance. */ - commands: CommandRegistry; - - /** A Config instance. */ - config: Config; - - /** A Clipboard instance. */ - clipboard: Clipboard; - - /** A ContextMenuManager instance. */ - contextMenu: ContextMenuManager; - - /** A MenuManager instance. */ - menu: MenuManager; - - /** A KeymapManager instance. */ - keymaps: AtomKeymap.KeymapManager; - - /** A TooltipManager instance. */ - tooltips: TooltipManager; - - /** A NotificationManager instance. */ - notifications: NotificationManager; - - /** A Project instance. */ - project: Project; - - /** A GrammarRegistry instance. */ - grammars: FirstMate.GrammarRegistry; - - /** A HistoryManager instance. */ - history: HistoryManager; - - /** A PackageManager instance. */ - packages: PackageManager; - - /** A ThemeManager instance. */ - themes: ThemeManager; - - /** A StyleManager instance. */ - styles: StyleManager; - - /** A DeserializerManager instance. */ - deserializers: DeserializerManager; - - /** A ViewRegistry instance. */ - views: ViewRegistry; - - /** A Workspace instance. */ - workspace: Workspace; - - /** A TextEditorRegistry instance. */ - textEditors: TextEditorRegistry; - - // Event Subscription - /** Invoke the given callback whenever ::beep is called. */ - onDidBeep(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when there is an unhandled error, but before - * the devtools pop open. - */ - onWillThrowError(callback: (event: Events.PreventableExceptionThrown) => - void): EventKit.Disposable; - - /** Invoke the given callback whenever there is an unhandled error. */ - onDidThrowError(callback: (event: Events.ExceptionThrown) => void): EventKit.Disposable; - - /** Invoke the given callback as soon as the shell environment is loaded (or - * immediately if it was already loaded). - */ - whenShellEnvironmentLoaded(callback: () => void): EventKit.Disposable; - - // Atom Details - /** Returns a boolean that is true if the current window is in development mode. */ - inDevMode(): boolean; - - /** Returns a boolean that is true if the current window is in safe mode. */ - inSafeMode(): boolean; - - /** Returns a boolean that is true if the current window is running specs. */ - inSpecMode(): boolean; - - /** Get the version of the Atom application. */ - getVersion(): string; - - /** Gets the release channel of the Atom application. - * Returns the release channel, which can be 'dev', 'beta', or 'stable'. - */ - getReleaseChannel(): "dev"|"beta"|"stable"; - - /** Returns a boolean that is true if the current version is an official release. */ - isReleasedVersion(): boolean; - - /** Get the time taken to completely load the current window. */ - getWindowLoadTime(): number; - - /** Get the load settings for the current window. */ - getLoadSettings(): Structures.WindowLoadSettings; - - // Managing the Atom Window - /** Open a new Atom window using the given options. */ - open(params: { - pathsToOpen: ReadonlyArray, - newWindow: boolean, - devMode: boolean, - safeMode: boolean, - }): void; - - /** Close the current window. */ - close(): void; - - /** Get the size of current window. */ - getSize(): { width: number, height: number }; - - /** Set the size of current window. */ - setSize(width: number, height: number): void; - - /** Get the position of current window. */ - getPosition(): { x: number, y: number }; - - /** Set the position of current window. */ - setPosition(x: number, y: number): void; - - /** Prompt the user to select one or more folders. */ - pickFolder(callback: (paths: string[]|null) => void): void; - - /** Get the current window. */ - getCurrentWindow(): object; - - /** Move current window to the center of the screen. */ - center(): void; - - /** Focus the current window. */ - focus(): void; - - /** Show the current window. */ - show(): void; - - /** Hide the current window. */ - hide(): void; - - /** Reload the current window. */ - reload(): void; - - /** Relaunch the entire application. */ - restartApplication(): void; - - /** Returns a boolean that is true if the current window is maximized. */ - isMaximized(): boolean; - - /** Returns a boolean that is true if the current window is in full screen mode. */ - isFullScreen(): boolean; - - /** Set the full screen state of the current window. */ - setFullScreen(fullScreen: boolean): void; - - /** Toggle the full screen state of the current window. */ - toggleFullScreen(): void; - - // Messaging the User - /** Visually and audibly trigger a beep. */ - beep(): void; - - /** A flexible way to open a dialog akin to an alert dialog. - * Returns the chosen button index number if the buttons option was an array. - */ - confirm(options: { - message: string, - detailedMessage?: string, - buttons?: ReadonlyArray, - }): void; - - /** A flexible way to open a dialog akin to an alert dialog. - * Returns the chosen button index number if the buttons option was an array. - */ - confirm(options: { - message: string, - detailedMessage?: string, - buttons?: { - [key: string]: () => void - }, - }): number; - - // Managing the Dev Tools - /** Open the dev tools for the current window. */ - openDevTools(): Promise; - - /** Toggle the visibility of the dev tools for the current window. */ - toggleDevTools(): Promise; - - /** Execute code in dev tools. */ - executeJavaScriptInDevTools(code: string): void; - } - - /** A wrapper which provides standard error/output line buffering for - * Node's ChildProcess. - */ - interface BufferedProcess { - process: NodeJS.EventEmitter; - - // Event Subscription - /** Will call your callback when an error will be raised by the process. Usually - * this is due to the command not being available or not on the PATH. You can - * call handle() on the object passed to your callback to indicate that you - * have handled this error. - */ - onWillThrowError(callback: (errorObject: { error: Error, handle(): void }) => - void): EventKit.Disposable; - - // Helper Methods - /** Terminate the process. */ - kill(): void; - - /** Runs the process. */ - start(): void; - } - - /** The static side to the BufferedProcess class. */ - interface BufferedProcessStatic { - new (options: Options.Process): BufferedProcess; - } - - /** Like BufferedProcess, but accepts a Node script as the command to run. - * This is necessary on Windows since it doesn't support shebang #! lines. - */ - type BufferedNodeProcess = BufferedProcess; - - /** The static side to the BufferedNodeProcess class. */ - interface BufferedNodeProcessStatic { - /** Runs the given Node script by spawning a new child process. */ - new (options: Options.NodeProcess): BufferedNodeProcess; - } - - /** Represents the clipboard used for copying and pasting in Atom. */ - interface Clipboard { - /** Write the given text to the clipboard. */ - write(text: string, metadata?: object): void; - - /** Read the text from the clipboard. */ - read(): string; - - /** Read the text from the clipboard and return both the text and the associated - * metadata. - */ - readWithMetadata(): { text: string, metadata: object }; - } - - /** A simple color class returned from Config::get when the value at the key path is - * of type 'color'. - */ - interface Color { - /** Returns a string in the form '#abcdef'. */ - toHexString(): string; - - /** Returns a string in the form 'rgba(25, 50, 75, .9)'. */ - toRGBAString(): string; - } - - /** Associates listener functions with commands in a context-sensitive way - * using CSS selectors. - */ - interface CommandRegistry { - /** Register a single command. */ - add(target: string|Node, commandName: string, listener: { - didDispatch(event: AtomKeymap.Events.CommandEvent): void, - displayName?: string, - description?: string, - } | ((event: AtomKeymap.Events.CommandEvent) => void)): EventKit.Disposable; - - /** Register multiple commands. */ - add(target: string|Node, commands: { [key: string]: (event: - AtomKeymap.Events.CommandEvent) => void }): EventKit.CompositeDisposable; - - /** Find all registered commands matching a query. */ - findCommands(params: { target: Node }): Array<{ - name: string, - displayName: string, - description?: string, - tags?: string[], - }>; - - /** Simulate the dispatch of a command on a DOM node. */ - dispatch(target: Node, commandName: string): void; - - /** Invoke the given callback before dispatching a command event. */ - onWillDispatch(callback: (event: AtomKeymap.Events.CommandEvent) => void): - EventKit.Disposable; - - /** Invoke the given callback after dispatching a command event. */ - onDidDispatch(callback: (event: AtomKeymap.Events.CommandEvent) => void): - EventKit.Disposable; - } - - /** Used to access all of Atom's configuration details. */ - interface Config { - // Config Subscription - /** Add a listener for changes to a given key path. This is different than ::onDidChange in - * that it will immediately call your callback with the current value of the config entry. - */ - // tslint:disable-next-line:no-any - observe(keyPath: string, callback: (value: any) => void): EventKit.Disposable; - /** Add a listener for changes to a given key path. This is different than ::onDidChange in - * that it will immediately call your callback with the current value of the config entry. - */ - // tslint:disable:no-any - observe(keyPath: string, options: { scope: string[]|ScopeDescriptor }, - callback: (value: any) => void): EventKit.Disposable; - // tslint:enable:no-any - - /** Add a listener for changes to a given key path. If keyPath is not specified, your - * callback will be called on changes to any key. - */ - // tslint:disable-next-line:no-any - onDidChange(callback: (values: { newValue: T, oldValue: T }) => void): - EventKit.Disposable; - /** Add a listener for changes to a given key path. If keyPath is not specified, your - * callback will be called on changes to any key. - */ - // tslint:disable-next-line:no-any - onDidChange(keyPath: string, callback: (values: { newValue: T, - oldValue: T }) => void): EventKit.Disposable; - /** Add a listener for changes to a given key path. If keyPath is not specified, your - * callback will be called on changes to any key. - */ - // tslint:disable-next-line:no-any - onDidChange(keyPath: string, options: { scope: string[]|ScopeDescriptor }, - callback: (values: { newValue: T, oldValue: T }) => void): EventKit.Disposable; - - // Managing Settings - /** Retrieves the setting for the given key. */ - // tslint:disable:no-any - get(keyPath: string, options?: { sources?: string[], excludeSources?: string[], - scope?: string[]|ScopeDescriptor }): any; - // tslint:enable:no-any - - /** Sets the value for a configuration setting. - * This value is stored in Atom's internal configuration file. - */ - // tslint:disable-next-line:no-any - set(keyPath: string, value: any, options?: { scopeSelector?: string, source?: - string }): void; - - /** Restore the setting at keyPath to its default value. */ - unset(keyPath: string, options?: { scopeSelector?: string, source?: string }): void; - - /** Get all of the values for the given key-path, along with their associated - * scope selector. - */ - // tslint:disable:no-any - getAll(keyPath: string, options?: { sources?: string[], excludeSources?: string[], - scope?: ScopeDescriptor }): Array<{ scopeDescriptor: ScopeDescriptor, value: any}>; - // tslint:enable:no-any - - /** Get an Array of all of the source Strings with which settings have been added - * via ::set. - */ - getSources(): string[]; - - /** Retrieve the schema for a specific key path. The schema will tell you what type - * the keyPath expects, and other metadata about the config option. - */ - getSchema(keyPath: string): object|null; - - /** Get the string path to the config file being used. */ - getUserConfigPath(): string; - - /** Suppress calls to handler functions registered with ::onDidChange and ::observe - * for the duration of callback. After callback executes, handlers will be called - * once if the value for their key-path has changed. - */ - transact(callback: () => void): void; - } - - /** Provides a registry for commands that you'd like to appear in the context menu. */ - interface ContextMenuManager { - /** Add context menu items scoped by CSS selectors. */ - add(itemsBySelector: { [key: string]: ReadonlyArray }): - EventKit.Disposable; - } - - /** The Cursor class represents the little blinking line identifying where text - * can be inserted. - */ - interface Cursor { - // Event Subscription - /** Calls your callback when the cursor has been moved. */ - onDidChangePosition(callback: (event: Events.CursorPositionChanged) => void): - EventKit.Disposable; - - /** Calls your callback when the cursor is destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - /** Calls your callback when the cursor's visibility has changed. */ - onDidChangeVisibility(callback: (visibility: boolean) => void): EventKit.Disposable; - - // Managing Cursor Position - /** Moves a cursor to a given screen position. */ - setScreenPosition(screenPosition: TextBuffer.PointCompatible, options?: - { autoscroll?: boolean }): void; - - /** Returns the screen position of the cursor as a Point. */ - getScreenPosition(): TextBuffer.Point; - - /** Moves a cursor to a given buffer position. */ - setBufferPosition(bufferPosition: TextBuffer.PointCompatible, options?: - { autoscroll?: boolean }): void; - - /** Returns the current buffer position as an Array. */ - getBufferPosition(): TextBuffer.Point; - - /** Returns the cursor's current screen row. */ - getScreenRow(): number; - - /** Returns the cursor's current screen column. */ - getScreenColumn(): number; - - /** Retrieves the cursor's current buffer row. */ - getBufferRow(): number; - - /** Returns the cursor's current buffer column. */ - getBufferColumn(): number; - - /** Returns the cursor's current buffer row of text excluding its line ending. */ - getCurrentBufferLine(): string; - - /** Returns whether the cursor is at the start of a line. */ - isAtBeginningOfLine(): boolean; - - /** Returns whether the cursor is on the line return character. */ - isAtEndOfLine(): boolean; - - // Cursor Position Details - /** Returns the underlying DisplayMarker for the cursor. Useful with overlay - * Decorations. - */ - getMarker(): TextBuffer.DisplayMarker; - - /** Identifies if the cursor is surrounded by whitespace. - * "Surrounded" here means that the character directly before and after the cursor - * are both whitespace. - */ - isSurroundedByWhitespace(): boolean; - - /** This method returns false if the character before or after the cursor is whitespace. */ - isBetweenWordAndNonWord(): boolean; - - /** Returns whether this cursor is between a word's start and end. */ - isInsideWord(options?: { wordRegex?: RegExp }): boolean; - - /** Returns the indentation level of the current line. */ - getIndentLevel(): number; - - /** Retrieves the scope descriptor for the cursor's current position. */ - getScopeDescriptor(): ScopeDescriptor; - - /** Returns true if this cursor has no non-whitespace characters before its - * current position. - */ - hasPrecedingCharactersOnLine(): boolean; - - /** Identifies if this cursor is the last in the TextEditor. - * "Last" is defined as the most recently added cursor. - */ - isLastCursor(): boolean; - - // Moving the Cursor - /** Moves the cursor up one screen row. */ - moveUp(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void; - - /** Moves the cursor down one screen row. */ - moveDown(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void; - - /** Moves the cursor left one screen column. */ - moveLeft(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void; - - /** Moves the cursor right one screen column. */ - moveRight(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void; - - /** Moves the cursor to the top of the buffer. */ - moveToTop(): void; - - /** Moves the cursor to the bottom of the buffer. */ - moveToBottom(): void; - - /** Moves the cursor to the beginning of the line. */ - moveToBeginningOfScreenLine(): void; - - /** Moves the cursor to the beginning of the buffer line. */ - moveToBeginningOfLine(): void; - - /** Moves the cursor to the beginning of the first character in the line. */ - moveToFirstCharacterOfLine(): void; - - /** Moves the cursor to the end of the line. */ - moveToEndOfScreenLine(): void; - - /** Moves the cursor to the end of the buffer line. */ - moveToEndOfLine(): void; - - /** Moves the cursor to the beginning of the word. */ - moveToBeginningOfWord(): void; - - /** Moves the cursor to the end of the word. */ - moveToEndOfWord(): void; - - /** Moves the cursor to the beginning of the next word. */ - moveToBeginningOfNextWord(): void; - - /** Moves the cursor to the previous word boundary. */ - moveToPreviousWordBoundary(): void; - - /** Moves the cursor to the next word boundary. */ - moveToNextWordBoundary(): void; - - /** Moves the cursor to the previous subword boundary. */ - moveToPreviousSubwordBoundary(): void; - - /** Moves the cursor to the next subword boundary. */ - moveToNextSubwordBoundary(): void; - - /** Moves the cursor to the beginning of the buffer line, skipping all whitespace. */ - skipLeadingWhitespace(): void; - - /** Moves the cursor to the beginning of the next paragraph. */ - moveToBeginningOfNextParagraph(): void; - - /** Moves the cursor to the beginning of the previous paragraph. */ - moveToBeginningOfPreviousParagraph(): void; - - // Local Positions and Ranges - /** Returns buffer position of previous word boundary. It might be on the current - * word, or the previous word. - */ - getPreviousWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): - TextBuffer.Point; - - /** Returns buffer position of the next word boundary. It might be on the current - * word, or the previous word. - */ - getNextWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): - TextBuffer.Point; - - /** Retrieves the buffer position of where the current word starts. */ - getBeginningOfCurrentWordBufferPosition(options?: { - wordRegex?: RegExp, - includeNonWordCharacters?: boolean, - allowPrevious?: boolean - }): TextBuffer.Point; - - /** Retrieves the buffer position of where the current word ends. */ - getEndOfCurrentWordBufferPosition(options?: { - wordRegex?: RegExp, - includeNonWordCharacters?: boolean - }): TextBuffer.Point; - - /** Retrieves the buffer position of where the next word starts. */ - getBeginningOfNextWordBufferPosition(options?: { wordRegex?: RegExp }): - TextBuffer.Point; - - /** Returns the buffer Range occupied by the word located under the cursor. */ - getCurrentWordBufferRange(options?: { wordRegex?: RegExp }): TextBuffer.Range; - - /** Returns the buffer Range for the current line. */ - getCurrentLineBufferRange(options?: { includeNewline?: boolean }): TextBuffer.Range; - - /** Retrieves the range for the current paragraph. - * A paragraph is defined as a block of text surrounded by empty lines or comments. - */ - getCurrentParagraphBufferRange(): TextBuffer.Range; - - /** Returns the characters preceding the cursor in the current word. */ - getCurrentWordPrefix(): string; - - // Visibility - /** Sets whether the cursor is visible. */ - setVisible(visible: boolean): void; - - /** Returns the visibility of the cursor. */ - isVisible(): boolean; - - // Comparing to another cursor - /** Compare this cursor's buffer position to another cursor's buffer position. - * See Point::compare for more details. - */ - compare(otherCursor: Cursor): number; - - // Utilities - /** Prevents this cursor from causing scrolling. */ - clearAutoscroll(): void; - - /** Deselects the current selection. */ - clearSelection(): void; - - /** Get the RegExp used by the cursor to determine what a "word" is. */ - wordRegExp(options?: { includeNonWordCharacters?: boolean }): RegExp; - - /** Get the RegExp used by the cursor to determine what a "subword" is. */ - subwordRegExp(options?: { backwards?: boolean }): RegExp; - } - - /** Represents a decoration that follows a DisplayMarker. A decoration is basically - * a visual representation of a marker. It allows you to add CSS classes to line - * numbers in the gutter, lines, and add selection-line regions around marked ranges - * of text. - */ - interface Decoration { - id: number; - - // Construction and Destruction - /** Destroy this marker decoration. - * You can also destroy the marker if you own it, which will destroy this decoration. - */ - destroy(): void; - - // Event Subscription - /** When the Decoration is updated via Decoration::setProperties. */ - onDidChangeProperties(callback: (event: Events.DecorationPropsChanged) => void): - EventKit.Disposable; - - /** Invoke the given callback when the Decoration is destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - // Decoration Details - /** An id unique across all Decoration objects. */ - getId(): number; - - /** Returns the marker associated with this Decoration. */ - getMarker(): TextBuffer.DisplayMarker; - - // Properties - /** Returns the Decoration's properties. */ - getProperties(): Options.DecorationProps; - - /** Update the marker with new Properties. Allows you to change the decoration's - * class. - */ - setProperties(newProperties: Options.DecorationProps): void; - } - - interface Deserializer { - name: string; - deserialize(state: object): object; - } - - /** Manages the deserializers used for serialized state. */ - interface DeserializerManager { - /** Register the given class(es) as deserializers. */ - add(...deserializers: Deserializer[]): EventKit.Disposable; - - /** Deserialize the state and params. */ - deserialize(state: object): object|undefined; - } - - /** A container at the edges of the editor window capable of holding items. */ - interface Dock { - // Methods - /** Show the dock and focus its active Pane. */ - activate(): void; - - /** Show the dock without focusing it. */ - show(): void; - - /** Hide the dock and activate the WorkspaceCenter if the dock was was previously - * focused. - */ - hide(): void; - - /** Toggle the dock's visibility without changing the Workspace's active pane - * container. - */ - toggle(): void; - - /** Check if the dock is visible. */ - isVisible(): boolean; - - // Event Subscription - /** Invoke the given callback when the visibility of the dock changes. */ - onDidChangeVisible(callback: (visible: boolean) => void): EventKit.Disposable; - - /** Invoke the given callback with the current and all future visibilities of - * the dock. - */ - observeVisible(callback: (visible: boolean) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes items in the dock. */ - observePaneItems(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item changes. - * - * Because observers are invoked synchronously, it's important not to perform any - * expensive operations via this method. Consider ::onDidStopChangingActivePaneItem - * to delay operations until after changes stop occurring. - */ - onDidChangeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item stops changing. */ - onDidStopChangingActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane item and with all future - * active pane items in the dock. - */ - observeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is added to the dock. */ - onDidAddPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback before a pane is destroyed in the dock. */ - onWillDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is destroyed in the dock. */ - onDidDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes in the dock. */ - observePanes(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane changes. */ - onDidChangeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane and when the active - * pane changes. - */ - observeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane item is added to the dock. */ - onDidAddPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is about to be destroyed, before the user is - * prompted to save it. - */ - onWillDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is destroyed. */ - onDidDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - // Pane Items - /** Get all pane items in the dock. */ - getPaneItems(): object[]; - - /** Get the active Pane's active item. */ - getActivePaneItem(): object; - - // Panes - /** Returns an Array of Panes. */ - getPanes(): Pane[]; - - /** Get the active Pane. */ - getActivePane(): Pane; - - /** Make the next pane active. */ - activateNextPane(): boolean; - - /** Make the previous pane active. */ - activatePreviousPane(): boolean; - } - - /** Represents the underlying git operations performed by Atom. */ - interface GitRepository { - // Lifecycle - /** Destroy this GitRepository object. */ - destroy(): void; - - /** Returns a boolean indicating if this repository has been destroyed. */ - isDestroyed(): boolean; - - // Event Subscription - /** Invoke the given callback when this GitRepository's destroy() method is - * invoked. - */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when a specific file's status has changed. When - * a file is updated, reloaded, etc, and the status changes, this will be fired. - */ - onDidChangeStatus(callback: (event: Events.RepoStatusChanged) => void): - EventKit.Disposable; - - /** Invoke the given callback when a multiple files' statuses have changed. */ - onDidChangeStatuses(callback: () => void): EventKit.Disposable; - - // Repository Details - /** A string indicating the type of version control system used by this repository. */ - getType(): "git"; - - /** Returns the string path of the repository. */ - getPath(): string; - - /** Returns the string working directory path of the repository. */ - getWorkingDirectory(): string; - - /** Returns true if at the root, false if in a subfolder of the repository. */ - isProjectAtRoot(): boolean; - - /** Makes a path relative to the repository's working directory. */ - relativize(): string; - - /** Returns true if the given branch exists. */ - hasBranch(branch: string): boolean; - - /** Retrieves a shortened version of the HEAD reference value. */ - getShortHead(path?: string): string; - - /** Is the given path a submodule in the repository? */ - isSubmodule(path: string): boolean; - - /** Returns the number of commits behind the current branch is from the its - * upstream remote branch. The default reference is the HEAD. - * @param reference The branch reference name. - * @param path The path in the repository to get this ifnromation for, only - * needed if the repository contains submodules. - * @return Returns the number of commits behind the current branch is from its - * upstream remote branch. - */ - getAheadBehindCount(reference: string, path?: string): { ahead: number, behind: number }; - - /** Get the cached ahead/behind commit counts for the current branch's - * upstream branch. - */ - getCachedUpstreamAheadBehindCount(path?: string): { ahead: number, behind: number }; - - /** Returns the git configuration value specified by the key. */ - getConfigValue(key: string, path?: string): string; - - /** Returns the origin url of the repository. */ - getOriginURL(path?: string): string; - - /** Returns the upstream branch for the current HEAD, or null if there is no - * upstream branch for the current HEAD. - */ - getUpstreamBranch(path?: string): string|null; - - /** Gets all the local and remote references. */ - getReferences(path?: string): { heads: string[], remotes: string[], tags: string[] }; - - /** Returns the current string SHA for the given reference. */ - getReferenceTarget(reference: string, path?: string): string; - - // Reading Status - /** Returns true if the given path is modified. */ - isPathModified(path: string): boolean; - - /** Returns true if the given path is new. */ - isPathNew(path: string): boolean; - - /** Is the given path ignored? */ - isPathIgnored(path: string): boolean; - - /** Get the status of a directory in the repository's working directory. */ - getDirectoryStatus(path: string): number; - - /** Get the status of a single path in the repository. */ - getPathStatus(path: string): number; - - /** Get the cached status for the given path. */ - getCachedPathStatus(path: string): number|null; - - /** Returns true if the given status indicates modification. */ - isStatusModified(status: number): boolean; - - /** Returns true if the given status indicates a new path. */ - isStatusNew(status: number): boolean; - - // Retrieving Diffs - /** Retrieves the number of lines added and removed to a path. - * This compares the working directory contents of the path to the HEAD version. - */ - getDiffStats(path: string): { added: number, deleted: number }; - - /** Retrieves the line diffs comparing the HEAD version of the given path - * and the given text. - */ - getLineDiffs(path: string, text: string): Array<{ oldStart: number, - newStart: number, oldLines: number, newLines: number }>; - - // Checking Out - /** Restore the contents of a path in the working directory and index to the - * version at HEAD. - */ - checkoutHead(path: string): boolean; - - /** Checks out a branch in your repository. */ - checkoutReference(reference: string, create: boolean): boolean; - } - - /** The static side to the GitRepository class. */ - interface GitRepositoryStatic { - /** Creates a new GitRepository instance. */ - open(path: string, options?: { refreshOnWindowFocus?: boolean }): GitRepository; - - new (path: string, options?: { refreshOnWindowFocus?: boolean, config?: Config, - project?: Project }): GitRepository; - } - - /** Represents a gutter within a TextEditor. */ - interface Gutter { - // Gutter Destruction - /** Destroys the gutter. */ - destroy(): void; - - // Event Subscription - /** Calls your callback when the gutter's visibility changes. */ - onDidChangeVisible(callback: (gutter: Gutter) => void): EventKit.Disposable; - - /** Calls your callback when the gutter is destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - // Visibility - /** Hide the gutter. */ - hide(): void; - - /** Show the gutter. */ - show(): void; - - /** Determine whether the gutter is visible. */ - isVisible(): boolean; - - /** Add a decoration that tracks a DisplayMarker. When the marker moves, is - * invalidated, or is destroyed, the decoration will be updated to reflect - * the marker's state. - */ - decorateMarker(marker: TextBuffer.DisplayMarker, decorationParams: - Options.DecorationProps): Decoration; - } - - /** History manager for remembering which projects have been opened. - * An instance of this class is always available as the atom.history global. - * The project history is used to enable the 'Reopen Project' menu. - */ - interface HistoryManager { - /** Obtain a list of previously opened projects. */ - getProjects(): Structures.HistoryProject[]; - - /** Clear all projects from the history. - * Note: This is not a privacy function - other traces will still exist, e.g. - * window state. - */ - clearProjects(): void; - - /** Invoke the given callback when the list of projects changes. */ - onDidChangeProjects(callback: (args: { reloaded: boolean }) => void): - EventKit.Disposable; - } - - /** Represents a decoration that applies to every marker on a given layer. Created via - * TextEditor::decorateMarkerLayer. - */ - interface LayerDecoration { - /** Destroys the decoration. */ - destroy(): void; - - /** Determine whether this decoration is destroyed. */ - isDestroyed(): boolean; - - /** Get this decoration's properties. */ - getProperties(): Options.DecorationLayerProps; - - /** Set this decoration's properties. */ - setProperties(newProperties: Options.DecorationLayerProps): void; - - /** Override the decoration properties for a specific marker. */ - setPropertiesForMarker(marker: TextBuffer.DisplayMarker|TextBuffer.Marker, - properties: Options.DecorationLayerProps): void; - } - - /** Provides a registry for menu items that you'd like to appear in the application menu. */ - interface MenuManager { - /** Adds the given items to the application menu. */ - add(items: ReadonlyArray): EventKit.Disposable; - - /** Refreshes the currently visible menu. */ - update(): void; - } - - /** A notification to the user containing a message and type. */ - interface Notification { - dismissed: boolean; - displayed: boolean; - timestamp: Date; - - // Event Subscription - /** Invoke the given callback when the notification is dismissed. */ - onDidDismiss(callback: (notification: Notification) => void): EventKit.Disposable; - - /** Invoke the given callback when the notification is displayed. */ - onDidDisplay(callback: (notification: Notification) => void): EventKit.Disposable; - - // Methods - /** Returns the Notification's type. */ - getType(): string; - - /** Returns the Notification's message. */ - getMessage(): string; - - /** Dismisses the notification, removing it from the UI. Calling this - * programmatically will call all callbacks added via onDidDismiss. - */ - dismiss(): void; - } - - /** The static side to the Notification class. */ - interface NotificationStatic { - new (type: "warning"|"info"|"success", message: string, options?: - Options.Notification): Notification; - new (type: "fatal"|"error", message: string, options?: Options.ErrorNotification): - Notification; - } - - /** A notification manager used to create Notifications to be shown to the user. */ - interface NotificationManager { - // Properties - notifications: Notification[]; - - // Events - /** Invoke the given callback after a notification has been added. */ - onDidAddNotification(callback: (notification: Notification) => void): - EventKit.Disposable; - - // Adding Notifications - /** Add a success notification. */ - addSuccess(message: string, options?: Options.Notification): Notification; - - /** Add an informational notification. */ - addInfo(message: string, options?: Options.Notification): Notification; - - /** Add a warning notification. */ - addWarning(message: string, options?: Options.Notification): Notification; - - /** Add an error notification. */ - addError(message: string, options?: Options.ErrorNotification): Notification; - - /** Add a fatal error notification. */ - addFatalError(message: string, options?: Options.ErrorNotification): Notification; - - // Getting Notifications - /** Get all the notifications. */ - getNotifications(): Notification[]; - } - - /** Loads and activates a package's main module and resources such as stylesheets, - * keymaps, grammar, editor properties, and menus. - */ - interface Package { - // Properties - name: string; - bundledPackage: boolean; - path: string; - - // Event Subscription - /** Invoke the given callback when all packages have been activated. */ - onDidDeactivate(callback: () => void): EventKit.Disposable; - - // Native Module Compatibility - /** Are all native modules depended on by this package correctly compiled - * against the current version of Atom? - */ - isCompatible(): boolean; - - /** Rebuild native modules in this package's dependencies for the current - * version of Atom. - */ - rebuild(): Promise<{ code: number, stdout: string, stderr: string }>; - - /** If a previous rebuild failed, get the contents of stderr. */ - getBuildFailureOutput(): string|null; - } - - /** Package manager for coordinating the lifecycle of Atom packages. */ - interface PackageManager { - // Event Subscription - /** Invoke the given callback when all packages have been loaded. */ - onDidLoadInitialPackages(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when all packages have been activated. */ - onDidActivateInitialPackages(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when a package is activated. */ - onDidActivatePackage(callback: (package: Package) => void): EventKit.Disposable; - - /** Invoke the given callback when a package is deactivated. */ - onDidDeactivatePackage(callback: (package: Package) => void): EventKit.Disposable; - - /** Invoke the given callback when a package is loaded. */ - onDidLoadPackage(callback: (package: Package) => void): EventKit.Disposable; - - /** Invoke the given callback when a package is unloaded. */ - onDidUnloadPackage(callback: (package: Package) => void): EventKit.Disposable; - - // Package System Data - /** Get the path to the apm command. */ - getApmPath(): string; - - /** Get the paths being used to look for packages. */ - getPackageDirPaths(): string[]; - - // General Package Data - /** Resolve the given package name to a path on disk. */ - resolvePackagePath(name: string): string|undefined; - - /** Is the package with the given name bundled with Atom? */ - isBundledPackage(name: string): boolean; - - // Enabling and Disabling Packages - /** Enable the package with the given name. */ - enablePackage(name: string): Package|undefined; - - /** Disable the package with the given name. */ - disablePackage(name: string): Package|undefined; - - /** Is the package with the given name disabled? */ - isPackageDisabled(name: string): boolean; - - // Accessing Active Packages - /** Get an Array of all the active Packages. */ - getActivePackages(): Package[]; - - /** Get the active Package with the given name. */ - getActivePackage(name: string): Package|undefined; - - /** Is the Package with the given name active? */ - isPackageActive(name: string): boolean; - - /** Returns a boolean indicating whether package activation has occurred. */ - hasActivatedInitialPackages(): boolean; - - // Accessing Loaded Packages - /** Get an Array of all the loaded Packages. */ - getLoadedPackages(): Package[]; - - /** Get the loaded Package with the given name. */ - getLoadedPackage(name: string): Package|undefined; - - /** Is the package with the given name loaded? */ - isPackageLoaded(name: string): boolean; - - /** Returns a boolean indicating whether package loading has occurred. */ - hasLoadedInitialPackages(): boolean; - - // Accessing Available Packages - /** Returns an Array of strings of all the available package paths. */ - getAvailablePackagePaths(): string[]; - - /** Returns an Array of strings of all the available package names. */ - getAvailablePackageNames(): string[]; - - /** Returns an Array of strings of all the available package metadata. */ - getAvailablePackageMetadata(): string[]; - } - - /** A container for presenting content in the center of the workspace. */ - interface Pane { - // Event Subscription - /** Invoke the given callback when the pane resizes. */ - onDidChangeFlexScale(callback: (flexScale: number) => void): EventKit.Disposable; - - /** Invoke the given callback with the current and future values of ::getFlexScale. */ - observeFlexScale(callback: (flexScale: number) => void): EventKit.Disposable; - - /** Invoke the given callback when the pane is activated. */ - onDidActivate(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback before the pane is destroyed. */ - onWillDestroy(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when the pane is destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when the value of the ::isActive property changes. */ - onDidChangeActive(callback: (active: boolean) => void): EventKit.Disposable; - - /** Invoke the given callback with the current and future values of the ::isActive - * property. - */ - observeActive(callback: (active: boolean) => void): EventKit.Disposable; - - /** Invoke the given callback when an item is added to the pane. */ - onDidAddItem(callback: (event: Events.PaneListItemShifted) => void): - EventKit.Disposable; - - /** Invoke the given callback when an item is removed from the pane. */ - onDidRemoveItem(callback: (event: Events.PaneListItemShifted) => void): - EventKit.Disposable; - - /** Invoke the given callback before an item is removed from the pane. */ - onWillRemoveItem(callback: (event: Events.PaneListItemShifted) => void): - EventKit.Disposable; - - /** Invoke the given callback when an item is moved within the pane. */ - onDidMoveItem(callback: (event: Events.PaneItemMoved) => void): - EventKit.Disposable; - - /** Invoke the given callback with all current and future items. */ - observeItems(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the value of ::getActiveItem changes. */ - onDidChangeActiveItem(callback: (activeItem: object) => void): EventKit.Disposable; - - /** Invoke the given callback when ::activateNextRecentlyUsedItem has been called, - * either initiating or continuing a forward MRU traversal of pane items. - */ - onChooseNextMRUItem(callback: (nextRecentlyUsedItem: object) => void): - EventKit.Disposable; - - /** Invoke the given callback when ::activatePreviousRecentlyUsedItem has been called, - * either initiating or continuing a reverse MRU traversal of pane items. - */ - onChooseLastMRUItem(callback: (previousRecentlyUsedItem: object) => void): - EventKit.Disposable; - - /** Invoke the given callback when ::moveActiveItemToTopOfStack has been called, - * terminating an MRU traversal of pane items and moving the current active item - * to the top of the stack. Typically bound to a modifier (e.g. CTRL) key up event. - */ - onDoneChoosingMRUItem(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback with the current and future values of ::getActiveItem. */ - observeActiveItem(callback: (activeItem: object) => void): EventKit.Disposable; - - /** Invoke the given callback before items are destroyed. */ - onWillDestroyItem(callback: (event: Events.PaneListItemShifted) => void): - EventKit.Disposable; - - // Items - /** Get the items in this pane. */ - getItems(): object[]; - - /** Get the active pane item in this pane. */ - getActiveItem(): object; - - /** Return the item at the given index. */ - itemAtIndex(index: number): object|undefined; - - /** Makes the next item active. */ - activateNextItem(): void; - - /** Makes the previous item active. */ - activatePreviousItem(): void; - - /** Move the active tab to the right. */ - moveItemRight(): void; - - /** Move the active tab to the left. */ - moveItemLeft(): void; - - /** Get the index of the active item. */ - getActiveItemIndex(): number; - - /** Activate the item at the given index. */ - activateItemAtIndex(index: number): void; - - /** Make the given item active, causing it to be displayed by the pane's view. */ - activateItem(item: object, options?: { pending: boolean }): void; - - /** Add the given item to the pane. */ - addItem(item: object, options?: { index?: number, pending?: boolean }): object; - - /** Add the given items to the pane. */ - addItems(items: object[], index?: number): object[]; - - /** Move the given item to the given index. */ - moveItem(item: object, index: number): void; - - /** Move the given item to the given index on another pane. */ - moveItemToPane(item: object, pane: Pane, index: number): void; - - /** Destroy the active item and activate the next item. */ - destroyActiveItem(): void; - - /** Destroy the given item. */ - destroyItem(item: object, force?: boolean): Promise; - - /** Destroy all items. */ - destroyItems(): void; - - /** Destroy all items except for the active item. */ - destroyInactiveItems(): void; - - /** Save the active item. */ - saveActiveItem(nextAction?: (error?: Error) => T): - Promise|undefined; - - /** Prompt the user for a location and save the active item with the path - * they select. - */ - saveActiveItemAs(nextAction?: (error?: Error) => T): - Promise|undefined; - - /** Save the given item. */ - saveItem(item: object, nextAction?: (error?: Error) => T): - Promise|undefined; - - /** Prompt the user for a location and save the active item with the path - * they select. - */ - saveItemAs(item: object, nextAction?: (error?: Error) => T): - Promise|undefined; - - /** Save all items. */ - saveItems(): void; - - /** Return the first item that matches the given URI or undefined if none exists. */ - itemForURI(uri: string): object|undefined; - - /** Activate the first item that matches the given URI. */ - activateItemForURI(uri: string): boolean; - - // Lifecycle - /** Determine whether the pane is active. */ - isActive(): boolean; - - /** Makes this pane the active pane, causing it to gain focus. */ - activate(): void; - - /** Close the pane and destroy all its items. */ - destroy(): void; - - /** Determine whether this pane has been destroyed. */ - isDestroyed(): boolean; - - // Splitting - /** Create a new pane to the left of this pane. */ - splitLeft(params?: { - items?: object[], - copyActiveItem?: boolean, - }): Pane; - - /** Create a new pane to the right of this pane. */ - splitRight(params?: { - items?: object[], - copyActiveItem?: boolean, - }): Pane; - - /** Creates a new pane above the receiver. */ - splitUp(params?: { - items?: object[], - copyActiveItem?: boolean, - }): Pane; - - /** Creates a new pane below the receiver. */ - splitDown(params?: { - items?: object[], - copyActiveItem?: boolean, - }): Pane; - } - - /** A container representing a panel on the edges of the editor window. You - * should not create a Panel directly, instead use Workspace::addTopPanel and - * friends to add panels. - */ - interface Panel { - visible: boolean; - - // Construction and Destruction - /** Destroy and remove this panel from the UI. */ - destroy(): void; - - // Event Subscription - /** Invoke the given callback when the pane hidden or shown. */ - onDidChangeVisible(callback: (visible: boolean) => void): EventKit.Disposable; - - /** Invoke the given callback when the pane is destroyed. */ - onDidDestroy(callback: (panel: Panel) => void): EventKit.Disposable; - - // Panel Details - /** Returns the panel's item. */ - getItem(): object; - - /** Returns a number indicating this panel's priority. */ - getPriority(): number; - - /** Returns a boolean true when the panel is visible. */ - isVisible(): boolean; - - /** Hide this panel. */ - hide(): void; - - /** Show this panel. */ - show(): void; - } - - /** Manage a subscription to filesystem events that occur beneath a root directory. */ - interface PathWatcher extends EventKit.DisposableLike { - /** Return a Promise that will resolve when the underlying native watcher is - * ready to begin sending events. - */ - getStartPromise(): Promise; - - /** Invokes a function when any errors related to this watcher are reported. */ - onDidError(callback: (error: Error) => void): EventKit.Disposable; - - /** Unsubscribe all subscribers from filesystem events. Native resources will be - * release asynchronously, but this watcher will stop broadcasting events - * immediately. - */ - dispose(): void; - } - - /** Represents a project that's opened in Atom. */ - interface Project { - // Event Subscription - /** Invoke the given callback when the project paths change. */ - onDidChangePaths(callback: (projectPaths: string[]) => void): EventKit.Disposable; - - /** Invoke the given callback when a text buffer is added to the project. */ - onDidAddBuffer(callback: (buffer: TextBuffer.TextBuffer) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future text buffers in - * the project. - */ - observeBuffers(callback: (buffer: TextBuffer.TextBuffer) => void): EventKit.Disposable; - - /** Invoke a callback when a filesystem change occurs within any open project path. */ - onDidChangeFiles(callback: (events: Events.FilesystemChange) => void): - EventKit.Disposable; - - // Accessing the Git Repository - /** Get an Array of GitRepositorys associated with the project's directories. */ - getRepositories(): GitRepository[]; - - /** Get the repository for a given directory asynchronously. */ - repositoryForDirectory(directory: PathWatcher.Directory): Promise; - - // Managing Paths - /** Get an Array of strings containing the paths of the project's directories. */ - getPaths(): string[]; - - /** Set the paths of the project's directories. */ - setPaths(projectPaths: string[]): void; - - /** Add a path to the project's list of root paths. */ - addPath(projectPath: string): void; - - /** Access a promise that resolves when the filesystem watcher associated with a - * project root directory is ready to begin receiving events. - */ - getWatcherPromise(projectPath: string): Promise; - - /** Remove a path from the project's list of root paths. */ - removePath(projectPath: string): void; - - /** Get an Array of Directorys associated with this project. */ - getDirectories(): PathWatcher.Directory[]; - - /** Get the relative path from the project directory to the given path. */ - relativize(fullPath: string): string; - - /** Get the path to the project directory that contains the given path, and - * the relative path from that project directory to the given path. - */ - relativizePath(fullPath: string): [string|null, string]; - - /** Determines whether the given path (real or symbolic) is inside the - * project's directory. - */ - contains(pathToCheck: string): boolean; - } - - /** Wraps an Array of Strings. The Array describes a path from the root of the - * syntax tree to a token including all scope names for the entire path. - */ - interface ScopeDescriptor { - scopes: string[]; - - /** Returns all scopes for this descriptor. */ - getScopesArray(): string[]; - } - - /** Represents a selection in the TextEditor. */ - interface Selection { - // Event Subscription - /** Calls your callback when the selection was moved. */ - onDidChangeRange(callback: (event: Events.SelectionChanged) => void): - EventKit.Disposable; - - /** Calls your callback when the selection was destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - // Managing the selection range - /** Returns the screen Range for the selection. */ - getScreenRange(): TextBuffer.Range; - - /** Modifies the screen range for the selection. */ - setScreenRange(screenRange: TextBuffer.RangeCompatible, options?: - { preserveFolds?: boolean, autoscroll?: boolean }): void; - - /** Returns the buffer Range for the selection. */ - getBufferRange(): TextBuffer.Range; - - /** Modifies the buffer Range for the selection. */ - setBufferRange(bufferRange: TextBuffer.RangeCompatible, options?: - { preserveFolds?: boolean, autoscroll?: boolean }): void; - - /** Returns the starting and ending buffer rows the selection is highlighting. */ - getBufferRowRange(): [number, number]; - - // Info about the selection - /** Determines if the selection contains anything. */ - isEmpty(): boolean; - - /** Determines if the ending position of a marker is greater than the starting position. - * This can happen when, for example, you highlight text "up" in a TextBuffer. - */ - isReversed(): boolean; - - /** Returns whether the selection is a single line or not. */ - isSingleScreenLine(): boolean; - - /** Returns the text in the selection. */ - getText(): string; - - // NOTE: this calls into Range.intersectsWith(), which is one of the few functions - // that doesn't take a range-compatible range, despite what the API says. - /** Identifies if a selection intersects with a given buffer range. */ - intersectsBufferRange(bufferRange: TextBuffer.RangeLike): boolean; - - /** Identifies if a selection intersects with another selection. */ - intersectsWith(otherSelection: Selection): boolean; - - // Modifying the selected range - /** Clears the selection, moving the marker to the head. */ - clear(options?: { autoscroll?: boolean }): void; - - /** Selects the text from the current cursor position to a given screen position. */ - selectToScreenPosition(position: TextBuffer.PointCompatible): void; - - /** Selects the text from the current cursor position to a given buffer position. */ - selectToBufferPosition(position: TextBuffer.PointCompatible): void; - - /** Selects the text one position right of the cursor. */ - selectRight(columnCount?: number): void; - - /** Selects the text one position left of the cursor. */ - selectLeft(columnCount?: number): void; - - /** Selects all the text one position above the cursor. */ - selectUp(rowCount?: number): void; - - /** Selects all the text one position below the cursor. */ - selectDown(rowCount?: number): void; - - /** Selects all the text from the current cursor position to the top of the - * buffer. - */ - selectToTop(): void; - - /** Selects all the text from the current cursor position to the bottom of - * the buffer. - */ - selectToBottom(): void; - - /** Selects all the text in the buffer. */ - selectAll(): void; - - /** Selects all the text from the current cursor position to the beginning of - * the line. - */ - selectToBeginningOfLine(): void; - - /** Selects all the text from the current cursor position to the first character - * of the line. - */ - selectToFirstCharacterOfLine(): void; - - /** Selects all the text from the current cursor position to the end of the - * screen line. - */ - selectToEndOfLine(): void; - - /** Selects all the text from the current cursor position to the end of the - * buffer line. - */ - selectToEndOfBufferLine(): void; - - /** Selects all the text from the current cursor position to the beginning - * of the word. - */ - selectToBeginningOfWord(): void; - - /** Selects all the text from the current cursor position to the end of the word. */ - selectToEndOfWord(): void; - - /** Selects all the text from the current cursor position to the beginning of - * the next word. - */ - selectToBeginningOfNextWord(): void; - - /** Selects text to the previous word boundary. */ - selectToPreviousWordBoundary(): void; - - /** Selects text to the next word boundary. */ - selectToNextWordBoundary(): void; - - /** Selects text to the previous subword boundary. */ - selectToPreviousSubwordBoundary(): void; - - /** Selects text to the next subword boundary. */ - selectToNextSubwordBoundary(): void; - - /** Selects all the text from the current cursor position to the beginning of - * the next paragraph. - */ - selectToBeginningOfNextParagraph(): void; - - /** Selects all the text from the current cursor position to the beginning of - * the previous paragraph. - */ - selectToBeginningOfPreviousParagraph(): void; - - /** Modifies the selection to encompass the current word. */ - selectWord(): void; - - /** Expands the newest selection to include the entire word on which the - * cursors rests. - */ - expandOverWord(): void; - - /** Selects an entire line in the buffer. */ - selectLine(row: number): void; - - /** Expands the newest selection to include the entire line on which the cursor - * currently rests. - * It also includes the newline character. - */ - expandOverLine(): void; - - // Modifying the selected text - /** Replaces text at the current selection. */ - insertText(text: string, options?: Options.TextInsertion): void; - - /** Removes the first character before the selection if the selection is empty - * otherwise it deletes the selection. - */ - backspace(): void; - - /** Removes the selection or, if nothing is selected, then all characters from - * the start of the selection back to the previous word boundary. - */ - deleteToPreviousWordBoundary(): void; - - /** Removes the selection or, if nothing is selected, then all characters from - * the start of the selection up to the next word boundary. - */ - deleteToNextWordBoundary(): void; - - /** Removes from the start of the selection to the beginning of the current - * word if the selection is empty otherwise it deletes the selection. - */ - deleteToBeginningOfWord(): void; - - /** Removes from the beginning of the line which the selection begins on all - * the way through to the end of the selection. - */ - deleteToBeginningOfLine(): void; - - /** Removes the selection or the next character after the start of the selection - * if the selection is empty. - */ - delete(): void; - - /** If the selection is empty, removes all text from the cursor to the end of - * the line. If the cursor is already at the end of the line, it removes the following - * newline. If the selection isn't empty, only deletes the contents of the selection. - */ - deleteToEndOfLine(): void; - - /** Removes the selection or all characters from the start of the selection to - * the end of the current word if nothing is selected. - */ - deleteToEndOfWord(): void; - - /** Removes the selection or all characters from the start of the selection to - * the end of the current word if nothing is selected. - */ - deleteToBeginningOfSubword(): void; - - /** Removes the selection or all characters from the start of the selection to - * the end of the current word if nothing is selected. - */ - deleteToEndOfSubword(): void; - - /** Removes only the selected text. */ - deleteSelectedText(): void; - - /** Removes the line at the beginning of the selection if the selection is empty - * unless the selection spans multiple lines in which case all lines are removed. - */ - deleteLine(): void; - - /** Joins the current line with the one below it. Lines will be separated by a single space. - * If there selection spans more than one line, all the lines are joined together. - */ - joinLines(): void; - - /** Removes one level of indent from the currently selected rows. */ - outdentSelectedRows(): void; - - /** Sets the indentation level of all selected rows to values suggested by the - * relevant grammars. - */ - autoIndentSelectedRows(): void; - - /** Wraps the selected lines in comments if they aren't currently part of a comment. - * Removes the comment if they are currently wrapped in a comment. - */ - toggleLineComments(): void; - - /** Cuts the selection until the end of the screen line. */ - cutToEndOfLine(): void; - - /** Cuts the selection until the end of the buffer line. */ - cutToEndOfBufferLine(): void; - - /** Copies the selection to the clipboard and then deletes it. */ - cut(maintainClipboard?: boolean, fullLine?: boolean): void; - - /** Copies the current selection to the clipboard. */ - copy(maintainClipboard?: boolean, fullLine?: boolean): void; - - /** Creates a fold containing the current selection. */ - fold(): void; - - /** If the selection spans multiple rows, indent all of them. */ - indentSelectedRows(): void; - - // Managing multiple selections - /** Moves the selection down one row. */ - addSelectionBelow(): void; - - /** Moves the selection up one row. */ - addSelectionAbove(): void; - - /** Combines the given selection into this selection and then destroys the - * given selection. - */ - merge(otherSelection: Selection, options?: { preserveFolds?: boolean, - autoscroll?: boolean }): void; - - // Comparing to other selections - /** Compare this selection's buffer range to another selection's buffer range. - * See Range::compare for more details. - */ - compare(otherSelection: Selection): number; - } - - /** A singleton instance of this class available via atom.styles, which you can - * use to globally query and observe the set of active style sheets. - */ - interface StyleManager { - // Event Subscription - /** Invoke callback for all current and future style elements. */ - observeStyleElements(callback: (styleElement: Events.StyleElementObserved) => - void): EventKit.Disposable; - - /** Invoke callback when a style element is added. */ - onDidAddStyleElement(callback: (styleElement: Events.StyleElementObserved) => - void): EventKit.Disposable; - - /** Invoke callback when a style element is removed. */ - onDidRemoveStyleElement(callback: (styleElement: HTMLStyleElement) => void): - EventKit.Disposable; - - /** Invoke callback when an existing style element is updated. */ - onDidUpdateStyleElement(callback: (styleElement: Events.StyleElementObserved) => - void): EventKit.Disposable; - - // Reading Style Elements - /** Get all loaded style elements. */ - getStyleElements(): HTMLStyleElement[]; - - // Paths - /** Get the path of the user style sheet in ~/.atom. */ - getUserStyleSheetPath(): string; - } - - /** Run a node script in a separate process. */ - interface Task { - // NOTE: this is actually the best we can do here with the REST parameter - // for this appearing in the beginning of the parameter list, which isn't - // aligned with the ES6 spec. - /** Starts the task. - * Throws an error if this task has already been terminated or if sending a - * message to the child process fails. - */ - // tslint:disable-next-line:no-any - start(...args: any[]): void; - - /** Send message to the task. - * Throws an error if this task has already been terminated or if sending a - * message to the child process fails. - */ - send(message: string): void; - - /** Call a function when an event is emitted by the child process. */ - // tslint:disable-next-line:no-any - on(eventName: string, callback: (param: any) => void): EventKit.Disposable; - - /** Forcefully stop the running task. - * No more events are emitted once this method is called. - */ - terminate(): void; - - /** Cancel the running task and emit an event if it was canceled. */ - cancel(): boolean; - } - - /** The static side to the Task class. */ - interface TaskStatic { - // NOTE: this is actually the best we can do here with the REST parameter for - // this appearing in the middle of the parameter list, which isn't aligned with - // the ES6 spec. Maybe when they rewrite it in JavaScript this will change. - /** A helper method to easily launch and run a task once. */ - // tslint:disable-next-line:no-any - once(taskPath: string, ...args: any[]): Task; - - /** Creates a task. You should probably use .once */ - new (taskPath: string): Task; - } - - /** An interface which all custom test runners should implement. */ - type TestRunner = (params: Structures.TestRunnerArgs) => Promise; - - /** This class represents all essential editing state for a single TextBuffer, - * including cursor and selection positions, folds, and soft wraps. - */ - interface TextEditor { - id: number; - buffer: TextBuffer.TextBuffer; - element: HTMLElement; - - // Event Subscription - /** Calls your callback when the buffer's title has changed. */ - onDidChangeTitle(callback: (title: string) => void): EventKit.Disposable; - - /** Calls your callback when the buffer's path, and therefore title, has changed. */ - onDidChangePath(callback: (path: string) => void): EventKit.Disposable; - - /** Invoke the given callback synchronously when the content of the buffer - * changes. - */ - onDidChange(callback: (event: Events.EditorChanged[]) => void): EventKit.Disposable; - - /** Invoke callback when the buffer's contents change. It is emit - * asynchronously 300ms after the last buffer change. This is a good place - * to handle changes to the buffer without compromising typing performance. - */ - onDidStopChanging(callback: (event: TextBuffer.Events.BufferStoppedChanging) => void): - EventKit.Disposable; - - /** Calls your callback when a Cursor is moved. If there are multiple cursors, - * your callback will be called for each cursor. - */ - onDidChangeCursorPosition(callback: (event: Events.CursorPositionChanged) => void): - EventKit.Disposable; - - /** Calls your callback when a selection's screen range changes. */ - onDidChangeSelectionRange(callback: (event: Events.SelectionChanged) => void): - EventKit.Disposable; - - /** Invoke the given callback after the buffer is saved to disk. */ - onDidSave(callback: (event: { path: string }) => void): EventKit.Disposable; - - /** Invoke the given callback when the editor is destroyed. */ - onDidDestroy(callback: () => void): EventKit.Disposable; - - /** Retrieves the current TextBuffer. */ - getBuffer(): TextBuffer.TextBuffer; - - /** Calls your callback when a Gutter is added to the editor. Immediately calls - * your callback for each existing gutter. - */ - observeGutters(callback: (gutter: Gutter) => void): EventKit.Disposable; - - /** Calls your callback when a Gutter is added to the editor. */ - onDidAddGutter(callback: (gutter: Gutter) => void): EventKit.Disposable; - - /** Calls your callback when a Gutter is removed from the editor. */ - onDidRemoveGutter(callback: (name: string) => void): EventKit.Disposable; - - /** Calls your callback when soft wrap was enabled or disabled. */ - onDidChangeSoftWrapped(callback: (softWrapped: boolean) => void): EventKit.Disposable; - - /** Calls your callback when the buffer's encoding has changed. */ - onDidChangeEncoding(callback: (encoding: string) => void): EventKit.Disposable; - - /** Calls your callback when the grammar that interprets and colorizes the text - * has been changed. Immediately calls your callback with the current grammar. - */ - observeGrammar(callback: (grammar: FirstMate.Grammar) => void): EventKit.Disposable; - - /** Calls your callback when the grammar that interprets and colorizes the text - * has been changed. - */ - onDidChangeGrammar(callback: (grammar: FirstMate.Grammar) => void): EventKit.Disposable; - - /** Calls your callback when the result of ::isModified changes. */ - onDidChangeModified(callback: (modified: boolean) => void): EventKit.Disposable; - - /** Calls your callback when the buffer's underlying file changes on disk at a - * moment when the result of ::isModified is true. - */ - onDidConflict(callback: () => void): EventKit.Disposable; - - /** Calls your callback before text has been inserted. */ - onWillInsertText(callback: (event: { text: string, cancel(): void }) => void): - EventKit.Disposable; - - /** Calls your callback after text has been inserted. */ - onDidInsertText(callback: (event: { text: string }) => void): EventKit.Disposable; - - /** Calls your callback when a Cursor is added to the editor. Immediately calls - * your callback for each existing cursor. - */ - observeCursors(callback: (cursor: Cursor) => void): EventKit.Disposable; - - /** Calls your callback when a Cursor is added to the editor. */ - onDidAddCursor(callback: (cursor: Cursor) => void): EventKit.Disposable; - - /** Calls your callback when a Cursor is removed from the editor. */ - onDidRemoveCursor(callback: (cursor: Cursor) => void): EventKit.Disposable; - - /** Calls your callback when a Selection is added to the editor. Immediately - * calls your callback for each existing selection. - */ - observeSelections(callback: (selection: Selection) => void): EventKit.Disposable; - - /** Calls your callback when a Selection is added to the editor. */ - onDidAddSelection(callback: (selection: Selection) => void): EventKit.Disposable; - - /** Calls your callback when a Selection is removed from the editor. */ - onDidRemoveSelection(callback: (selection: Selection) => void): EventKit.Disposable; - - /** Calls your callback with each Decoration added to the editor. Calls your - * callback immediately for any existing decorations. - */ - observeDecorations(callback: (decoration: Decoration) => void): EventKit.Disposable; - - /** Calls your callback when a Decoration is added to the editor. */ - onDidAddDecoration(callback: (decoration: Decoration) => void): EventKit.Disposable; - - /** Calls your callback when a Decoration is removed from the editor. */ - onDidRemoveDecoration(callback: (decoration: Decoration) => void): EventKit.Disposable; - - /** Calls your callback when the placeholder text is changed. */ - onDidChangePlaceholderText(callback: (placeholderText: string) => void): - EventKit.Disposable; - - // File Details - /** Get the editor's title for display in other parts of the UI such as the tabs. - * If the editor's buffer is saved, its title is the file name. If it is unsaved, - * its title is "untitled". - */ - getTitle(): string; - - /** Get unique title for display in other parts of the UI, such as the window title. - * If the editor's buffer is unsaved, its title is "untitled" If the editor's - * buffer is saved, its unique title is formatted as one of the following, - * - * "" when it is the only editing buffer with this file name. - * " — " when other buffers have this file name. - */ - getLongTitle(): string; - - /** Returns the string path of this editor's text buffer. */ - getPath(): string|undefined; - - /** Returns boolean true if this editor has been modified. */ - isModified(): boolean; - - /** Returns boolean true if this editor has no content. */ - isEmpty(): boolean; - - /** Returns the string character set encoding of this editor's text buffer. */ - getEncoding(): string; - - /** Set the character set encoding to use in this editor's text buffer. */ - setEncoding(encoding: string): void; - - // File Operations - /** Saves the editor's text buffer. - * See TextBuffer::save for more details. - */ - save(): Promise; - - /** Saves the editor's text buffer as the given path. - * See TextBuffer::saveAs for more details. - */ - saveAs(filePath: string): Promise; - - // Reading Text - /** Returns a string representing the entire contents of the editor. */ - getText(): string; - - /** Get the text in the given range in buffer coordinates. */ - getTextInBufferRange(range: TextBuffer.RangeCompatible): string; - - /** Returns a number representing the number of lines in the buffer. */ - getLineCount(): number; - - /** Returns a number representing the number of screen lines in the editor. - * This accounts for folds. - */ - getScreenLineCount(): number; - - /** Returns a number representing the last zero-indexed buffer row number of - * the editor. - */ - getLastBufferRow(): number; - - /** Returns a number representing the last zero-indexed screen row number of - * the editor. - */ - getLastScreenRow(): number; - - /** Returns a string representing the contents of the line at the given - * buffer row. - */ - lineTextForBufferRow(bufferRow: number): string; - - /** Returns a string representing the contents of the line at the given - * screen row. - */ - lineTextForScreenRow(screenRow: number): string; - - /** Get the range of the paragraph surrounding the most recently added cursor. */ - getCurrentParagraphBufferRange(): TextBuffer.Range; - - // Mutating Text - /** Replaces the entire contents of the buffer with the given string. */ - setText(text: string): void; - - /** Set the text in the given Range in buffer coordinates. */ - setTextInBufferRange(range: TextBuffer.RangeCompatible, text: string, options?: - { normalizeLineEndings?: boolean, undo?: "skip" }): void; - - /* For each selection, replace the selected text with the given text. */ - insertText(text: string, options?: { select?: boolean, autoIndent?: boolean, - autoIndentNewline?: boolean, autoDecreaseIndent?: boolean, - normalizeLineEndings?: boolean, undo?: "skip" }): TextBuffer.Range|boolean; - - /** For each selection, replace the selected text with a newline. */ - insertNewline(): void; - - /** For each selection, if the selection is empty, delete the character following - * the cursor. Otherwise delete the selected text. - */ - delete(): void; - - /** For each selection, if the selection is empty, delete the character preceding - * the cursor. Otherwise delete the selected text. - */ - backspace(): void; - - /** Mutate the text of all the selections in a single transaction. - * All the changes made inside the given function can be reverted with a single - * call to ::undo. - */ - mutateSelectedText(fn: (selection: Selection, index: number) => void): void; - - /** For each selection, transpose the selected text. - * If the selection is empty, the characters preceding and following the cursor - * are swapped. Otherwise, the selected characters are reversed. - */ - transpose(): void; - - /** Convert the selected text to upper case. - * For each selection, if the selection is empty, converts the containing word - * to upper case. Otherwise convert the selected text to upper case. - */ - upperCase(): void; - - /** Convert the selected text to lower case. - * For each selection, if the selection is empty, converts the containing word - * to upper case. Otherwise convert the selected text to upper case. - */ - lowerCase(): void; - - /** Toggle line comments for rows intersecting selections. - * If the current grammar doesn't support comments, does nothing. - */ - toggleLineCommentsInSelection(): void; - - /** For each cursor, insert a newline at beginning the following line. */ - insertNewlineBelow(): void; - - /** For each cursor, insert a newline at the end of the preceding line. */ - insertNewlineAbove(): void; - - /** For each selection, if the selection is empty, delete all characters of the - * containing word that precede the cursor. Otherwise delete the selected text. - */ - deleteToBeginningOfWord(): void; - - /** Similar to ::deleteToBeginningOfWord, but deletes only back to the previous - * word boundary. - */ - deleteToPreviousWordBoundary(): void; - - /** Similar to ::deleteToEndOfWord, but deletes only up to the next word boundary. */ - deleteToNextWordBoundary(): void; - - /** For each selection, if the selection is empty, delete all characters of the - * containing subword following the cursor. Otherwise delete the selected text. - */ - deleteToBeginningOfSubword(): void; - - /** For each selection, if the selection is empty, delete all characters of the - * containing subword following the cursor. Otherwise delete the selected text. - */ - deleteToEndOfSubword(): void; - - /** For each selection, if the selection is empty, delete all characters of the - * containing line that precede the cursor. Otherwise delete the selected text. - */ - deleteToBeginningOfLine(): void; - - /** For each selection, if the selection is not empty, deletes the selection - * otherwise, deletes all characters of the containing line following the cursor. - * If the cursor is already at the end of the line, deletes the following newline. - */ - deleteToEndOfLine(): void; - - /** For each selection, if the selection is empty, delete all characters of the - * containing word following the cursor. Otherwise delete the selected text. - */ - deleteToEndOfWord(): void; - - /** Delete all lines intersecting selections. */ - deleteLine(): void; - - // History - /** Undo the last change. */ - undo(): void; - - /** Redo the last change. */ - redo(): void; - - /** Batch multiple operations as a single undo/redo step. - * Any group of operations that are logically grouped from the perspective of undoing - * and redoing should be performed in a transaction. If you want to abort the transaction, - * call ::abortTransaction to terminate the function's execution and revert any changes - * performed up to the abortion. - */ - transact(fn: () => void): void; - /** Batch multiple operations as a single undo/redo step. - * Any group of operations that are logically grouped from the perspective of undoing - * and redoing should be performed in a transaction. If you want to abort the transaction, - * call ::abortTransaction to terminate the function's execution and revert any changes - * performed up to the abortion. - */ - transact(groupingInterval: number, fn: () => void): void; - - /** Abort an open transaction, undoing any operations performed so far within the - * transaction. - */ - abortTransaction(): void; - - /** Create a pointer to the current state of the buffer for use with ::revertToCheckpoint - * and ::groupChangesSinceCheckpoint. - */ - createCheckpoint(): number; - - /** Revert the buffer to the state it was in when the given checkpoint was created. - * The redo stack will be empty following this operation, so changes since the checkpoint - * will be lost. If the given checkpoint is no longer present in the undo history, no - * changes will be made to the buffer and this method will return false. - */ - revertToCheckpoint(checkpoint: number): boolean; - - /** Group all changes since the given checkpoint into a single transaction for purposes - * of undo/redo. - * If the given checkpoint is no longer present in the undo history, no grouping will be - * performed and this method will return false. - */ - groupChangesSinceCheckpoint(checkpoint: number): boolean; - - // TextEditor Coordinates - /** Convert a position in buffer-coordinates to screen-coordinates. */ - screenPositionForBufferPosition(bufferPosition: TextBuffer.PointCompatible, options?: - { clipDirection?: "backward"|"forward"|"closest"}): TextBuffer.Point; - - /** Convert a position in screen-coordinates to buffer-coordinates. */ - bufferPositionForScreenPosition(bufferPosition: TextBuffer.PointCompatible, options?: - { clipDirection?: "backward"|"forward"|"closest"}): TextBuffer.Point; - - /** Convert a range in buffer-coordinates to screen-coordinates. */ - screenRangeForBufferRange(bufferRange: TextBuffer.RangeCompatible): TextBuffer.Range; - - /** Convert a range in screen-coordinates to buffer-coordinates. */ - bufferRangeForScreenRange(screenRange: TextBuffer.RangeCompatible): TextBuffer.Range; - - /** Clip the given Point to a valid position in the buffer. */ - clipBufferPosition(bufferPosition: TextBuffer.PointCompatible): TextBuffer.Point; - - /** Clip the start and end of the given range to valid positions in the buffer. - * See ::clipBufferPosition for more information. - */ - clipBufferRange(range: TextBuffer.RangeCompatible): TextBuffer.Range; - - /** Clip the given Point to a valid position on screen. */ - clipScreenPosition(screenPosition: TextBuffer.PointCompatible, options?: - { clipDirection?: "backward"|"forward"|"closest"}): TextBuffer.Point; - - /** Clip the start and end of the given range to valid positions on screen. - * See ::clipScreenPosition for more information. - */ - clipScreenRange(range: TextBuffer.RangeCompatible, options?: { clipDirection?: - "backward"|"forward"|"closest"}): TextBuffer.Range; - - // Decorations - /** Add a decoration that tracks a DisplayMarker. When the marker moves, is - * invalidated, or is destroyed, the decoration will be updated to reflect - * the marker's state. - */ - decorateMarker(marker: TextBuffer.DisplayMarker, decorationParams: Options.DecorationProps): - Decoration; - - /** Add a decoration to every marker in the given marker layer. Can be used to - * decorate a large number of markers without having to create and manage many - * individual decorations. - */ - decorateMarkerLayer(markerLayer: TextBuffer.MarkerLayer|TextBuffer.DisplayMarkerLayer, - decorationParams: Options.DecorationLayerProps): LayerDecoration; - - /** Get all decorations. */ - getDecorations(propertyFilter?: Options.DecorationProps): Decoration[]; - - /** Get all decorations of type 'line'. */ - getLineDecorations(propertyFilter?: Options.DecorationProps): Decoration[]; - - /** Get all decorations of type 'line-number'. */ - getLineNumberDecorations(propertyFilter?: Options.DecorationProps): Decoration[]; - - /** Get all decorations of type 'highlight'. */ - getHighlightDecorations(propertyFilter?: Options.DecorationProps): Decoration[]; - - /** Get all decorations of type 'overlay'. */ - getOverlayDecorations(propertyFilter?: Options.DecorationProps): Decoration[]; - - // Markers - /** Create a marker on the default marker layer with the given range in buffer coordinates. - * This marker will maintain its logical location as the buffer is changed, so if you mark - * a particular word, the marker will remain over that word even if the word's location - * in the buffer changes. - */ - markBufferRange(range: TextBuffer.RangeCompatible, properties?: { maintainHistory?: - boolean, reversed?: boolean, invalidate?: "never"|"surround"|"overlap"|"inside" - |"touch" }): TextBuffer.DisplayMarker; - - /** Create a marker on the default marker layer with the given range in screen coordinates. - * This marker will maintain its logical location as the buffer is changed, so if you mark - * a particular word, the marker will remain over that word even if the word's location in - * the buffer changes. - */ - markScreenRange(range: TextBuffer.RangeCompatible, properties?: { maintainHistory?: - boolean, reversed?: boolean, invalidate?: "never"|"surround"|"overlap"|"inside" - |"touch" }): TextBuffer.DisplayMarker; - - /** Create a marker on the default marker layer with the given buffer position and no tail. - * To group multiple markers together in their own private layer, see ::addMarkerLayer. - */ - markBufferPosition(bufferPosition: TextBuffer.PointCompatible, options?: - { invalidate?: "never"|"surround"|"overlap"|"inside"|"touch" }): - TextBuffer.DisplayMarker; - - /** Create a marker on the default marker layer with the given screen position and no tail. - * To group multiple markers together in their own private layer, see ::addMarkerLayer. - */ - markScreenPosition(screenPosition: TextBuffer.PointCompatible, options?: - { invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", clipDirection?: - "backward"|"forward"|"closest" }): TextBuffer.DisplayMarker; - - /** Find all DisplayMarkers on the default marker layer that match the given properties. - * - * This method finds markers based on the given properties. Markers can be associated - * with custom properties that will be compared with basic equality. In addition, there - * are several special properties that will be compared with the range of the markers - * rather than their properties. - */ - findMarkers(properties: TextBuffer.Options.FindDisplayMarker): TextBuffer.DisplayMarker[]; - - /** Create a marker layer to group related markers. */ - addMarkerLayer(options?: { - maintainHistory?: boolean, - persistent?: boolean, - }): TextBuffer.DisplayMarkerLayer; - - /** Get a DisplayMarkerLayer by id. */ - getMarkerLayer(id: number): TextBuffer.DisplayMarkerLayer|undefined; - - /** Get the default DisplayMarkerLayer. - * All marker APIs not tied to an explicit layer interact with this default layer. - */ - getDefaultMarkerLayer(): TextBuffer.DisplayMarkerLayer; - - /** Get the DisplayMarker on the default layer for the given marker id. */ - getMarker(id: number): TextBuffer.DisplayMarker; - - /** Get all DisplayMarkers on the default marker layer. Consider using ::findMarkers. */ - getMarkers(): TextBuffer.DisplayMarker[]; - - /** Get the number of markers in the default marker layer. */ - getMarkerCount(): number; - - // Cursors - /** Get the position of the most recently added cursor in buffer coordinates. */ - getCursorBufferPosition(): TextBuffer.Point; - - /** Get the position of all the cursor positions in buffer coordinates. */ - getCursorBufferPositions(): TextBuffer.Point[]; - - /** Move the cursor to the given position in buffer coordinates. - * If there are multiple cursors, they will be consolidated to a single cursor. - */ - setCursorBufferPosition(position: TextBuffer.PointCompatible, options?: - { autoscroll?: boolean }): void; - - /** Get a Cursor at given screen coordinates Point. */ - getCursorAtScreenPosition(position: TextBuffer.PointCompatible): Cursor|undefined; - - /** Get the position of the most recently added cursor in screen coordinates. */ - getCursorScreenPosition(): TextBuffer.Point; - - /** Get the position of all the cursor positions in screen coordinates. */ - getCursorScreenPositions(): TextBuffer.Point[]; - - /** Move the cursor to the given position in screen coordinates. - * If there are multiple cursors, they will be consolidated to a single cursor. - */ - setCursorScreenPosition(position: TextBuffer.PointCompatible, options?: - { autoscroll?: boolean }): void; - - /** Add a cursor at the given position in buffer coordinates. */ - addCursorAtBufferPosition(bufferPosition: TextBuffer.PointCompatible): Cursor; - - /** Add a cursor at the position in screen coordinates. */ - addCursorAtScreenPosition(screenPosition: TextBuffer.PointCompatible): Cursor; - - /** Returns a boolean indicating whether or not there are multiple cursors. */ - hasMultipleCursors(): boolean; - - /** Move every cursor up one row in screen coordinates. */ - moveUp(lineCount?: number): void; - - /** Move every cursor down one row in screen coordinates. */ - moveDown(lineCount?: number): void; - - /** Move every cursor left one column. */ - moveLeft(columnCount?: number): void; - - /** Move every cursor right one column. */ - moveRight(columnCount?: number): void; - - /** Move every cursor to the beginning of its line in buffer coordinates. */ - moveToBeginningOfLine(): void; - - /** Move every cursor to the beginning of its line in screen coordinates. */ - moveToBeginningOfScreenLine(): void; - - /** Move every cursor to the first non-whitespace character of its line. */ - moveToFirstCharacterOfLine(): void; - - /** Move every cursor to the end of its line in buffer coordinates. */ - moveToEndOfLine(): void; - - /** Move every cursor to the end of its line in screen coordinates. */ - moveToEndOfScreenLine(): void; - - /** Move every cursor to the beginning of its surrounding word. */ - moveToBeginningOfWord(): void; - - /** Move every cursor to the end of its surrounding word. */ - moveToEndOfWord(): void; - - /** Move every cursor to the top of the buffer. - * If there are multiple cursors, they will be merged into a single cursor. - */ - moveToTop(): void; - - /** Move every cursor to the bottom of the buffer. - * If there are multiple cursors, they will be merged into a single cursor. - */ - moveToBottom(): void; - - /** Move every cursor to the beginning of the next word. */ - moveToBeginningOfNextWord(): void; - - /** Move every cursor to the previous word boundary. */ - moveToPreviousWordBoundary(): void; - - /** Move every cursor to the next word boundary. */ - moveToNextWordBoundary(): void; - - /** Move every cursor to the previous subword boundary. */ - moveToPreviousSubwordBoundary(): void; - - /** Move every cursor to the next subword boundary. */ - moveToNextSubwordBoundary(): void; - - /** Move every cursor to the beginning of the next paragraph. */ - moveToBeginningOfNextParagraph(): void; - - /** Move every cursor to the beginning of the previous paragraph. */ - moveToBeginningOfPreviousParagraph(): void; - - /** Returns the most recently added Cursor. */ - getLastCursor(): Cursor; - - /** Returns the word surrounding the most recently added cursor. */ - getWordUnderCursor(options?: { - wordRegex?: RegExp, - includeNonWordCharacters?: boolean, - allowPrevious?: boolean, - }): string; - - /** Get an Array of all Cursors. */ - getCursors(): Cursor[]; - - /** Get all Cursorss, ordered by their position in the buffer instead of the - * order in which they were added. - */ - getCursorsOrderedByBufferPosition(): Cursor[]; - - // Selections - /** Get the selected text of the most recently added selection. */ - getSelectedText(): string; - - /** Get the Range of the most recently added selection in buffer coordinates. */ - getSelectedBufferRange(): TextBuffer.Range; - - /** Get the Ranges of all selections in buffer coordinates. - * The ranges are sorted by when the selections were added. Most recent at the end. - */ - getSelectedBufferRanges(): TextBuffer.Range[]; - - /** Set the selected range in buffer coordinates. If there are multiple selections, - * they are reduced to a single selection with the given range. - */ - setSelectedBufferRange(bufferRange: TextBuffer.RangeCompatible, options?: - { reversed?: boolean, preserveFolds?: boolean}): void; - - /** Set the selected ranges in buffer coordinates. If there are multiple selections, - * they are replaced by new selections with the given ranges. - */ - setSelectedBufferRanges(bufferRanges: ReadonlyArray, - options?: { reversed?: boolean, preserveFolds?: boolean}): void; - - /** Get the Range of the most recently added selection in screen coordinates. */ - getSelectedScreenRange(): TextBuffer.Range; - - /** Get the Ranges of all selections in screen coordinates. - * The ranges are sorted by when the selections were added. Most recent at the end. - */ - getSelectedScreenRanges(): TextBuffer.Range[]; - - /** Set the selected range in screen coordinates. If there are multiple selections, - * they are reduced to a single selection with the given range. - */ - setSelectedScreenRange(screenRange: TextBuffer.RangeCompatible, options?: - { reversed?: boolean }): void; - - /** Set the selected ranges in screen coordinates. If there are multiple selections, - * they are replaced by new selections with the given ranges. - */ - setSelectedScreenRanges(screenRanges: ReadonlyArray, - options?: { reversed?: boolean }): void; - - /** Add a selection for the given range in buffer coordinates. */ - addSelectionForBufferRange(bufferRange: TextBuffer.RangeCompatible, options?: - { reversed?: boolean, preserveFolds?: boolean }): Selection; - - /** Add a selection for the given range in screen coordinates. */ - addSelectionForScreenRange(screenRange: TextBuffer.RangeCompatible, options?: - { reversed?: boolean, preserveFolds?: boolean }): Selection; - - /** Select from the current cursor position to the given position in buffer coordinates. - * This method may merge selections that end up intersecting. - */ - selectToBufferPosition(position: TextBuffer.PointCompatible): void; - - /** Select from the current cursor position to the given position in screen coordinates. - * This method may merge selections that end up intersecting. - */ - selectToScreenPosition(position: TextBuffer.PointCompatible): void; - - /** Move the cursor of each selection one character upward while preserving the - * selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectUp(rowCount?: number): void; - - /** Move the cursor of each selection one character downward while preserving - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectDown(rowCount?: number): void; - - /** Move the cursor of each selection one character leftward while preserving - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectLeft(columnCount?: number): void; - - /** Move the cursor of each selection one character rightward while preserving - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectRight(columnCount?: number): void; - - /** Select from the top of the buffer to the end of the last selection in the buffer. - * This method merges multiple selections into a single selection. - */ - selectToTop(): void; - - /** Selects from the top of the first selection in the buffer to the end of the buffer. - * This method merges multiple selections into a single selection. - */ - selectToBottom(): void; - - /** Select all text in the buffer. - * This method merges multiple selections into a single selection. - */ - selectAll(): void; - - /** Move the cursor of each selection to the beginning of its line while preserving - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToBeginningOfLine(): void; - - /** Move the cursor of each selection to the first non-whitespace character of its - * line while preserving the selection's tail position. If the cursor is already - * on the first character of the line, move it to the beginning of the line. - * This method may merge selections that end up intersecting. - */ - selectToFirstCharacterOfLine(): void; - - /** Move the cursor of each selection to the end of its line while preserving the - * selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToEndOfLine(): void; - - /** Expand selections to the beginning of their containing word. - * Operates on all selections. Moves the cursor to the beginning of the containing - * word while preserving the selection's tail position. - */ - selectToBeginningOfWord(): void; - - /** Expand selections to the end of their containing word. - * Operates on all selections. Moves the cursor to the end of the containing word - * while preserving the selection's tail position. - */ - selectToEndOfWord(): void; - - /** For each cursor, select the containing line. - * This method merges selections on successive lines. - */ - selectLinesContainingCursors(): void; - - /** Select the word surrounding each cursor. */ - selectWordsContainingCursors(): void; - - /** For each selection, move its cursor to the preceding subword boundary while - * maintaining the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToPreviousSubwordBoundary(): void; - - /** For each selection, move its cursor to the next subword boundary while maintaining - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToNextSubwordBoundary(): void; - - /** For each selection, move its cursor to the preceding word boundary while - * maintaining the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToPreviousWordBoundary(): void; - - /** For each selection, move its cursor to the next word boundary while maintaining - * the selection's tail position. - * This method may merge selections that end up intersecting. - */ - selectToNextWordBoundary(): void; - - /** Expand selections to the beginning of the next word. - * Operates on all selections. Moves the cursor to the beginning of the next word - * while preserving the selection's tail position. - */ - selectToBeginningOfNextWord(): void; - - /** Expand selections to the beginning of the next paragraph. - * Operates on all selections. Moves the cursor to the beginning of the next - * paragraph while preserving the selection's tail position. - */ - selectToBeginningOfNextParagraph(): void; - - /** Expand selections to the beginning of the next paragraph. - * Operates on all selections. Moves the cursor to the beginning of the next - * paragraph while preserving the selection's tail position. - */ - selectToBeginningOfPreviousParagraph(): void; - - /** Select the range of the given marker if it is valid. */ - selectMarker(marker: TextBuffer.DisplayMarker): TextBuffer.Range|undefined; - - /** Get the most recently added Selection. */ - getLastSelection(): Selection; - - /** Get current Selections. */ - getSelections(): Selection[]; - - /** Get all Selections, ordered by their position in the buffer instead of the - * order in which they were added. - */ - getSelectionsOrderedByBufferPosition(): Selection[]; - - // NOTE: this calls into Selection::intersectsBufferRange, which itself calls - // into Range::intersectsWith. Range::intersectsWith is one of the few functions - // which does NOT take a range-compatible array. - /** Determine if a given range in buffer coordinates intersects a selection. */ - selectionIntersectsBufferRange(bufferRange: TextBuffer.RangeLike): boolean; - - // Searching and Replacing - /** Scan regular expression matches in the entire buffer, calling the given - * iterator function on each match. - * - * ::scan functions as the replace method as well via the replace. - */ - scan(regex: RegExp, options: TextBuffer.Options.ScanContext, iterator: (params: - TextBuffer.Structures.ContextualBufferScanResult) => void): void; - /** Scan regular expression matches in the entire buffer, calling the given - * iterator function on each match. - * - * ::scan functions as the replace method as well via the replace. - */ - scan(regex: RegExp, iterator: (params: TextBuffer.Structures.BufferScanResult) => void): - void; - - /** Scan regular expression matches in a given range, calling the given iterator. - * function on each match. - */ - scanInBufferRange(regex: RegExp, range: TextBuffer.RangeCompatible, iterator: - (params: TextBuffer.Structures.BufferScanResult) => void): void; - - /** Scan regular expression matches in a given range in reverse order, calling the - * given iterator function on each match. - */ - backwardsScanInBufferRange(regex: RegExp, range: TextBuffer.RangeCompatible, - iterator: (params: TextBuffer.Structures.BufferScanResult) => void): void; - - // Tab Behavior - /** Returns a boolean indicating whether softTabs are enabled for this editor. */ - getSoftTabs(): boolean; - - /** Enable or disable soft tabs for this editor. */ - setSoftTabs(softTabs: boolean): void; - - /** Toggle soft tabs for this editor. */ - toggleSoftTabs(): boolean; - - /** Get the on-screen length of tab characters. */ - getTabLength(): number; - - /** Set the on-screen length of tab characters. Setting this to a number will - * override the editor.tabLength setting. - */ - setTabLength(tabLength: number): void; - - /** Determine if the buffer uses hard or soft tabs. */ - usesSoftTabs(): boolean|undefined; - - /** Get the text representing a single level of indent. - * If soft tabs are enabled, the text is composed of N spaces, where N is the - * tab length. Otherwise the text is a tab character (\t). - */ - getTabText(): string; - - // Soft Wrap Behavior - /** Determine whether lines in this editor are soft-wrapped. */ - isSoftWrapped(): boolean; - - /** Enable or disable soft wrapping for this editor. */ - setSoftWrapped(softWrapped: boolean): boolean; - - /** Toggle soft wrapping for this editor. */ - toggleSoftWrapped(): boolean; - - /** Gets the column at which column will soft wrap. */ - getSoftWrapColumn(): number; - - // Indentation - /** Get the indentation level of the given buffer row. - * Determines how deeply the given row is indented based on the soft tabs and tab - * length settings of this editor. Note that if soft tabs are enabled and the tab - * length is 2, a row with 4 leading spaces would have an indentation level of 2. - */ - indentationForBufferRow(bufferRow: number): number; - - /** Set the indentation level for the given buffer row. - * Inserts or removes hard tabs or spaces based on the soft tabs and tab length settings - * of this editor in order to bring it to the given indentation level. Note that if soft - * tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an - * indentation level of 2. - */ - setIndentationForBufferRow(bufferRow: number, newLevel: number, options?: - { preserveLeadingWhitespace?: boolean }): void; - - /** Indent rows intersecting selections by one level. */ - indentSelectedRows(): void; - - /** Outdent rows intersecting selections by one level. */ - outdentSelectedRows(): void; - - /** Get the indentation level of the given line of text. - * Determines how deeply the given line is indented based on the soft tabs and tab length - * settings of this editor. Note that if soft tabs are enabled and the tab length is 2, - * a row with 4 leading spaces would have an indentation level of 2. - */ - indentLevelForLine(line: string): number; - - /** Indent rows intersecting selections based on the grammar's suggested indent level. */ - autoIndentSelectedRows(): void; - - // Grammars - /** Get the current Grammar of this editor. */ - getGrammar(): FirstMate.Grammar; - - /** Set the current Grammar of this editor. - * Assigning a grammar will cause the editor to re-tokenize based on the new grammar. - */ - setGrammar(grammar: FirstMate.Grammar): void; - - // Managing Syntax Scopes - /** Returns a ScopeDescriptor that includes this editor's language. - * e.g. [".source.ruby"], or [".source.coffee"]. - */ - getRootScopeDescriptor(): ScopeDescriptor; - - /** Get the syntactic scopeDescriptor for the given position in buffer coordinates. */ - scopeDescriptorForBufferPosition(bufferPosition: TextBuffer.PointCompatible): - ScopeDescriptor; - - /** Get the range in buffer coordinates of all tokens surrounding the cursor - * that match the given scope selector. - */ - bufferRangeForScopeAtCursor(scopeSelector: string): TextBuffer.Range; - - /** Determine if the given row is entirely a comment. */ - isBufferRowCommented(bufferRow: number): boolean; - - // Clipboard Operations - /** For each selection, copy the selected text. */ - copySelectedText(): void; - - /** For each selection, cut the selected text. */ - cutSelectedText(): void; - - /** For each selection, replace the selected text with the contents of the clipboard. - * If the clipboard contains the same number of selections as the current editor, - * each selection will be replaced with the content of the corresponding clipboard - * selection text. - */ - pasteText(options?: Options.TextInsertion): void; - - /** For each selection, if the selection is empty, cut all characters of the - * containing screen line following the cursor. Otherwise cut the selected text. - */ - cutToEndOfLine(): void; - - /** For each selection, if the selection is empty, cut all characters of the - * containing buffer line following the cursor. Otherwise cut the selected text. - */ - cutToEndOfBufferLine(): void; - - // Folds - /** Fold the most recent cursor's row based on its indentation level. - * The fold will extend from the nearest preceding line with a lower indentation - * level up to the nearest following row with a lower indentation level. - */ - foldCurrentRow(): void; - - /** Unfold the most recent cursor's row by one level. */ - unfoldCurrentRow(): void; - - /** Fold the given row in buffer coordinates based on its indentation level. - * If the given row is foldable, the fold will begin there. Otherwise, it will - * begin at the first foldable row preceding the given row. - */ - foldBufferRow(bufferRow: number): void; - - /** Unfold all folds containing the given row in buffer coordinates. */ - unfoldBufferRow(bufferRow: number): void; - - /** For each selection, fold the rows it intersects. */ - foldSelectedLines(): void; - - /** Fold all foldable lines. */ - foldAll(): void; - - /** Unfold all existing folds. */ - unfoldAll(): void; - - /** Fold all foldable lines at the given indent level. */ - foldAllAtIndentLevel(level: number): void; - - /** Determine whether the given row in buffer coordinates is foldable. - * A foldable row is a row that starts a row range that can be folded. - */ - isFoldableAtBufferRow(bufferRow: number): boolean; - - /** Determine whether the given row in screen coordinates is foldable. - * A foldable row is a row that starts a row range that can be folded. - */ - isFoldableAtScreenRow(bufferRow: number): boolean; - - /** Fold the given buffer row if it isn't currently folded, and unfold it otherwise. */ - toggleFoldAtBufferRow(bufferRow: number): void; - - /** Determine whether the most recently added cursor's row is folded. */ - isFoldedAtCursorRow(): boolean; - - /** Determine whether the given row in buffer coordinates is folded. */ - isFoldedAtBufferRow(bufferRow: number): boolean; - - /** Determine whether the given row in screen coordinates is folded. */ - isFoldedAtScreenRow(screenRow: number): boolean; - - // Gutters - /** Add a custom Gutter. */ - addGutter(options: { - name: string, - priority?: number, - visible?: boolean, - }): Gutter; - - /** Get this editor's gutters. */ - getGutters(): Gutter[]; - - /** Get the gutter with the given name. */ - gutterWithName(name: string): Gutter|null; - - // Scrolling the TextEditor - /** Scroll the editor to reveal the most recently added cursor if it is off-screen. */ - scrollToCursorPosition(options?: { center?: boolean }): void; - - /** Scrolls the editor to the given buffer position. */ - scrollToBufferPosition(bufferPosition: TextBuffer.PointCompatible, options?: - { center?: boolean }): void; - - /** Scrolls the editor to the given screen position. */ - scrollToScreenPosition(screenPosition: TextBuffer.PointCompatible, options?: - { center?: boolean }): void; - - // TextEditor Rendering - /** Retrieves the rendered line height in pixels. */ - getLineHeightInPixels(): number; - - /** Retrieves the greyed out placeholder of a mini editor. */ - getPlaceholderText(): string; - - /** Set the greyed out placeholder of a mini editor. Placeholder text will be - * displayed when the editor has no content. - */ - setPlaceholderText(placeholderText: string): void; - } - - /** The static side to the TextEditor class. */ - interface TextEditorStatic { - // NOTE: undocumented within the public API. Don't go down the rabbit hole. - new (options?: object): TextEditor; - } - - /** Experimental: This global registry tracks registered TextEditors. */ - interface TextEditorRegistry { - // Managing Text Editors - /** Remove all editors from the registry. */ - clear(): void; - - /** Register a TextEditor. */ - add(editor: TextEditor): EventKit.Disposable; - - /** Remove the given TextEditor from the registry. */ - remove(editor: TextEditor): boolean; - - /** Keep a TextEditor's configuration in sync with Atom's settings. */ - maintainConfig(editor: TextEditor): EventKit.Disposable; - - /** Set a TextEditor's grammar based on its path and content, and continue - * to update its grammar as gramamrs are added or updated, or the editor's - * file path changes. - */ - maintainGrammar(editor: TextEditor): EventKit.Disposable; - - /** Force a TextEditor to use a different grammar than the one that would - * otherwise be selected for it. - */ - setGrammarOverride(editor: TextEditor, scopeName: string): void; - - /** Retrieve the grammar scope name that has been set as a grammar override - * for the given TextEditor. - */ - getGrammarOverride(editor: TextEditor): string|null; - - /** Remove any grammar override that has been set for the given TextEditor. */ - clearGrammarOverride(editor: TextEditor): void; - - // Event Subscription - /** Invoke the given callback with all the current and future registered TextEditors. */ - observe(callback: (editor: TextEditor) => void): EventKit.Disposable; - } - - /** Handles loading and activating available themes. */ - interface ThemeManager { - // Event Subscription - /** Invoke callback when style sheet changes associated with updating the - * list of active themes have completed. - */ - onDidChangeActiveThemes(callback: () => void): EventKit.Disposable; - - // Accessing Loaded Themes - /** Returns an Array of strings of all the loaded theme names. */ - getLoadedThemeNames(): string[]|undefined; - - /** Returns an Array of all the loaded themes. */ - getLoadedThemes(): Package[]|undefined; - - // Accessing Active Themes - /** Returns an Array of strings all the active theme names. */ - getActiveThemeNames(): string[]|undefined; - - /** Returns an Array of all the active themes. */ - getActiveThemes(): Package[]|undefined; - - // Managing Enabled Themes - /** Get the enabled theme names from the config. */ - getEnabledThemeNames(): string[]; - } - - /** Associates tooltips with HTML elements or selectors. */ - interface TooltipManager { - /** Add a tooltip to the given element. */ - add(target: JQuery|HTMLElement, options: { - title?: string, - html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), - trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, - keyBindingCommand?: string, - keyBindingTarget?: HTMLElement - } | { - title?: string|(() => string), - html?: boolean, - item?: HTMLElement|{ element: HTMLElement }, - class?: string, - placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), - trigger?: "click"|"hover"|"focus"|"manual", - delay?: { show: number, hide: number }, - }): EventKit.Disposable; - - /** Find the tooltips that have been applied to the given element. */ - findTooltips(target: HTMLElement): Structures.Tooltip[]; - } - - /** ViewRegistry handles the association between model and view types in Atom. - * We call this association a View Provider. As in, for a given model, this class - * can provide a view via ::getView, as long as the model/view association was - * registered via ::addViewProvider. - */ - interface ViewRegistry { - /** Add a provider that will be used to construct views in the workspace's view - * layer based on model objects in its model layer. - */ - addViewProvider(createView: (model: object) => HTMLElement|undefined): - EventKit.Disposable; - /** Add a provider that will be used to construct views in the workspace's view - * layer based on model objects in its model layer. - */ - // tslint:disable-next-line:no-any - addViewProvider(modelConstructor: { new (...args: any[]): T }, createView: - (instance: T) => HTMLElement|undefined): EventKit.Disposable; - - /** Get the view associated with an object in the workspace. */ - getView(obj: object): HTMLElement; - } - - /** Represents the state of the user interface for the entire window. */ - interface Workspace { - // Event Subscription - /** Invoke the given callback with all current and future text editors in - * the workspace. - */ - observeTextEditors(callback: (editor: TextEditor) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes items in the - * workspace. - */ - observePaneItems(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item changes. */ - onDidChangeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item stops changing. */ - onDidStopChangingActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when a text editor becomes the active text editor and - * when there is no longer an active text editor. - */ - onDidChangeActiveTextEditor(callback: (editor?: TextEditor) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane item and with all - * future active pane items in the workspace. - */ - observeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active text editor (if any), with all - * future active text editors, and when there is no longer an active text editor. - */ - observeActiveTextEditor(callback: (editor?: TextEditor) => void): EventKit.Disposable; - - /** Invoke the given callback whenever an item is opened. Unlike ::onDidAddPaneItem, - * observers will be notified for items that are already present in the workspace - * when they are reopened. - */ - onDidOpen(callback: (event: Events.PaneItemOpened) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is added to the workspace. */ - onDidAddPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback before a pane is destroyed in the workspace. */ - onWillDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is destroyed in the workspace. */ - onDidDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes in the workspace. */ - observePanes(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane changes. */ - onDidChangeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane and when the - * active pane changes. - */ - observeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane item is added to the workspace. */ - onDidAddPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is about to be destroyed, - * before the user is prompted to save it. - */ - onWillDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is destroyed. */ - onDidDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a text editor is added to the workspace. */ - onDidAddTextEditor(callback: (event: Events.TextEditorObserved) => void): - EventKit.Disposable; - - // Opening - /** Opens the given URI in Atom asynchronously. If the URI is already open, - * the existing item for that URI will be activated. If no URI is given, or - * no registered opener can open the URI, a new empty TextEditor will be created. - */ - open(uri: string, options?: { - initialLine?: number, - initialColumn?: number, - split?: "left"|"right"|"up"|"down", - activatePane?: boolean, - activateItem?: boolean, - pending?: boolean, - searchAllPanes?: boolean, - location?: "left"|"right"|"bottom"|"center", - }): Promise; - /** Opens the given URI in Atom asynchronously. If the URI is already open, - * the existing item for that URI will be activated. If no URI is given, or - * no registered opener can open the URI, a new empty TextEditor will be created. - */ - open(): Promise; - - /** Search the workspace for items matching the given URI and hide them. - * Returns a boolean indicating whether any items were found (and hidden). - */ - hide(itemOrURI: object|string): boolean; - - /** Search the workspace for items matching the given URI. If any are found, - * hide them. Otherwise, open the URL. - * Returns a Promise that resolves when the item is shown or hidden. - */ - toggle(itemOrURI: object|string): Promise; - - /** Creates a new item that corresponds to the provided URI. - * If no URI is given, or no registered opener can open the URI, a new empty TextEditor - * will be created. - */ - createItemForURI(uri: string): Promise; - - /** Returns a boolean that is true if object is a TextEditor. */ - isTextEditor(object: object): boolean; - - /** Asynchronously reopens the last-closed item's URI if it hasn't already - * been reopened. - */ - reopenItem(): Promise; - - /** Register an opener for a URI. */ - addOpener(opener: (uri: string) => HTMLElement|{ getTitle(): string }|undefined): - EventKit.Disposable; - - /** Create a new text editor. */ - buildTextEditor(params: object): TextEditor; - - // Pane Items - /** Get all pane items in the workspace. */ - getPaneItems(): object[]; - - /** Get the active Pane's active item. */ - getActivePaneItem(): object; - - /** Get all text editors in the workspace. */ - getTextEditors(): TextEditor[]; - - /** Get the workspace center's active item if it is a TextEditor. */ - getActiveTextEditor(): TextEditor|undefined; - - // Panes - /** Get the most recently focused pane container. */ - getActivePaneContainer(): Dock|WorkspaceCenter; - - /** Get all panes in the workspace. */ - getPanes(): Pane[]; - - /** Get the active Pane. */ - getActivePane(): Pane; - - /** Make the next pane active. */ - activateNextPane(): boolean; - - /** Make the previous pane active. */ - activatePreviousPane(): boolean; - - /** Get the first pane container that contains an item with the given URI. */ - paneContainerForURI(uri: string): Dock|WorkspaceCenter|undefined; - - /** Get the first pane container that contains the given item. */ - paneContainerForItem(item: object): Dock|WorkspaceCenter|undefined; - - /** Get the first Pane with an item for the given URI. */ - paneForURI(uri: string): Pane|undefined; - - /** Get the Pane containing the given item. */ - paneForItem(item: object): Pane|undefined; - - // Pane Locations - /** Get the WorkspaceCenter at the center of the editor window. */ - getCenter(): WorkspaceCenter; - - /** Get the Dock to the left of the editor window. */ - getLeftDock(): Dock; - - /** Get the Dock to the right of the editor window. */ - getRightDock(): Dock; - - /** Get the Dock below the editor window. */ - getBottomDock(): Dock; - - /** Returns all Pane containers. */ - getPaneContainers(): [WorkspaceCenter, Dock, Dock, Dock]; - - // Panels - /** Get an Array of all the panel items at the bottom of the editor window. */ - getBottomPanels(): Panel[]; - - /** Adds a panel item to the bottom of the editor window. */ - addBottomPanel(options: { - item: object, - visible?: boolean, - priority?: number, - }): Panel; - - /** Get an Array of all the panel items to the left of the editor window. */ - getLeftPanels(): Panel[]; - - /** Adds a panel item to the left of the editor window. */ - addLeftPanel(options: { - item: object, - visible?: boolean, - priority?: number, - }): Panel; - - /** Get an Array of all the panel items to the right of the editor window. */ - getRightPanels(): Panel[]; - - /** Adds a panel item to the right of the editor window. */ - addRightPanel(options: { - item: object, - visible?: boolean, - priority?: number, - }): Panel; - - /** Get an Array of all the panel items at the top of the editor window. */ - getTopPanels(): Panel[]; - - /** Adds a panel item to the top of the editor window above the tabs. */ - addTopPanel(options: { - item: object, - visible?: boolean, - priority?: number - }): Panel; - - /** Get an Array of all the panel items in the header. */ - getHeaderPanels(): Panel[]; - - /** Adds a panel item to the header. */ - addHeaderPanel(options: { - item: object, - visible?: boolean, - priority?: number, - }): Panel; - - /** Get an Array of all the panel items in the footer. */ - getFooterPanels(): Panel[]; - - /** Adds a panel item to the footer. */ - addFooterPanel(options: { - item: object, - visible?: boolean, - priority?: number, - }): Panel; - - /** Get an Array of all the modal panel items. */ - getModalPanels(): Panel[]; - - /** Adds a panel item as a modal dialog. */ - addModalPanel(options: { - item: object, - visible?: boolean, - priority?: number, - autoFocus?: boolean, - }): Panel; - - /** Returns the Panel associated with the given item or null when the item - * has no panel. - */ - panelForItem(item: object): Panel|null; - - // Searching and Replacing - /** Performs a search across all files in the workspace. */ - scan(regex: RegExp, iterator: (result: Structures.ScandalResult) => void): - Structures.CancellablePromise; - /** Performs a search across all files in the workspace. */ - scan(regex: RegExp, options: Options.WorkspaceScan, iterator: - (result: Structures.ScandalResult) => void): - Structures.CancellablePromise; - - /** Performs a replace across all the specified files in the project. */ - replace(regex: RegExp, replacementText: string, filePaths: ReadonlyArray, - iterator: (result: { filePath: string|undefined, replacements: number }) => void): - Promise; - } - - // https://github.com/atom/atom/blob/master/src/workspace-center.js - /** The central container for the editor window capable of holding items. */ - interface WorkspaceCenter { - // Event Subscription - /** Invoke the given callback with all current and future text editors in the - * workspace center. - */ - observeTextEditors(callback: (editor: TextEditor) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes items in the - * workspace center. - */ - observePaneItems(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item changes. */ - onDidChangeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane item stops changing. */ - onDidStopChangingActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane item and with all future - * active pane items in the workspace center. - */ - observeActivePaneItem(callback: (item: object) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is added to the workspace center. */ - onDidAddPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback before a pane is destroyed in the workspace center. */ - onWillDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane is destroyed in the workspace center. */ - onDidDestroyPane(callback: (event: { pane: Pane }) => void): EventKit.Disposable; - - /** Invoke the given callback with all current and future panes in the workspace center. */ - observePanes(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when the active pane changes. */ - onDidChangeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback with the current active pane and when the active pane - * changes. - */ - observeActivePane(callback: (pane: Pane) => void): EventKit.Disposable; - - /** Invoke the given callback when a pane item is added to the workspace center. */ - onDidAddPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is about to be destroyed, before the user - * is prompted to save it. - */ - onWillDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a pane item is destroyed. */ - onDidDestroyPaneItem(callback: (event: Events.PaneItemObserved) => void): - EventKit.Disposable; - - /** Invoke the given callback when a text editor is added to the workspace center. */ - onDidAddTextEditor(callback: (event: Events.TextEditorObserved) => void): - EventKit.Disposable; - - // Pane Items - /** Get all pane items in the workspace center. */ - getPaneItems(): object[]; - - /** Get the active Pane's active item. */ - getActivePaneItem(): object|undefined; - - /** Get all text editors in the workspace center. */ - getTextEditors(): TextEditor[]; - - /** Get the active item if it is an TextEditor. */ - getActiveTextEditor(): TextEditor|undefined; - - /** Save all pane items. */ - saveAll(): void; - - // Panes - /** Get all panes in the workspace center. */ - getPanes(): Pane[]; - - /** Get the active Pane. */ - getActivePane(): Pane; - - /** Make the next pane active. */ - activateNextPane(): void; - - /** Make the previous pane active. */ - activatePreviousPane(): void; - - /** Retrieve the Pane associated with the given URI. */ - paneForURI(uri: string): Pane|undefined; - - /** Retrieve the Pane associated with the given item. */ - paneForItem(item: object): Pane|undefined; - - /** Destroy (close) the active pane. */ - destroyActivePane(): void; - } - } - - /** An amalgamation of all types used within the public Atom API. */ - namespace Atom { - /** The event objects that are passed into the callbacks which the user provides to - * specific API calls. - */ - namespace Events { - // Atom Core - type CursorPositionChanged = AtomCore.Events.CursorPositionChanged; - type DecorationPropsChanged = AtomCore.Events.DecorationPropsChanged; - type EditorChanged = AtomCore.Events.EditorChanged; - type ExceptionThrown = AtomCore.Events.ExceptionThrown; - type FilesystemChange = AtomCore.Events.FilesystemChange; - type PaneItemMoved = AtomCore.Events.PaneItemMoved; - type PaneItemObserved = AtomCore.Events.PaneItemObserved; - type PaneItemOpened = AtomCore.Events.PaneItemOpened; - type PaneListItemShifted = AtomCore.Events.PaneListItemShifted; - type PreventableExceptionThrown = AtomCore.Events.PreventableExceptionThrown; - type RepoStatusChanged = AtomCore.Events.RepoStatusChanged; - type SelectionChanged = AtomCore.Events.SelectionChanged; - type StyleElementObserved = AtomCore.Events.StyleElementObserved; - type TextEditorObserved = AtomCore.Events.TextEditorObserved; - - // Atom Keymap - type CommandEvent = AtomKeymap.Events.CommandEvent; - type FullKeybindingMatch = AtomKeymap.Events.FullKeybindingMatch; - type PartialKeybindingMatch = AtomKeymap.Events.PartialKeybindingMatch; - type FailedKeybindingMatch = AtomKeymap.Events.FailedKeybindingMatch; - type FailedKeymapFileRead = AtomKeymap.Events.FailedKeymapFileRead; - type KeymapLoaded = AtomKeymap.Events.KeymapLoaded; - type AddedKeystrokeResolver = AtomKeymap.Events.AddedKeystrokeResolver; - - // Path Watcher - type PathWatchErrorThrown = PathWatcher.Events.PathWatchErrorThrown; - // NOTE: WatchedFilePathChangedEvent isn't used. - - // Text Buffer - type BufferWatchError = TextBuffer.Events.BufferWatchError; - type FileSaved = TextBuffer.Events.FileSaved; - type MarkerChanged = TextBuffer.Events.MarkerChanged; - type DisplayMarkerChanged = TextBuffer.Events.DisplayMarkerChanged; - type BufferChanging = TextBuffer.Events.BufferChanging; - type BufferChanged = TextBuffer.Events.BufferChanged; - type BufferStoppedChanging = TextBuffer.Events.BufferStoppedChanging; - } - - /** The option objects that the user is expected to fill out and provide to - * specific API calls. - */ - namespace Options { - // Atom Core - type BuildEnvironment = AtomCore.Options.BuildEnvironment; - type ContextMenu = AtomCore.Options.ContextMenu; - type DecorationLayerProps = AtomCore.Options.DecorationLayerProps; - type DecorationProps = AtomCore.Options.DecorationProps; - type ErrorNotification = AtomCore.Options.ErrorNotification; - type Menu = AtomCore.Options.Menu; - type Notification = AtomCore.Options.Notification; - type NodeProcess = AtomCore.Options.NodeProcess; - type Process = AtomCore.Options.Process; - type SharedDecorationProps = AtomCore.Options.SharedDecorationProps; - type SpawnProcess = AtomCore.Options.SpawnProcess; - type TextInsertion = AtomCore.Options.TextInsertion; - type Tooltip = AtomCore.Options.Tooltip; - type WorkspaceScan = AtomCore.Options.WorkspaceScan; - - // Atom Keymap - type BuildKeyEvent = AtomKeymap.Options.BuildKeyEvent; - - // First Mate - type Grammar = FirstMate.Options.Grammar; - - // Text Buffer - type BufferLoad = TextBuffer.Options.BufferLoad; - type FindMarker = TextBuffer.Options.FindMarker; - type FindDisplayMarker = TextBuffer.Options.FindDisplayMarker; - type CopyMarker = TextBuffer.Options.CopyMarker; - type ScanContext = TextBuffer.Options.ScanContext; - } - - /** The structures that are passed to the user by Atom following specific API calls. */ - namespace Structures { - // Atom Core - type CancellablePromise = AtomCore.Structures.CancellablePromise; - type HistoryProject = AtomCore.Structures.HistoryProject; - type ScandalResult = AtomCore.Structures.ScandalResult; - type TestRunnerArgs = AtomCore.Structures.TestRunnerArgs; - type Tooltip = AtomCore.Structures.Tooltip; - type WindowLoadSettings = AtomCore.Structures.WindowLoadSettings; - - // First Mate - type GrammarToken = FirstMate.Structures.GrammarToken; - type TokenizeLineResult = FirstMate.Structures.TokenizeLineResult; - type GrammarRule = FirstMate.Structures.GrammarRule; - - // Text Buffer - type TextChange = TextBuffer.Structures.TextChange; - type BufferScanResult = TextBuffer.Structures.BufferScanResult; - type ContextualBufferScanResult = TextBuffer.Structures.ContextualBufferScanResult; - } - - // Atom Core ========================================================== - type AtomEnvironment = AtomCore.AtomEnvironment; - type BufferedProcess = AtomCore.BufferedProcess; - type BufferedProcessStatic = AtomCore.BufferedProcessStatic; - type BufferedNodeProcess = AtomCore.BufferedNodeProcess; - type BufferedNodeProcessStatic = AtomCore.BufferedNodeProcessStatic; - type Clipboard = AtomCore.Clipboard; - type Color = AtomCore.Color; - type CommandRegistry = AtomCore.CommandRegistry; - type Config = AtomCore.Config; - type ContextMenuManager = AtomCore.ContextMenuManager; - type Cursor = AtomCore.Cursor; - type Decoration = AtomCore.Decoration; - type Deserializer = AtomCore.Deserializer; - type DeserializerManager = AtomCore.DeserializerManager; - type Dock = AtomCore.Dock; - type GitRepository = AtomCore.GitRepository; - type GitRepositoryStatic = AtomCore.GitRepositoryStatic; - type Gutter = AtomCore.Gutter; - type HistoryManager = AtomCore.HistoryManager; - type LayerDecoration = AtomCore.LayerDecoration; - type MenuManager = AtomCore.MenuManager; - type Notification = AtomCore.Notification; - type NotificationStatic = AtomCore.NotificationStatic; - type NotificationManager = AtomCore.NotificationManager; - type Package = AtomCore.Package; - type PackageManager = AtomCore.PackageManager; - type Pane = AtomCore.Pane; - type Panel = AtomCore.Panel; - type PathWatcher = AtomCore.PathWatcher; - type Project = AtomCore.Project; - type ScopeDescriptor = AtomCore.ScopeDescriptor; - type Selection = AtomCore.Selection; - type StyleManager = AtomCore.StyleManager; - type Task = AtomCore.Task; - type TaskStatic = AtomCore.TaskStatic; - type TestRunner = AtomCore.TestRunner; - type TextEditor = AtomCore.TextEditor; - type TextEditorStatic = AtomCore.TextEditorStatic; - type TextEditorRegistry = AtomCore.TextEditorRegistry; - type ThemeManager = AtomCore.ThemeManager; - type TooltipManager = AtomCore.TooltipManager; - type ViewRegistry = AtomCore.ViewRegistry; - type Workspace = AtomCore.Workspace; - type WorkspaceCenter = AtomCore.WorkspaceCenter; - - // Atom Keymap ======================================================== - type KeyBinding = AtomKeymap.KeyBinding; - type KeymapManager = AtomKeymap.KeymapManager; - // NOTE: KeymapManagerStatic isn't used. - - // Event Kit ========================================================== - type DisposableLike = EventKit.DisposableLike; - type Disposable = EventKit.Disposable; - type DisposableStatic = EventKit.DisposableStatic; - type CompositeDisposable = EventKit.CompositeDisposable; - type CompositeDisposableStatic = EventKit.CompositeDisposableStatic; - type Emitter = EventKit.Emitter; - type EmitterStatic = EventKit.EmitterStatic; - - // First Mate ========================================================= - type Grammar = FirstMate.Grammar; - type GrammarStatic = FirstMate.GrammarStatic; - type GrammarRegistry = FirstMate.GrammarRegistry; - type GrammarRegistryStatic = FirstMate.GrammarRegistryStatic; - type ScopeSelector = FirstMate.ScopeSelector; - type ScopeSelectorStatic = FirstMate.ScopeSelectorStatic; - - // Path Watcher ======================================================= - type File = PathWatcher.File; - type FileStatic = PathWatcher.FileStatic; - type Directory = PathWatcher.Directory; - type DirectoryStatic = PathWatcher.DirectoryStatic; - // NOTE: PathWatcher isn't used. - - // Text Buffer ======================================================== - type Marker = TextBuffer.Marker; - type MarkerLayer = TextBuffer.MarkerLayer; - type DisplayMarker = TextBuffer.DisplayMarker; - type DisplayMarkerLayer = TextBuffer.DisplayMarkerLayer; - type Point = TextBuffer.Point; - type PointStatic = TextBuffer.PointStatic; - type PointCompatible = TextBuffer.PointCompatible; - type PointLike = TextBuffer.PointLike; - type Range = TextBuffer.Range; - type RangeStatic = TextBuffer.RangeStatic; - type RangeCompatible = TextBuffer.RangeCompatible; - type RangeLike = TextBuffer.RangeLike; - type TextBuffer = TextBuffer.TextBuffer; - type TextBufferStatic = TextBuffer.TextBufferStatic; - } - - const atom: AtomCore.AtomEnvironment; + const atom: AtomEnvironment; } -/** A wrapper which provides standard error/output line buffering for - * Node's ChildProcess. - */ -export const BufferedProcess: AtomCore.BufferedProcessStatic; - -/** Like BufferedProcess, but accepts a Node script as the command to run. - * This is necessary on Windows since it doesn't support shebang #! lines. - */ -export const BufferedNodeProcess: AtomCore.BufferedNodeProcessStatic; - -/** Represents the underlying git operations performed by Atom. */ -export const GitRepository: AtomCore.GitRepositoryStatic; - -/** A notification to the user containing a message and type. */ -export const Notification: AtomCore.NotificationStatic; - -/** A mutable text container with undo/redo support and the ability to - * annotate logical regions in the text. - */ -export const TextBuffer: TextBuffer.TextBufferStatic; - -/** Represents a point in a buffer in row/column coordinates. */ -export const Point: TextBuffer.PointStatic; - -/** Represents a region in a buffer in row/column coordinates. */ -export const Range: TextBuffer.RangeStatic; - -/** Represents an individual file that can be watched, read from, and written to. */ -export const File: PathWatcher.FileStatic; - -/** Represents a directory on disk that can be watched for changes. */ -export const Directory: PathWatcher.DirectoryStatic; - -/** Utility class to be used when implementing event-based APIs that allows - * for handlers registered via ::on to be invoked with calls to ::emit. - */ -export const Emitter: EventKit.EmitterStatic; - -/** A handle to a resource that can be disposed. */ -export const Disposable: EventKit.DisposableStatic; - -/** An object that aggregates multiple Disposable instances together into a - * single disposable, so they can all be disposed as a group. - */ -export const CompositeDisposable: EventKit.CompositeDisposableStatic; - -/** Invoke a callback with each filesystem event that occurs beneath a specified path. +/** + * Invoke a callback with each filesystem event that occurs beneath a specified path. * If you only need to watch events within the project's root paths, use * Project::onDidChangeFiles instead. */ export function watchPath(rootPath: string, options: {}, eventCallback: (events: - AtomCore.Events.FilesystemChange) => void): AtomCore.PathWatcher; + FilesystemChangeEvent) => void): PathWatcher; -/** Run a node script in a separate process. */ -export const Task: AtomCore.TaskStatic; +// Essential Classes ========================================================== -/** This class represents all essential editing state for a single TextBuffer, +/** + * Atom global for dealing with packages, themes, menus, and the window. + * An instance of this class is always available as the atom global. + */ +export interface AtomEnvironment { + // Properties + /** A CommandRegistry instance. */ + commands: CommandRegistry; + + /** A Config instance. */ + config: Config; + + /** A Clipboard instance. */ + clipboard: Clipboard; + + /** A ContextMenuManager instance. */ + contextMenu: ContextMenuManager; + + /** A MenuManager instance. */ + menu: MenuManager; + + /** A KeymapManager instance. */ + keymaps: KeymapManager; + + /** A TooltipManager instance. */ + tooltips: TooltipManager; + + /** A NotificationManager instance. */ + notifications: NotificationManager; + + /** A Project instance. */ + project: Project; + + /** A GrammarRegistry instance. */ + grammars: GrammarRegistry; + + /** A HistoryManager instance. */ + history: HistoryManager; + + /** A PackageManager instance. */ + packages: PackageManager; + + /** A ThemeManager instance. */ + themes: ThemeManager; + + /** A StyleManager instance. */ + styles: StyleManager; + + /** A DeserializerManager instance. */ + deserializers: DeserializerManager; + + /** A ViewRegistry instance. */ + views: ViewRegistry; + + /** A Workspace instance. */ + workspace: Workspace; + + /** A TextEditorRegistry instance. */ + textEditors: TextEditorRegistry; + + // Event Subscription + /** Invoke the given callback whenever ::beep is called. */ + onDidBeep(callback: () => void): Disposable; + + /** + * Invoke the given callback when there is an unhandled error, but before + * the devtools pop open. + */ + onWillThrowError(callback: (event: PreventableExceptionThrownEvent) => void): Disposable; + + /** Invoke the given callback whenever there is an unhandled error. */ + onDidThrowError(callback: (event: ExceptionThrownEvent) => void): Disposable; + + /** + * Invoke the given callback as soon as the shell environment is loaded (or + * immediately if it was already loaded). + */ + whenShellEnvironmentLoaded(callback: () => void): Disposable; + + // Atom Details + /** Returns a boolean that is true if the current window is in development mode. */ + inDevMode(): boolean; + + /** Returns a boolean that is true if the current window is in safe mode. */ + inSafeMode(): boolean; + + /** Returns a boolean that is true if the current window is running specs. */ + inSpecMode(): boolean; + + /** Get the version of the Atom application. */ + getVersion(): string; + + /** + * Gets the release channel of the Atom application. + * Returns the release channel, which can be 'dev', 'beta', or 'stable'. + */ + getReleaseChannel(): "dev"|"beta"|"stable"; + + /** Returns a boolean that is true if the current version is an official release. */ + isReleasedVersion(): boolean; + + /** Get the time taken to completely load the current window. */ + getWindowLoadTime(): number; + + /** Get the load settings for the current window. */ + getLoadSettings(): WindowLoadSettings; + + // Managing the Atom Window + /** Open a new Atom window using the given options. */ + open(params?: { + pathsToOpen: ReadonlyArray, + newWindow?: boolean, + devMode?: boolean, + safeMode?: boolean, + }): void; + + /** Close the current window. */ + close(): void; + + /** Get the size of current window. */ + getSize(): { width: number, height: number }; + + /** Set the size of current window. */ + setSize(width: number, height: number): void; + + /** Get the position of current window. */ + getPosition(): { x: number, y: number }; + + /** Set the position of current window. */ + setPosition(x: number, y: number): void; + + /** Prompt the user to select one or more folders. */ + pickFolder(callback: (paths: string[]|null) => void): void; + + /** Get the current window. */ + getCurrentWindow(): object; + + /** Move current window to the center of the screen. */ + center(): void; + + /** Focus the current window. */ + focus(): void; + + /** Show the current window. */ + show(): void; + + /** Hide the current window. */ + hide(): void; + + /** Reload the current window. */ + reload(): void; + + /** Relaunch the entire application. */ + restartApplication(): void; + + /** Returns a boolean that is true if the current window is maximized. */ + isMaximized(): boolean; + + /** Returns a boolean that is true if the current window is in full screen mode. */ + isFullScreen(): boolean; + + /** Set the full screen state of the current window. */ + setFullScreen(fullScreen: boolean): void; + + /** Toggle the full screen state of the current window. */ + toggleFullScreen(): void; + + // Messaging the User + /** Visually and audibly trigger a beep. */ + beep(): void; + + /** + * A flexible way to open a dialog akin to an alert dialog. + * If the dialog is closed (via `Esc` key or `X` in the top corner) without + * selecting a button the first button will be clicked unless a "Cancel" or "No" + * button is provided. + * + * Returns the chosen button index number if the buttons option was an array. + */ + confirm(options: { + message: string, + detailedMessage?: string, + buttons?: ReadonlyArray, + }): void; + + /** + * A flexible way to open a dialog akin to an alert dialog. + * If the dialog is closed (via `Esc` key or `X` in the top corner) without + * selecting a button the first button will be clicked unless a "Cancel" or "No" + * button is provided. + * + * Returns the chosen button index number if the buttons option was an array. + */ + confirm(options: { + message: string, + detailedMessage?: string, + buttons?: { + [key: string]: () => void + }, + }): number; + + // Managing the Dev Tools + /** Open the dev tools for the current window. */ + openDevTools(): Promise; + + /** Toggle the visibility of the dev tools for the current window. */ + toggleDevTools(): Promise; + + /** Execute code in dev tools. */ + executeJavaScriptInDevTools(code: string): void; +} + +/** + * A simple color class returned from Config::get when the value at the key path is + * of type 'color'. + */ +export interface Color { + /** Returns a string in the form '#abcdef'. */ + toHexString(): string; + + /** Returns a string in the form 'rgba(25, 50, 75, .9)'. */ + toRGBAString(): string; +} + +/** + * Associates listener functions with commands in a context-sensitive way + * using CSS selectors. + */ +export interface CommandRegistry { + /** Register a single command. */ + add(target: string|Node, commandName: string, listener: { + didDispatch(event: CommandEvent): void, + displayName?: string, + description?: string, + } | ((event: CommandEvent) => void)): Disposable; + + /** Register multiple commands. */ + add(target: string|Node, commands: { + [key: string]: (event: CommandEvent) => void + }): CompositeDisposable; + + /** Find all registered commands matching a query. */ + findCommands(params: { target: string|Node }): Array<{ + name: string, + displayName: string, + description?: string, + tags?: string[], + }>; + + /** + * Simulate the dispatch of a command on a DOM node. + * @return Whether or not there was a matching command for the target. + */ + dispatch(target: Node, commandName: string): boolean; + + /** Invoke the given callback before dispatching a command event. */ + onWillDispatch(callback: (event: CommandEvent) => void): Disposable; + + /** Invoke the given callback after dispatching a command event. */ + onDidDispatch(callback: (event: CommandEvent) => void): Disposable; +} + +/** + * An object that aggregates multiple Disposable instances together into a + * single disposable, so they can all be disposed as a group. + */ +export class CompositeDisposable implements DisposableLike { + /** Construct an instance, optionally with one or more disposables. */ + constructor(...disposables: DisposableLike[]); + + /** + * Dispose all disposables added to this composite disposable. + * If this object has already been disposed, this method has no effect. + */ + dispose(): void; + + // Managing Disposables + /** + * Add disposables to be disposed when the composite is disposed. + * If this object has already been disposed, this method has no effect. + */ + add(...disposables: DisposableLike[]): void; + + /** Remove a previously added disposable. */ + remove(disposable: DisposableLike): void; + + /** Alias to CompositeDisposable::remove. */ + delete(disposable: DisposableLike): void; + + /** + * Clear all disposables. They will not be disposed by the next call to + * dispose. + */ + clear(): void; +} + +/** Used to access all of Atom's configuration details. */ +export interface Config { + // Config Subscription + /** + * Add a listener for changes to a given key path. This is different than ::onDidChange in + * that it will immediately call your callback with the current value of the config entry. + */ + observe(keyPath: T, callback: + (value: ConfigValues[T]) => void): Disposable; + /** + * Add a listener for changes to a given key path. This is different than ::onDidChange in + * that it will immediately call your callback with the current value of the config entry. + */ + observe(keyPath: T, options: + { scope: string[]|ScopeDescriptor }, callback: (value: ConfigValues[T]) => void): + Disposable; + + /** + * Add a listener for changes to a given key path. If keyPath is not specified, your + * callback will be called on changes to any key. + */ + // tslint:disable-next-line:no-any + onDidChange(callback: (values: { newValue: T, oldValue: T }) => void): + Disposable; + /** + * Add a listener for changes to a given key path. If keyPath is not specified, your + * callback will be called on changes to any key. + */ + onDidChange(keyPath: T, callback: (values: { + newValue: ConfigValues[T], + oldValue?: ConfigValues[T], + }) => void): Disposable; + /** + * Add a listener for changes to a given key path. If keyPath is not specified, your + * callback will be called on changes to any key. + */ + onDidChange(keyPath: T, options: + { scope: string[]|ScopeDescriptor }, callback: + (values: { newValue: ConfigValues[T], oldValue?: ConfigValues[T] }) => void): + Disposable; + + // Managing Settings + /** Retrieves the setting for the given key. */ + get(keyPath: T, options?: { sources?: string[], + excludeSources?: string[], scope?: string[]|ScopeDescriptor }): + ConfigValues[T]|undefined; + + /** + * Sets the value for a configuration setting. + * This value is stored in Atom's internal configuration file. + */ + set(keyPath: T, value: ConfigValues[T], options?: + { scopeSelector?: string, source?: string }): void; + + /** Restore the setting at keyPath to its default value. */ + unset(keyPath: string, options?: { scopeSelector?: string, source?: string }): void; + + /** + * Get all of the values for the given key-path, along with their associated + * scope selector. + */ + getAll(keyPath: T, options?: { sources?: string[], + excludeSources?: string[], scope?: ScopeDescriptor }): + Array<{ scopeDescriptor: ScopeDescriptor, value: ConfigValues[T] }>; + + /** + * Get an Array of all of the source Strings with which settings have been added + * via ::set. + */ + getSources(): string[]; + + /** + * Retrieve the schema for a specific key path. The schema will tell you what type + * the keyPath expects, and other metadata about the config option. + */ + getSchema(keyPath: string): object|null; + + /** Get the string path to the config file being used. */ + getUserConfigPath(): string; + + /** + * Suppress calls to handler functions registered with ::onDidChange and ::observe + * for the duration of callback. After callback executes, handlers will be called + * once if the value for their key-path has changed. + */ + transact(callback: () => void): void; +} + +/** + * Represents a decoration that follows a DisplayMarker. A decoration is basically + * a visual representation of a marker. It allows you to add CSS classes to line + * numbers in the gutter, lines, and add selection-line regions around marked ranges + * of text. + */ +export interface Decoration { + /** The identifier for this Decoration. */ + id: number; + + // Construction and Destruction + /** + * Destroy this marker decoration. + * You can also destroy the marker if you own it, which will destroy this decoration. + */ + destroy(): void; + + // Event Subscription + /** When the Decoration is updated via Decoration::setProperties. */ + onDidChangeProperties(callback: (event: DecorationPropsChangedEvent) => void): Disposable; + + /** Invoke the given callback when the Decoration is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + // Decoration Details + /** An id unique across all Decoration objects. */ + getId(): number; + + /** Returns the marker associated with this Decoration. */ + getMarker(): DisplayMarker; + + // Properties + /** Returns the Decoration's properties. */ + getProperties(): DecorationOptions; + + /** + * Update the marker with new Properties. Allows you to change the decoration's + * class. + */ + setProperties(newProperties: DecorationOptions): void; +} + +/** + * Represents a buffer annotation that remains logically stationary even as the + * buffer changes. This is used to represent cursors, folds, snippet targets, + * misspelled words, and anything else that needs to track a logical location + * in the buffer over time. + */ +export interface DisplayMarker { + // Construction and Destruction + /** + * Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed, + * a marker cannot be restored by undo/redo operations. + */ + destroy(): void; + + /** Creates and returns a new DisplayMarker with the same properties as this marker. */ + copy(options?: CopyMarkerOptions): DisplayMarker; + + // Event Subscription + /** Invoke the given callback when the state of the marker changes. */ + onDidChange(callback: (event: DisplayMarkerChangedEvent) => void): Disposable; + + /** Invoke the given callback when the marker is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + // TextEditorMarker Details + /** + * Returns a boolean indicating whether the marker is valid. Markers can be + * invalidated when a region surrounding them in the buffer is changed. + */ + isValid(): boolean; + + /** + * Returns a boolean indicating whether the marker has been destroyed. A marker + * can be invalid without being destroyed, in which case undoing the invalidating + * operation would restore the marker. + */ + isDestroyed(): boolean; + + /** Returns a boolean indicating whether the head precedes the tail. */ + isReversed(): boolean; + + /** + * Returns a boolean indicating whether changes that occur exactly at the marker's + * head or tail cause it to move. + */ + isExclusive(): boolean; + + /** + * Get the invalidation strategy for this marker. + * Valid values include: never, surround, overlap, inside, and touch. + */ + getInvalidationStrategy(): string; + + /** Returns an Object containing any custom properties associated with the marker. */ + getProperties(): object; + + /** Merges an Object containing new properties into the marker's existing properties. */ + setProperties(properties: object): void; + + /** Returns whether this marker matches the given parameters. */ + matchesProperties(attributes: FindDisplayMarkerOptions): boolean; + + // Comparing to other markers + /** Compares this marker to another based on their ranges. */ + compare(other: DisplayMarker): number; + + /** + * Returns a boolean indicating whether this marker is equivalent to another + * marker, meaning they have the same range and options. + */ + isEqual(other: DisplayMarker): boolean; + + // Managing the marker's range + /** Gets the buffer range of this marker. */ + getBufferRange(): Range; + + /** Gets the screen range of this marker. */ + getScreenRange(): Range; + + /** Modifies the buffer range of this marker. */ + setBufferRange(bufferRange: RangeCompatible, properties?: { reversed: boolean }): + void; + + /** Modifies the screen range of this marker. */ + setScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean, + clipDirection?: "backward"|"forward"|"closest" }): void; + + /** + * Retrieves the screen position of the marker's start. This will always be + * less than or equal to the result of DisplayMarker::getEndScreenPosition. + */ + getStartScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }): + Point; + + /** + * Retrieves the screen position of the marker's end. This will always be + * greater than or equal to the result of DisplayMarker::getStartScreenPosition. + */ + getEndScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }): + Point; + + /** Retrieves the buffer position of the marker's head. */ + getHeadBufferPosition(): Point; + + /** Sets the buffer position of the marker's head. */ + setHeadBufferPosition(bufferPosition: PointCompatible): void; + + /** Retrieves the screen position of the marker's head. */ + getHeadScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }): + Point; + + /** Sets the screen position of the marker's head. */ + setHeadScreenPosition(screenPosition: PointCompatible, + options?: { clipDirection: "backward"|"forward"|"closest" }): void; + + /** Retrieves the buffer position of the marker's tail. */ + getTailBufferPosition(): Point; + + /** Sets the buffer position of the marker's tail. */ + setTailBufferPosition(bufferPosition: PointCompatible): void; + + /** Retrieves the screen position of the marker's tail. */ + getTailScreenPosition(options?: { clipDirection: "backward"|"forward"|"closest" }): + Point; + + /** Sets the screen position of the marker's tail. */ + setTailScreenPosition(screenPosition: PointCompatible, + options?: { clipDirection: "backward"|"forward"|"closest" }): void; + + /** + * Retrieves the buffer position of the marker's start. This will always be less + * than or equal to the result of DisplayMarker::getEndBufferPosition. + */ + getStartBufferPosition(): Point; + + /** + * Retrieves the buffer position of the marker's end. This will always be greater + * than or equal to the result of DisplayMarker::getStartBufferPosition. + */ + getEndBufferPosition(): Point; + + /** Returns a boolean indicating whether the marker has a tail. */ + hasTail(): boolean; + + /** + * Plants the marker's tail at the current head position. After calling the + * marker's tail position will be its head position at the time of the call, + * regardless of where the marker's head is moved. + */ + plantTail(): void; + + /** + * Removes the marker's tail. After calling the marker's head position will be + * reported as its current tail position until the tail is planted again. + */ + clearTail(): void; +} + +/** + * Experimental: A container for a related set of markers at the DisplayLayer level. + * Wraps an underlying MarkerLayer on the TextBuffer. + * + * This API is experimental and subject to change on any release. + */ +export interface DisplayMarkerLayer { + // Lifecycle + /** Destroy this layer. */ + destroy(): void; + + /** Destroy all markers in this layer. */ + clear(): void; + + /** Determine whether this layer has been destroyed. */ + isDestroyed(): boolean; + + // Event Subscription + /** Subscribe to be notified synchronously when this layer is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** + * Subscribe to be notified asynchronously whenever markers are created, updated, + * or destroyed on this layer. Prefer this method for optimal performance when + * interacting with layers that could contain large numbers of markers. + */ + onDidUpdate(callback: () => void): Disposable; + + /** + * Subscribe to be notified synchronously whenever markers are created on this + * layer. Avoid this method for optimal performance when interacting with layers + * that could contain large numbers of markers. + */ + onDidCreateMarker(callback: (marker: DisplayMarker|Marker) => void): Disposable; + + // Marker creation + /** Create a marker with the given screen range. */ + markScreenRange(range: RangeCompatible, options?: { reversed?: boolean, + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", exclusive?: + boolean, clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker; + + /** + * Create a marker on this layer with its head at the given screen position + * and no tail. + */ + markScreenPosition(screenPosition: PointCompatible, options?: { invalidate?: + "never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean, + clipDirection?: "backward"|"forward"|"closest" }): DisplayMarker; + + /** Create a marker with the given buffer range. */ + markBufferRange(range: RangeCompatible, options?: { + reversed?: boolean, invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", + exclusive?: boolean }): DisplayMarker; + + /** + * Create a marker on this layer with its head at the given buffer position + * and no tail. + */ + markBufferPosition(bufferPosition: PointCompatible, options?: { invalidate?: + "never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }): + DisplayMarker; + + // Querying + /** Get an existing marker by its id. */ + getMarker(id: number): DisplayMarker; + + /** Get all markers in the layer. */ + getMarkers(): DisplayMarker[]; + + /** Get the number of markers in the marker layer. */ + getMarkerCount(): number; + + /** + * Find markers in the layer conforming to the given parameters. + * + * This method finds markers based on the given properties. Markers can be associated + * with custom properties that will be compared with basic equality. In addition, + * there are several special properties that will be compared with the range of the + * markers rather than their properties. + */ + findMarkers(properties: FindDisplayMarkerOptions): DisplayMarker[]; +} + +/** A handle to a resource that can be disposed. */ +export class Disposable implements DisposableLike { + /** Ensure that Object correctly implements the Disposable contract. */ + static isDisposable(object: object): boolean; + + /** Construct a Disposable. */ + constructor(disposableAction?: () => void); + + /** A callback which will be called within dispose(). */ + disposalAction?(): void; + + /** + * Perform the disposal action, indicating that the resource associated + * with this disposable is no longer needed. + */ + dispose(): void; +} + +/** + * Utility class to be used when implementing event-based APIs that allows + * for handlers registered via ::on to be invoked with calls to ::emit. + */ +export class Emitter implements DisposableLike { + /** Construct an emitter. */ + constructor(); + + /** Clear out any existing subscribers. */ + clear(): void; + + /** Unsubscribe all handlers. */ + dispose(): boolean; + + // Event Subscription + /** Registers a handler to be invoked whenever the given event is emitted. */ + on(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + /** + * Register the given handler function to be invoked the next time an event + * with the given name is emitted via ::emit. + */ + once(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + /** + * Register the given handler function to be invoked before all other + * handlers existing at the time of subscription whenever events by the + * given name are emitted via ::emit. + */ + preempt(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + // Event Emission + /** Invoke the handlers registered via ::on for the given event name. */ + emit(eventName: T, value?: Emissions[T]): void; +} + +/** + * Represents a decoration that applies to every marker on a given layer. Created via + * TextEditor::decorateMarkerLayer. + */ +export interface LayerDecoration { + /** Destroys the decoration. */ + destroy(): void; + + /** Determine whether this decoration is destroyed. */ + isDestroyed(): boolean; + + /** Get this decoration's properties. */ + getProperties(): DecorationLayerOptions; + + /** Set this decoration's properties. */ + setProperties(newProperties: DecorationLayerOptions): void; + + /** Override the decoration properties for a specific marker. */ + setPropertiesForMarker(marker: DisplayMarker|Marker, properties: DecorationLayerOptions): + void; +} + +/** + * Represents a buffer annotation that remains logically stationary even as + * the buffer changes. + */ +export interface Marker { + /** The identifier for this Marker. */ + id: number; + + // Lifecycle + /** + * Creates and returns a new Marker with the same properties as this + * marker. + */ + copy(options?: CopyMarkerOptions): Marker; + + /** Destroys the marker, causing it to emit the "destroyed" event. */ + destroy(): void; + + // Event Subscription + /** Invoke the given callback when the marker is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** Invoke the given callback when the state of the marker changes. */ + onDidChange(callback: (event: MarkerChangedEvent) => void): Disposable; + + // Marker Details + /** Returns the current range of the marker. The range is immutable. */ + getRange(): Range; + + /** Returns a point representing the marker's current head position. */ + getHeadPosition(): Point; + + /** Returns a point representing the marker's current tail position. */ + getTailPosition(): Point; + + /** + * Returns a point representing the start position of the marker, which + * could be the head or tail position, depending on its orientation. + */ + getStartPosition(): Point; + + /** + * Returns a point representing the end position of the marker, which + * could be the head or tail position, depending on its orientation. + */ + getEndPosition(): Point; + + /** Returns a boolean indicating whether the head precedes the tail. */ + isReversed(): boolean; + + /** Returns a boolean indicating whether the marker has a tail. */ + hasTail(): boolean; + + /** Is the marker valid? */ + isValid(): boolean; + + /** Is the marker destroyed? */ + isDestroyed(): boolean; + + /** + * Returns a boolean indicating whether changes that occur exactly at + * the marker's head or tail cause it to move. + */ + isExclusive(): boolean; + + /** Get the invalidation strategy for this marker. */ + getInvalidationStrategy(): string; + + // Mutating Markers + /** + * Sets the range of the marker. + * Returns a boolean indicating whether or not the marker was updated. + */ + setRange(range: RangeCompatible, params?: { reversed?: boolean, exclusive?: + boolean }): boolean; + + /** + * Sets the head position of the marker. + * Returns a boolean indicating whether or not the marker was updated. + */ + setHeadPosition(position: PointCompatible): boolean; + + /** + * Sets the tail position of the marker. + * Returns a boolean indicating whether or not the marker was updated. + */ + setTailPosition(position: PointCompatible): boolean; + + /** + * Removes the marker's tail. + * Returns a boolean indicating whether or not the marker was updated. + */ + clearTail(): boolean; + + /** + * Plants the marker's tail at the current head position. + * Returns a boolean indicating whether or not the marker was updated. + */ + plantTail(): boolean; + + // Comparison + /** + * Returns a boolean indicating whether this marker is equivalent to + * another marker, meaning they have the same range and options. + */ + isEqual(other: Marker): boolean; + + /** + * Compares this marker to another based on their ranges. + * Returns "-1" if this marker precedes the argument. + * Returns "0" if this marker is equivalent to the argument. + * Returns "1" if this marker follows the argument. + */ + compare(other: Marker): number; +} + +/** Experimental: A container for a related set of markers. */ +export interface MarkerLayer { + // Lifecycle + /** Create a copy of this layer with markers in the same state and locations. */ + copy(): MarkerLayer; + + /** Destroy this layer. */ + destroy(): boolean; + + /** Remove all markers from this layer. */ + clear(): void; + + /** Determine whether this layer has been destroyed. */ + isDestroyed(): boolean; + + // Querying + /** Get an existing marker by its id. */ + getMarker(id: number): Marker|undefined; + + /** Get all existing markers on the marker layer. */ + getMarkers(): Marker[]; + + /** Get the number of markers in the marker layer. */ + getMarkerCount(): number; + + /** Find markers in the layer conforming to the given parameters. */ + findMarkers(params: FindMarkerOptions): Marker[]; + + // Marker Creation + /** Create a marker with the given range. */ + markRange(range: RangeCompatible, options?: { reversed?: boolean, invalidate?: + "never"|"surround"|"overlap"|"inside"|"touch", exclusive?: boolean }): Marker; + + /** Create a marker at with its head at the given position with no tail. */ + markPosition(position: PointCompatible, options?: { invalidate?: "never"|"surround" + |"overlap"|"inside"|"touch", exclusive?: boolean }): Marker; + + // Event Subscription + /** + * Subscribe to be notified asynchronously whenever markers are created, + * updated, or destroyed on this layer. + */ + onDidUpdate(callback: () => void): Disposable; + + /** + * Subscribe to be notified synchronously whenever markers are created on + * this layer. + */ + onDidCreateMarker(callback: (marker: Marker) => void): Disposable; + + /** Subscribe to be notified synchronously when this layer is destroyed. */ + onDidDestroy(callback: () => void): Disposable; +} + +/** A notification to the user containing a message and type. */ +export class Notification { + constructor(type: "warning"|"info"|"success", message: string, + options?: NotificationOptions); + constructor(type: "fatal"|"error", message: string, options?: ErrorNotificationOptions); + + // Event Subscription + /** Invoke the given callback when the notification is dismissed. */ + onDidDismiss(callback: (notification: Notification) => void): Disposable; + + /** Invoke the given callback when the notification is displayed. */ + onDidDisplay(callback: (notification: Notification) => void): Disposable; + + // Methods + /** Returns the Notification's type. */ + getType(): string; + + /** Returns the Notification's message. */ + getMessage(): string; + + /** + * Dismisses the notification, removing it from the UI. Calling this + * programmatically will call all callbacks added via onDidDismiss. + */ + dismiss(): void; +} + +/** A notification manager used to create Notifications to be shown to the user. */ +export interface NotificationManager { + // Properties + notifications: Notification[]; + + // Events + /** Invoke the given callback after a notification has been added. */ + onDidAddNotification(callback: (notification: Notification) => void): Disposable; + + // Adding Notifications + /** Add a success notification. */ + addSuccess(message: string, options?: NotificationOptions): Notification; + + /** Add an informational notification. */ + addInfo(message: string, options?: NotificationOptions): Notification; + + /** Add a warning notification. */ + addWarning(message: string, options?: NotificationOptions): Notification; + + /** Add an error notification. */ + addError(message: string, options?: ErrorNotificationOptions): Notification; + + /** Add a fatal error notification. */ + addFatalError(message: string, options?: ErrorNotificationOptions): Notification; + + // Getting Notifications + /** Get all the notifications. */ + getNotifications(): Notification[]; +} + +/** Represents a point in a buffer in row/column coordinates. */ +export class Point { + // Properties + /** A zero-indexed number representing the row of the Point. */ + row: number; + + /** A zero-indexed number representing the column of the Point. */ + column: number; + + // Construction + /** + * Create a Point from an array containing two numbers representing the + * row and column. + */ + static fromObject(object: [number, number]): Point; + + /** Create a Point from an existing object which implements PointLike. */ + static fromObject(object: PointLike, copy?: boolean): Point; + + /** Construct a Point object */ + constructor(row?: number, column?: number); + + /** Returns a new Point with the same row and column. */ + copy(): Point; + + /** Returns a new Point with the row and column negated. */ + negate(): Point; + + // Comparison + /** Returns the given Point that is earlier in the buffer. */ + static min(point1: PointCompatible, point2: PointCompatible): Point; + + /** + * Compare another Point to this Point instance. + * Returns -1 if this point precedes the argument. + * Returns 0 if this point is equivalent to the argument. + * Returns 1 if this point follows the argument. + */ + compare(other: PointCompatible): number; + + /** + * Returns a boolean indicating whether this point has the same row and + * column as the given Point. + */ + isEqual(other: PointCompatible): boolean; + + /** Returns a Boolean indicating whether this point precedes the given Point. */ + isLessThan(other: PointCompatible): boolean; + + /** + * Returns a Boolean indicating whether this point precedes or is equal to + * the given Point. + */ + isLessThanOrEqual(other: PointCompatible): boolean; + + /** Returns a Boolean indicating whether this point follows the given Point. */ + isGreaterThan(other: PointCompatible): boolean; + + /** + * Returns a Boolean indicating whether this point follows or is equal to + * the given Point. + */ + isGreaterThanOrEqual(other: PointCompatible): boolean; + + // Operations + /** Makes this point immutable and returns itself. */ + freeze(): Readonly; + + /** + * Build and return a new point by adding the rows and columns of the + * given point. + */ + translate(other: PointCompatible): Point; + + /** + * Build and return a new Point by traversing the rows and columns + * specified by the given point. + */ + traverse(other: PointCompatible): Point; + + /** Returns an array of this point's row and column. */ + toArray(): [number, number]; + + /** Returns an array of this point's row and column. */ + serialize(): [number, number]; + + /** Returns a string representation of the point. */ + toString(): string; +} + +/** Represents a region in a buffer in row/column coordinates. */ +export class Range { + // Properties + /** A Point representing the start of the Range. */ + start: Point; + + /** A Point representing the end of the Range. */ + end: Point; + + // Construction + /** Convert any range-compatible object to a Range. */ + static fromObject(object: RangeCompatible, copy?: boolean): Range; + + /** Construct a Range object. */ + constructor(pointA?: PointCompatible, pointB?: PointCompatible); + + /** Call this with the result of Range::serialize to construct a new Range. */ + static deserialize(array: object): Range; + + /** Returns a new range with the same start and end positions. */ + copy(): Range; + + /** Returns a new range with the start and end positions negated. */ + negate(): Range; + + // Serialization and Deserialization + /** Returns a plain javascript object representation of the Range. */ + serialize(): number[][]; + + // Range Details + /** Is the start position of this range equal to the end position? */ + isEmpty(): boolean; + + /** + * Returns a boolean indicating whether this range starts and ends on the + * same row. + */ + isSingleLine(): boolean; + + /** Get the number of rows in this range. */ + getRowCount(): number; + + /** Returns an array of all rows in the range. */ + getRows(): number[]; + + // Operations + /** + * Freezes the range and its start and end point so it becomes immutable + * and returns itself. + */ + freeze(): Readonly; + + // NOTE: this function doesn't actually take a range-compatible parameter. + /** Returns a new range that contains this range and the given range. */ + union(other: RangeLike): Range; + + /** + * Build and return a new range by translating this range's start and end + * points by the given delta(s). + */ + translate(startDelta: PointCompatible, endDelta?: PointCompatible): Range; + + /** + * Build and return a new range by traversing this range's start and end + * points by the given delta. + */ + traverse(delta: PointCompatible): Range; + + // Comparison + /** + * Compare two Ranges. + * Returns -1 if this range starts before the argument or contains it. + * Returns 0 if this range is equivalent to the argument. + * Returns 1 if this range starts after the argument or is contained by it. + */ + compare(otherRange: RangeCompatible): number; + + /** + * Returns a Boolean indicating whether this range has the same start and + * end points as the given Range. + */ + isEqual(otherRange: RangeCompatible): boolean; + + // NOTE: this function doesn't actually take a range-compatible parameter. + /** + * Returns a Boolean indicating whether this range starts and ends on the + * same row as the argument. + */ + coversSameRows(otherRange: RangeLike): boolean; + + // NOTE: this function doesn't actually take a range-compatible parameter. + /** Determines whether this range intersects with the argument. */ + intersectsWith(otherRange: RangeLike, exclusive?: boolean): boolean; + + /** Returns a boolean indicating whether this range contains the given range. */ + containsRange(otherRange: RangeCompatible, exclusive?: boolean): boolean; + + /** Returns a boolean indicating whether this range contains the given point. */ + containsPoint(point: PointCompatible, exclusive?: boolean): boolean; + + /** + * Returns a boolean indicating whether this range intersects the given + * row number. + */ + intersectsRow(row: number): boolean; + + /** + * Returns a boolean indicating whether this range intersects the row range + * indicated by the given startRow and endRow numbers. + */ + intersectsRowRange(startRow: number, endRow: number): boolean; + + // Conversion + /** Returns a string representation of the range. */ + toString(): string; +} + +/** + * This class represents all essential editing state for a single TextBuffer, * including cursor and selection positions, folds, and soft wraps. */ -export const TextEditor: AtomCore.TextEditorStatic; +export class TextEditor { + id: number; + buffer: TextBuffer; + + // NOTE: undocumented within the public API. Don't go down the rabbit hole. + constructor(options?: object); + + // Event Subscription + /** Calls your callback when the buffer's title has changed. */ + onDidChangeTitle(callback: (title: string) => void): Disposable; + + /** Calls your callback when the buffer's path, and therefore title, has changed. */ + onDidChangePath(callback: (path: string) => void): Disposable; + + /** + * Invoke the given callback synchronously when the content of the buffer + * changes. + */ + onDidChange(callback: (event: EditorChangedEvent[]) => void): Disposable; + + /** + * Invoke callback when the buffer's contents change. It is emit + * asynchronously 300ms after the last buffer change. This is a good place + * to handle changes to the buffer without compromising typing performance. + */ + onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void): Disposable; + + /** + * Calls your callback when a Cursor is moved. If there are multiple cursors, + * your callback will be called for each cursor. + */ + onDidChangeCursorPosition(callback: (event: CursorPositionChangedEvent) => void): + Disposable; + + /** Calls your callback when a selection's screen range changes. */ + onDidChangeSelectionRange(callback: (event: SelectionChangedEvent) => void): Disposable; + + /** Invoke the given callback after the buffer is saved to disk. */ + onDidSave(callback: (event: { path: string }) => void): Disposable; + + /** Invoke the given callback when the editor is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** Retrieves the current TextBuffer. */ + getBuffer(): TextBuffer; + + /** + * Calls your callback when a Gutter is added to the editor. Immediately calls + * your callback for each existing gutter. + */ + observeGutters(callback: (gutter: Gutter) => void): Disposable; + + /** Calls your callback when a Gutter is added to the editor. */ + onDidAddGutter(callback: (gutter: Gutter) => void): Disposable; + + /** Calls your callback when a Gutter is removed from the editor. */ + onDidRemoveGutter(callback: (name: string) => void): Disposable; + + /** Calls your callback when soft wrap was enabled or disabled. */ + onDidChangeSoftWrapped(callback: (softWrapped: boolean) => void): Disposable; + + /** Calls your callback when the buffer's encoding has changed. */ + onDidChangeEncoding(callback: (encoding: string) => void): Disposable; + + /** + * Calls your callback when the grammar that interprets and colorizes the text + * has been changed. Immediately calls your callback with the current grammar. + */ + observeGrammar(callback: (grammar: Grammar) => void): Disposable; + + /** + * Calls your callback when the grammar that interprets and colorizes the text + * has been changed. + */ + onDidChangeGrammar(callback: (grammar: Grammar) => void): Disposable; + + /** Calls your callback when the result of ::isModified changes. */ + onDidChangeModified(callback: (modified: boolean) => void): Disposable; + + /** + * Calls your callback when the buffer's underlying file changes on disk at a + * moment when the result of ::isModified is true. + */ + onDidConflict(callback: () => void): Disposable; + + /** Calls your callback before text has been inserted. */ + onWillInsertText(callback: (event: { text: string, cancel(): void }) => void): Disposable; + + /** Calls your callback after text has been inserted. */ + onDidInsertText(callback: (event: { text: string }) => void): Disposable; + + /** + * Calls your callback when a Cursor is added to the editor. Immediately calls + * your callback for each existing cursor. + */ + observeCursors(callback: (cursor: Cursor) => void): Disposable; + + /** Calls your callback when a Cursor is added to the editor. */ + onDidAddCursor(callback: (cursor: Cursor) => void): Disposable; + + /** Calls your callback when a Cursor is removed from the editor. */ + onDidRemoveCursor(callback: (cursor: Cursor) => void): Disposable; + + /** + * Calls your callback when a Selection is added to the editor. Immediately + * calls your callback for each existing selection. + */ + observeSelections(callback: (selection: Selection) => void): Disposable; + + /** Calls your callback when a Selection is added to the editor. */ + onDidAddSelection(callback: (selection: Selection) => void): Disposable; + + /** Calls your callback when a Selection is removed from the editor. */ + onDidRemoveSelection(callback: (selection: Selection) => void): Disposable; + + /** + * Calls your callback with each Decoration added to the editor. Calls your + * callback immediately for any existing decorations. + */ + observeDecorations(callback: (decoration: Decoration) => void): Disposable; + + /** Calls your callback when a Decoration is added to the editor. */ + onDidAddDecoration(callback: (decoration: Decoration) => void): Disposable; + + /** Calls your callback when a Decoration is removed from the editor. */ + onDidRemoveDecoration(callback: (decoration: Decoration) => void): Disposable; + + /** Calls your callback when the placeholder text is changed. */ + onDidChangePlaceholderText(callback: (placeholderText: string) => void): Disposable; + + // File Details + /** + * Get the editor's title for display in other parts of the UI such as the tabs. + * If the editor's buffer is saved, its title is the file name. If it is unsaved, + * its title is "untitled". + */ + getTitle(): string; + + /** + * Get unique title for display in other parts of the UI, such as the window title. + * If the editor's buffer is unsaved, its title is "untitled" If the editor's + * buffer is saved, its unique title is formatted as one of the following, + * + * "" when it is the only editing buffer with this file name. + * " — " when other buffers have this file name. + */ + getLongTitle(): string; + + /** Returns the string path of this editor's text buffer. */ + getPath(): string|undefined; + + /** Returns boolean true if this editor has been modified. */ + isModified(): boolean; + + /** Returns boolean true if this editor has no content. */ + isEmpty(): boolean; + + /** Returns the string character set encoding of this editor's text buffer. */ + getEncoding(): string; + + /** Set the character set encoding to use in this editor's text buffer. */ + setEncoding(encoding: string): void; + + // File Operations + /** + * Saves the editor's text buffer. + * See TextBuffer::save for more details. + */ + save(): Promise; + + /** + * Saves the editor's text buffer as the given path. + * See TextBuffer::saveAs for more details. + */ + saveAs(filePath: string): Promise; + + // Reading Text + /** Returns a string representing the entire contents of the editor. */ + getText(): string; + + /** Get the text in the given range in buffer coordinates. */ + getTextInBufferRange(range: RangeCompatible): string; + + /** Returns a number representing the number of lines in the buffer. */ + getLineCount(): number; + + /** + * Returns a number representing the number of screen lines in the editor. + * This accounts for folds. + */ + getScreenLineCount(): number; + + /** + * Returns a number representing the last zero-indexed buffer row number of + * the editor. + */ + getLastBufferRow(): number; + + /** + * Returns a number representing the last zero-indexed screen row number of + * the editor. + */ + getLastScreenRow(): number; + + /** + * Returns a string representing the contents of the line at the given + * buffer row. + */ + lineTextForBufferRow(bufferRow: number): string; + + /** + * Returns a string representing the contents of the line at the given + * screen row. + */ + lineTextForScreenRow(screenRow: number): string; + + /** Get the range of the paragraph surrounding the most recently added cursor. */ + getCurrentParagraphBufferRange(): Range; + + // Mutating Text + /** Replaces the entire contents of the buffer with the given string. */ + setText(text: string): void; + + /** Set the text in the given Range in buffer coordinates. */ + setTextInBufferRange(range: RangeCompatible, text: string, options?: + { normalizeLineEndings?: boolean, undo?: "skip" }): void; + + /* For each selection, replace the selected text with the given text. */ + insertText(text: string, options?: { + select?: boolean, + autoIndent?: boolean, + autoIndentNewline?: boolean, + autoDecreaseIndent?: boolean, + normalizeLineEndings?: boolean, + undo?: "skip" + }): Range|boolean; + + /** For each selection, replace the selected text with a newline. */ + insertNewline(): void; + + /** + * For each selection, if the selection is empty, delete the character following + * the cursor. Otherwise delete the selected text. + */ + delete(): void; + + /** + * For each selection, if the selection is empty, delete the character preceding + * the cursor. Otherwise delete the selected text. + */ + backspace(): void; + + /** + * Mutate the text of all the selections in a single transaction. + * All the changes made inside the given function can be reverted with a single + * call to ::undo. + */ + mutateSelectedText(fn: (selection: Selection, index: number) => void): void; + + /** + * For each selection, transpose the selected text. + * If the selection is empty, the characters preceding and following the cursor + * are swapped. Otherwise, the selected characters are reversed. + */ + transpose(): void; + + /** + * Convert the selected text to upper case. + * For each selection, if the selection is empty, converts the containing word + * to upper case. Otherwise convert the selected text to upper case. + */ + upperCase(): void; + + /** + * Convert the selected text to lower case. + * For each selection, if the selection is empty, converts the containing word + * to upper case. Otherwise convert the selected text to upper case. + */ + lowerCase(): void; + + /** + * Toggle line comments for rows intersecting selections. + * If the current grammar doesn't support comments, does nothing. + */ + toggleLineCommentsInSelection(): void; + + /** For each cursor, insert a newline at beginning the following line. */ + insertNewlineBelow(): void; + + /** For each cursor, insert a newline at the end of the preceding line. */ + insertNewlineAbove(): void; + + /** + * For each selection, if the selection is empty, delete all characters of the + * containing word that precede the cursor. Otherwise delete the selected text. + */ + deleteToBeginningOfWord(): void; + + /** + * Similar to ::deleteToBeginningOfWord, but deletes only back to the previous + * word boundary. + */ + deleteToPreviousWordBoundary(): void; + + /** Similar to ::deleteToEndOfWord, but deletes only up to the next word boundary. */ + deleteToNextWordBoundary(): void; + + /** + * For each selection, if the selection is empty, delete all characters of the + * containing subword following the cursor. Otherwise delete the selected text. + */ + deleteToBeginningOfSubword(): void; + + /** + * For each selection, if the selection is empty, delete all characters of the + * containing subword following the cursor. Otherwise delete the selected text. + */ + deleteToEndOfSubword(): void; + + /** + * For each selection, if the selection is empty, delete all characters of the + * containing line that precede the cursor. Otherwise delete the selected text. + */ + deleteToBeginningOfLine(): void; + + /** + * For each selection, if the selection is not empty, deletes the selection + * otherwise, deletes all characters of the containing line following the cursor. + * If the cursor is already at the end of the line, deletes the following newline. + */ + deleteToEndOfLine(): void; + + /** + * For each selection, if the selection is empty, delete all characters of the + * containing word following the cursor. Otherwise delete the selected text. + */ + deleteToEndOfWord(): void; + + /** Delete all lines intersecting selections. */ + deleteLine(): void; + + // History + /** Undo the last change. */ + undo(): void; + + /** Redo the last change. */ + redo(): void; + + /** + * Batch multiple operations as a single undo/redo step. + * Any group of operations that are logically grouped from the perspective of undoing + * and redoing should be performed in a transaction. If you want to abort the transaction, + * call ::abortTransaction to terminate the function's execution and revert any changes + * performed up to the abortion. + */ + transact(fn: () => void): void; + /** + * Batch multiple operations as a single undo/redo step. + * Any group of operations that are logically grouped from the perspective of undoing + * and redoing should be performed in a transaction. If you want to abort the transaction, + * call ::abortTransaction to terminate the function's execution and revert any changes + * performed up to the abortion. + */ + transact(groupingInterval: number, fn: () => void): void; + + /** + * Abort an open transaction, undoing any operations performed so far within the + * transaction. + */ + abortTransaction(): void; + + /** + * Create a pointer to the current state of the buffer for use with ::revertToCheckpoint + * and ::groupChangesSinceCheckpoint. + */ + createCheckpoint(): number; + + /** + * Revert the buffer to the state it was in when the given checkpoint was created. + * The redo stack will be empty following this operation, so changes since the checkpoint + * will be lost. If the given checkpoint is no longer present in the undo history, no + * changes will be made to the buffer and this method will return false. + */ + revertToCheckpoint(checkpoint: number): boolean; + + /** + * Group all changes since the given checkpoint into a single transaction for purposes + * of undo/redo. + * If the given checkpoint is no longer present in the undo history, no grouping will be + * performed and this method will return false. + */ + groupChangesSinceCheckpoint(checkpoint: number): boolean; + + // TextEditor Coordinates + /** Convert a position in buffer-coordinates to screen-coordinates. */ + screenPositionForBufferPosition(bufferPosition: PointCompatible, options?: + { clipDirection?: "backward"|"forward"|"closest"}): Point; + + /** Convert a position in screen-coordinates to buffer-coordinates. */ + bufferPositionForScreenPosition(bufferPosition: PointCompatible, options?: + { clipDirection?: "backward"|"forward"|"closest"}): Point; + + /** Convert a range in buffer-coordinates to screen-coordinates. */ + screenRangeForBufferRange(bufferRange: RangeCompatible): Range; + + /** Convert a range in screen-coordinates to buffer-coordinates. */ + bufferRangeForScreenRange(screenRange: RangeCompatible): Range; + + /** Clip the given Point to a valid position in the buffer. */ + clipBufferPosition(bufferPosition: PointCompatible): Point; + + /** + * Clip the start and end of the given range to valid positions in the buffer. + * See ::clipBufferPosition for more information. + */ + clipBufferRange(range: RangeCompatible): Range; + + /** Clip the given Point to a valid position on screen. */ + clipScreenPosition(screenPosition: PointCompatible, options?: + { clipDirection?: "backward"|"forward"|"closest"}): Point; + + /** + * Clip the start and end of the given range to valid positions on screen. + * See ::clipScreenPosition for more information. + */ + clipScreenRange(range: RangeCompatible, options?: { clipDirection?: + "backward"|"forward"|"closest"}): Range; + + // Decorations + /** + * Add a decoration that tracks a DisplayMarker. When the marker moves, is + * invalidated, or is destroyed, the decoration will be updated to reflect + * the marker's state. + */ + decorateMarker(marker: DisplayMarker, decorationParams: DecorationOptions): Decoration; + + /** + * Add a decoration to every marker in the given marker layer. Can be used to + * decorate a large number of markers without having to create and manage many + * individual decorations. + */ + decorateMarkerLayer(markerLayer: MarkerLayer|DisplayMarkerLayer, + decorationParams: DecorationLayerOptions): LayerDecoration; + + /** Get all decorations. */ + getDecorations(propertyFilter?: DecorationOptions): Decoration[]; + + /** Get all decorations of type 'line'. */ + getLineDecorations(propertyFilter?: DecorationOptions): Decoration[]; + + /** Get all decorations of type 'line-number'. */ + getLineNumberDecorations(propertyFilter?: DecorationOptions): Decoration[]; + + /** Get all decorations of type 'highlight'. */ + getHighlightDecorations(propertyFilter?: DecorationOptions): Decoration[]; + + /** Get all decorations of type 'overlay'. */ + getOverlayDecorations(propertyFilter?: DecorationOptions): Decoration[]; + + // Markers + /** + * Create a marker on the default marker layer with the given range in buffer coordinates. + * This marker will maintain its logical location as the buffer is changed, so if you mark + * a particular word, the marker will remain over that word even if the word's location + * in the buffer changes. + */ + markBufferRange(range: RangeCompatible, properties?: { + maintainHistory?: boolean, + reversed?: boolean, + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", + }): DisplayMarker; + + /** + * Create a marker on the default marker layer with the given range in screen coordinates. + * This marker will maintain its logical location as the buffer is changed, so if you mark + * a particular word, the marker will remain over that word even if the word's location in + * the buffer changes. + */ + markScreenRange(range: RangeCompatible, properties?: { + maintainHistory?: boolean, reversed?: boolean, + invalidate?: "never"|"surround"|"overlap"|"inside" |"touch", + }): DisplayMarker; + + /** + * Create a marker on the default marker layer with the given buffer position and no tail. + * To group multiple markers together in their own private layer, see ::addMarkerLayer. + */ + markBufferPosition(bufferPosition: PointCompatible, options?: { + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", + }): DisplayMarker; + + /** + * Create a marker on the default marker layer with the given screen position and no tail. + * To group multiple markers together in their own private layer, see ::addMarkerLayer. + */ + markScreenPosition(screenPosition: PointCompatible, options?: { + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", + clipDirection?: "backward"|"forward"|"closest", + }): DisplayMarker; + + /** + * Find all DisplayMarkers on the default marker layer that match the given properties. + * + * This method finds markers based on the given properties. Markers can be associated + * with custom properties that will be compared with basic equality. In addition, there + * are several special properties that will be compared with the range of the markers + * rather than their properties. + */ + findMarkers(properties: FindDisplayMarkerOptions): DisplayMarker[]; + + /** Create a marker layer to group related markers. */ + addMarkerLayer(options?: { maintainHistory?: boolean, persistent?: boolean }): + DisplayMarkerLayer; + + /** Get a DisplayMarkerLayer by id. */ + getMarkerLayer(id: number): DisplayMarkerLayer|undefined; + + /** + * Get the default DisplayMarkerLayer. + * All marker APIs not tied to an explicit layer interact with this default layer. + */ + getDefaultMarkerLayer(): DisplayMarkerLayer; + + /** Get the DisplayMarker on the default layer for the given marker id. */ + getMarker(id: number): DisplayMarker; + + /** Get all DisplayMarkers on the default marker layer. Consider using ::findMarkers. */ + getMarkers(): DisplayMarker[]; + + /** Get the number of markers in the default marker layer. */ + getMarkerCount(): number; + + // Cursors + /** Get the position of the most recently added cursor in buffer coordinates. */ + getCursorBufferPosition(): Point; + + /** Get the position of all the cursor positions in buffer coordinates. */ + getCursorBufferPositions(): Point[]; + + /** + * Move the cursor to the given position in buffer coordinates. + * If there are multiple cursors, they will be consolidated to a single cursor. + */ + setCursorBufferPosition(position: PointCompatible, options?: { autoscroll?: boolean }): + void; + + /** Get a Cursor at given screen coordinates Point. */ + getCursorAtScreenPosition(position: PointCompatible): Cursor|undefined; + + /** Get the position of the most recently added cursor in screen coordinates. */ + getCursorScreenPosition(): Point; + + /** Get the position of all the cursor positions in screen coordinates. */ + getCursorScreenPositions(): Point[]; + + /** + * Move the cursor to the given position in screen coordinates. + * If there are multiple cursors, they will be consolidated to a single cursor. + */ + setCursorScreenPosition(position: PointCompatible, options?: { autoscroll?: boolean }): + void; + + /** Add a cursor at the given position in buffer coordinates. */ + addCursorAtBufferPosition(bufferPosition: PointCompatible): Cursor; + + /** Add a cursor at the position in screen coordinates. */ + addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor; + + /** Returns a boolean indicating whether or not there are multiple cursors. */ + hasMultipleCursors(): boolean; + + /** Move every cursor up one row in screen coordinates. */ + moveUp(lineCount?: number): void; + + /** Move every cursor down one row in screen coordinates. */ + moveDown(lineCount?: number): void; + + /** Move every cursor left one column. */ + moveLeft(columnCount?: number): void; + + /** Move every cursor right one column. */ + moveRight(columnCount?: number): void; + + /** Move every cursor to the beginning of its line in buffer coordinates. */ + moveToBeginningOfLine(): void; + + /** Move every cursor to the beginning of its line in screen coordinates. */ + moveToBeginningOfScreenLine(): void; + + /** Move every cursor to the first non-whitespace character of its line. */ + moveToFirstCharacterOfLine(): void; + + /** Move every cursor to the end of its line in buffer coordinates. */ + moveToEndOfLine(): void; + + /** Move every cursor to the end of its line in screen coordinates. */ + moveToEndOfScreenLine(): void; + + /** Move every cursor to the beginning of its surrounding word. */ + moveToBeginningOfWord(): void; + + /** Move every cursor to the end of its surrounding word. */ + moveToEndOfWord(): void; + + /** + * Move every cursor to the top of the buffer. + * If there are multiple cursors, they will be merged into a single cursor. + */ + moveToTop(): void; + + /** + * Move every cursor to the bottom of the buffer. + * If there are multiple cursors, they will be merged into a single cursor. + */ + moveToBottom(): void; + + /** Move every cursor to the beginning of the next word. */ + moveToBeginningOfNextWord(): void; + + /** Move every cursor to the previous word boundary. */ + moveToPreviousWordBoundary(): void; + + /** Move every cursor to the next word boundary. */ + moveToNextWordBoundary(): void; + + /** Move every cursor to the previous subword boundary. */ + moveToPreviousSubwordBoundary(): void; + + /** Move every cursor to the next subword boundary. */ + moveToNextSubwordBoundary(): void; + + /** Move every cursor to the beginning of the next paragraph. */ + moveToBeginningOfNextParagraph(): void; + + /** Move every cursor to the beginning of the previous paragraph. */ + moveToBeginningOfPreviousParagraph(): void; + + /** Returns the most recently added Cursor. */ + getLastCursor(): Cursor; + + /** Returns the word surrounding the most recently added cursor. */ + getWordUnderCursor(options?: { + wordRegex?: RegExp, + includeNonWordCharacters?: boolean, + allowPrevious?: boolean, + }): string; + + /** Get an Array of all Cursors. */ + getCursors(): Cursor[]; + + /** + * Get all Cursorss, ordered by their position in the buffer instead of the + * order in which they were added. + */ + getCursorsOrderedByBufferPosition(): Cursor[]; + + // Selections + /** Get the selected text of the most recently added selection. */ + getSelectedText(): string; + + /** Get the Range of the most recently added selection in buffer coordinates. */ + getSelectedBufferRange(): Range; + + /** + * Get the Ranges of all selections in buffer coordinates. + * The ranges are sorted by when the selections were added. Most recent at the end. + */ + getSelectedBufferRanges(): Range[]; + + /** + * Set the selected range in buffer coordinates. If there are multiple selections, + * they are reduced to a single selection with the given range. + */ + setSelectedBufferRange(bufferRange: RangeCompatible, options?: + { reversed?: boolean, preserveFolds?: boolean}): void; + + /** + * Set the selected ranges in buffer coordinates. If there are multiple selections, + * they are replaced by new selections with the given ranges. + */ + setSelectedBufferRanges(bufferRanges: ReadonlyArray, options?: + { reversed?: boolean, preserveFolds?: boolean}): void; + + /** Get the Range of the most recently added selection in screen coordinates. */ + getSelectedScreenRange(): Range; + + /** + * Get the Ranges of all selections in screen coordinates. + * The ranges are sorted by when the selections were added. Most recent at the end. + */ + getSelectedScreenRanges(): Range[]; + + /** + * Set the selected range in screen coordinates. If there are multiple selections, + * they are reduced to a single selection with the given range. + */ + setSelectedScreenRange(screenRange: RangeCompatible, options?: { reversed?: boolean }): + void; + + /** + * Set the selected ranges in screen coordinates. If there are multiple selections, + * they are replaced by new selections with the given ranges. + */ + setSelectedScreenRanges(screenRanges: ReadonlyArray, options?: + { reversed?: boolean }): void; + + /** Add a selection for the given range in buffer coordinates. */ + addSelectionForBufferRange(bufferRange: RangeCompatible, options?: + { reversed?: boolean, preserveFolds?: boolean }): Selection; + + /** Add a selection for the given range in screen coordinates. */ + addSelectionForScreenRange(screenRange: RangeCompatible, options?: + { reversed?: boolean, preserveFolds?: boolean }): Selection; + + /** + * Select from the current cursor position to the given position in buffer coordinates. + * This method may merge selections that end up intersecting. + */ + selectToBufferPosition(position: PointCompatible): void; + + /** + * Select from the current cursor position to the given position in screen coordinates. + * This method may merge selections that end up intersecting. + */ + selectToScreenPosition(position: PointCompatible): void; + + /** + * Move the cursor of each selection one character upward while preserving the + * selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectUp(rowCount?: number): void; + + /** + * Move the cursor of each selection one character downward while preserving + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectDown(rowCount?: number): void; + + /** + * Move the cursor of each selection one character leftward while preserving + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectLeft(columnCount?: number): void; + + /** + * Move the cursor of each selection one character rightward while preserving + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectRight(columnCount?: number): void; + + /** + * Select from the top of the buffer to the end of the last selection in the buffer. + * This method merges multiple selections into a single selection. + */ + selectToTop(): void; + + /** + * Selects from the top of the first selection in the buffer to the end of the buffer. + * This method merges multiple selections into a single selection. + */ + selectToBottom(): void; + + /** + * Select all text in the buffer. + * This method merges multiple selections into a single selection. + */ + selectAll(): void; + + /** + * Move the cursor of each selection to the beginning of its line while preserving + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToBeginningOfLine(): void; + + /** + * Move the cursor of each selection to the first non-whitespace character of its + * line while preserving the selection's tail position. If the cursor is already + * on the first character of the line, move it to the beginning of the line. + * This method may merge selections that end up intersecting. + */ + selectToFirstCharacterOfLine(): void; + + /** + * Move the cursor of each selection to the end of its line while preserving the + * selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToEndOfLine(): void; + + /** + * Expand selections to the beginning of their containing word. + * Operates on all selections. Moves the cursor to the beginning of the containing + * word while preserving the selection's tail position. + */ + selectToBeginningOfWord(): void; + + /** + * Expand selections to the end of their containing word. + * Operates on all selections. Moves the cursor to the end of the containing word + * while preserving the selection's tail position. + */ + selectToEndOfWord(): void; + + /** + * For each cursor, select the containing line. + * This method merges selections on successive lines. + */ + selectLinesContainingCursors(): void; + + /** Select the word surrounding each cursor. */ + selectWordsContainingCursors(): void; + + /** + * For each selection, move its cursor to the preceding subword boundary while + * maintaining the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToPreviousSubwordBoundary(): void; + + /** + * For each selection, move its cursor to the next subword boundary while maintaining + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToNextSubwordBoundary(): void; + + /** + * For each selection, move its cursor to the preceding word boundary while + * maintaining the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToPreviousWordBoundary(): void; + + /** + * For each selection, move its cursor to the next word boundary while maintaining + * the selection's tail position. + * This method may merge selections that end up intersecting. + */ + selectToNextWordBoundary(): void; + + /** + * Expand selections to the beginning of the next word. + * Operates on all selections. Moves the cursor to the beginning of the next word + * while preserving the selection's tail position. + */ + selectToBeginningOfNextWord(): void; + + /** + * Expand selections to the beginning of the next paragraph. + * Operates on all selections. Moves the cursor to the beginning of the next + * paragraph while preserving the selection's tail position. + */ + selectToBeginningOfNextParagraph(): void; + + /** + * Expand selections to the beginning of the next paragraph. + * Operates on all selections. Moves the cursor to the beginning of the next + * paragraph while preserving the selection's tail position. + */ + selectToBeginningOfPreviousParagraph(): void; + + /** Select the range of the given marker if it is valid. */ + selectMarker(marker: DisplayMarker): Range|undefined; + + /** Get the most recently added Selection. */ + getLastSelection(): Selection; + + /** Get current Selections. */ + getSelections(): Selection[]; + + /** + * Get all Selections, ordered by their position in the buffer instead of the + * order in which they were added. + */ + getSelectionsOrderedByBufferPosition(): Selection[]; + + // NOTE: this calls into Selection::intersectsBufferRange, which itself calls + // into Range::intersectsWith. Range::intersectsWith is one of the few functions + // which does NOT take a range-compatible array. + /** Determine if a given range in buffer coordinates intersects a selection. */ + selectionIntersectsBufferRange(bufferRange: RangeLike): boolean; + + // Searching and Replacing + /** + * Scan regular expression matches in the entire buffer, calling the given + * iterator function on each match. + * + * ::scan functions as the replace method as well via the replace. + */ + scan(regex: RegExp, options: ScanContextOptions, iterator: (params: + ContextualBufferScanResult) => void): void; + /** + * Scan regular expression matches in the entire buffer, calling the given + * iterator function on each match. + * + * ::scan functions as the replace method as well via the replace. + */ + scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void; + + /** + * Scan regular expression matches in a given range, calling the given iterator. + * function on each match. + */ + scanInBufferRange(regex: RegExp, range: RangeCompatible, iterator: + (params: BufferScanResult) => void): void; + + /** + * Scan regular expression matches in a given range in reverse order, calling the + * given iterator function on each match. + */ + backwardsScanInBufferRange(regex: RegExp, range: RangeCompatible, + iterator: (params: BufferScanResult) => void): void; + + // Tab Behavior + /** Returns a boolean indicating whether softTabs are enabled for this editor. */ + getSoftTabs(): boolean; + + /** Enable or disable soft tabs for this editor. */ + setSoftTabs(softTabs: boolean): void; + + /** Toggle soft tabs for this editor. */ + toggleSoftTabs(): boolean; + + /** Get the on-screen length of tab characters. */ + getTabLength(): number; + + /** + * Set the on-screen length of tab characters. Setting this to a number will + * override the editor.tabLength setting. + */ + setTabLength(tabLength: number): void; + + /** Determine if the buffer uses hard or soft tabs. */ + usesSoftTabs(): boolean|undefined; + + /** + * Get the text representing a single level of indent. + * If soft tabs are enabled, the text is composed of N spaces, where N is the + * tab length. Otherwise the text is a tab character (\t). + */ + getTabText(): string; + + // Soft Wrap Behavior + /** Determine whether lines in this editor are soft-wrapped. */ + isSoftWrapped(): boolean; + + /** Enable or disable soft wrapping for this editor. */ + setSoftWrapped(softWrapped: boolean): boolean; + + /** Toggle soft wrapping for this editor. */ + toggleSoftWrapped(): boolean; + + /** Gets the column at which column will soft wrap. */ + getSoftWrapColumn(): number; + + // Indentation + /** + * Get the indentation level of the given buffer row. + * Determines how deeply the given row is indented based on the soft tabs and tab + * length settings of this editor. Note that if soft tabs are enabled and the tab + * length is 2, a row with 4 leading spaces would have an indentation level of 2. + */ + indentationForBufferRow(bufferRow: number): number; + + /** + * Set the indentation level for the given buffer row. + * Inserts or removes hard tabs or spaces based on the soft tabs and tab length settings + * of this editor in order to bring it to the given indentation level. Note that if soft + * tabs are enabled and the tab length is 2, a row with 4 leading spaces would have an + * indentation level of 2. + */ + setIndentationForBufferRow(bufferRow: number, newLevel: number, options?: + { preserveLeadingWhitespace?: boolean }): void; + + /** Indent rows intersecting selections by one level. */ + indentSelectedRows(): void; + + /** Outdent rows intersecting selections by one level. */ + outdentSelectedRows(): void; + + /** + * Get the indentation level of the given line of text. + * Determines how deeply the given line is indented based on the soft tabs and tab length + * settings of this editor. Note that if soft tabs are enabled and the tab length is 2, + * a row with 4 leading spaces would have an indentation level of 2. + */ + indentLevelForLine(line: string): number; + + /** Indent rows intersecting selections based on the grammar's suggested indent level. */ + autoIndentSelectedRows(): void; + + // Grammars + /** Get the current Grammar of this editor. */ + getGrammar(): Grammar; + + /** + * Set the current Grammar of this editor. + * Assigning a grammar will cause the editor to re-tokenize based on the new grammar. + */ + setGrammar(grammar: Grammar): void; + + // Managing Syntax Scopes + /** + * Returns a ScopeDescriptor that includes this editor's language. + * e.g. [".source.ruby"], or [".source.coffee"]. + */ + getRootScopeDescriptor(): ScopeDescriptor; + + /** Get the syntactic scopeDescriptor for the given position in buffer coordinates. */ + scopeDescriptorForBufferPosition(bufferPosition: PointCompatible): ScopeDescriptor; + + /** + * Get the range in buffer coordinates of all tokens surrounding the cursor + * that match the given scope selector. + */ + bufferRangeForScopeAtCursor(scopeSelector: string): Range; + + /** Determine if the given row is entirely a comment. */ + isBufferRowCommented(bufferRow: number): boolean; + + // Clipboard Operations + /** For each selection, copy the selected text. */ + copySelectedText(): void; + + /** For each selection, cut the selected text. */ + cutSelectedText(): void; + + /** + * For each selection, replace the selected text with the contents of the clipboard. + * If the clipboard contains the same number of selections as the current editor, + * each selection will be replaced with the content of the corresponding clipboard + * selection text. + */ + pasteText(options?: TextInsertionOptions): void; + + /** + * For each selection, if the selection is empty, cut all characters of the + * containing screen line following the cursor. Otherwise cut the selected text. + */ + cutToEndOfLine(): void; + + /** + * For each selection, if the selection is empty, cut all characters of the + * containing buffer line following the cursor. Otherwise cut the selected text. + */ + cutToEndOfBufferLine(): void; + + // Folds + /** + * Fold the most recent cursor's row based on its indentation level. + * The fold will extend from the nearest preceding line with a lower indentation + * level up to the nearest following row with a lower indentation level. + */ + foldCurrentRow(): void; + + /** Unfold the most recent cursor's row by one level. */ + unfoldCurrentRow(): void; + + /** + * Fold the given row in buffer coordinates based on its indentation level. + * If the given row is foldable, the fold will begin there. Otherwise, it will + * begin at the first foldable row preceding the given row. + */ + foldBufferRow(bufferRow: number): void; + + /** Unfold all folds containing the given row in buffer coordinates. */ + unfoldBufferRow(bufferRow: number): void; + + /** For each selection, fold the rows it intersects. */ + foldSelectedLines(): void; + + /** Fold all foldable lines. */ + foldAll(): void; + + /** Unfold all existing folds. */ + unfoldAll(): void; + + /** Fold all foldable lines at the given indent level. */ + foldAllAtIndentLevel(level: number): void; + + /** + * Determine whether the given row in buffer coordinates is foldable. + * A foldable row is a row that starts a row range that can be folded. + */ + isFoldableAtBufferRow(bufferRow: number): boolean; + + /** + * Determine whether the given row in screen coordinates is foldable. + * A foldable row is a row that starts a row range that can be folded. + */ + isFoldableAtScreenRow(bufferRow: number): boolean; + + /** Fold the given buffer row if it isn't currently folded, and unfold it otherwise. */ + toggleFoldAtBufferRow(bufferRow: number): void; + + /** Determine whether the most recently added cursor's row is folded. */ + isFoldedAtCursorRow(): boolean; + + /** Determine whether the given row in buffer coordinates is folded. */ + isFoldedAtBufferRow(bufferRow: number): boolean; + + /** Determine whether the given row in screen coordinates is folded. */ + isFoldedAtScreenRow(screenRow: number): boolean; + + // Gutters + /** Add a custom Gutter. */ + addGutter(options: { + name: string, + priority?: number, + visible?: boolean, + }): Gutter; + + /** Get this editor's gutters. */ + getGutters(): Gutter[]; + + /** Get the gutter with the given name. */ + gutterWithName(name: string): Gutter|null; + + // Scrolling the TextEditor + /** Scroll the editor to reveal the most recently added cursor if it is off-screen. */ + scrollToCursorPosition(options?: { center?: boolean }): void; + + /** Scrolls the editor to the given buffer position. */ + scrollToBufferPosition(bufferPosition: PointCompatible, options?: { center?: boolean }): + void; + + /** Scrolls the editor to the given screen position. */ + scrollToScreenPosition(screenPosition: PointCompatible, options?: { center?: boolean }): + void; + + // TextEditor Rendering + /** Retrieves the rendered line height in pixels. */ + getLineHeightInPixels(): number; + + /** Retrieves the greyed out placeholder of a mini editor. */ + getPlaceholderText(): string; + + /** + * Set the greyed out placeholder of a mini editor. Placeholder text will be + * displayed when the editor has no content. + */ + setPlaceholderText(placeholderText: string): void; +} + +/** Experimental: This global registry tracks registered TextEditors. */ +export interface TextEditorRegistry { + // Managing Text Editors + /** Remove all editors from the registry. */ + clear(): void; + + /** Register a TextEditor. */ + add(editor: TextEditor): Disposable; + + /** Remove the given TextEditor from the registry. */ + remove(editor: TextEditor): boolean; + + /** Keep a TextEditor's configuration in sync with Atom's settings. */ + maintainConfig(editor: TextEditor): Disposable; + + /** + * Set a TextEditor's grammar based on its path and content, and continue + * to update its grammar as gramamrs are added or updated, or the editor's + * file path changes. + */ + maintainGrammar(editor: TextEditor): Disposable; + + /** + * Force a TextEditor to use a different grammar than the one that would + * otherwise be selected for it. + */ + setGrammarOverride(editor: TextEditor, scopeName: string): void; + + /** + * Retrieve the grammar scope name that has been set as a grammar override + * for the given TextEditor. + */ + getGrammarOverride(editor: TextEditor): string|null; + + /** Remove any grammar override that has been set for the given TextEditor. */ + clearGrammarOverride(editor: TextEditor): void; + + // Event Subscription + /** Invoke the given callback with all the current and future registered TextEditors. */ + observe(callback: (editor: TextEditor) => void): Disposable; +} + +/** Associates tooltips with HTML elements or selectors. */ +export interface TooltipManager { + /** Add a tooltip to the given element. */ + add(target: HTMLElement, options: { + title?: string, + html?: boolean, + item?: HTMLElement|{ element: HTMLElement }, + class?: string, + placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), + trigger?: "click"|"hover"|"focus"|"manual", + delay?: { show: number, hide: number }, + keyBindingCommand?: string, + keyBindingTarget?: HTMLElement + } | { + title?: string|(() => string), + html?: boolean, + item?: HTMLElement|{ element: HTMLElement }, + class?: string, + placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string), + trigger?: "click"|"hover"|"focus"|"manual", + delay?: { show: number, hide: number }, + }): Disposable; + + /** Find the tooltips that have been applied to the given element. */ + findTooltips(target: HTMLElement): Tooltip[]; +} + +/** + * ViewRegistry handles the association between model and view types in Atom. + * We call this association a View Provider. As in, for a given model, this class + * can provide a view via ::getView, as long as the model/view association was + * registered via ::addViewProvider. + */ +export interface ViewRegistry { + /** + * Add a provider that will be used to construct views in the workspace's view + * layer based on model objects in its model layer. + */ + addViewProvider(createView: (model: object) => HTMLElement|undefined): Disposable; + /** + * Add a provider that will be used to construct views in the workspace's view + * layer based on model objects in its model layer. + */ + // tslint:disable-next-line:no-any + addViewProvider(modelConstructor: { new (...args: any[]): T }, createView: + (instance: T) => HTMLElement|undefined): Disposable; + + /** Get the view associated with an object in the workspace. */ + getView(obj: object): HTMLElement; +} + +/** Represents the state of the user interface for the entire window. */ +export interface Workspace { + // Event Subscription + /** + * Invoke the given callback with all current and future text editors in + * the workspace. + */ + observeTextEditors(callback: (editor: TextEditor) => void): Disposable; + + /** + * Invoke the given callback with all current and future panes items in the + * workspace. + */ + observePaneItems(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the active pane item changes. */ + onDidChangeActivePaneItem(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the active pane item stops changing. */ + onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable; + + /** + * Invoke the given callback when a text editor becomes the active text editor and + * when there is no longer an active text editor. + */ + onDidChangeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable; + + /** + * Invoke the given callback with the current active pane item and with all + * future active pane items in the workspace. + */ + observeActivePaneItem(callback: (item: object) => void): Disposable; + + /** + * Invoke the given callback with the current active text editor (if any), with all + * future active text editors, and when there is no longer an active text editor. + */ + observeActiveTextEditor(callback: (editor?: TextEditor) => void): Disposable; + + /** + * Invoke the given callback whenever an item is opened. Unlike ::onDidAddPaneItem, + * observers will be notified for items that are already present in the workspace + * when they are reopened. + */ + onDidOpen(callback: (event: PaneItemOpenedEvent) => void): Disposable; + + /** Invoke the given callback when a pane is added to the workspace. */ + onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback before a pane is destroyed in the workspace. */ + onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback when a pane is destroyed in the workspace. */ + onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback with all current and future panes in the workspace. */ + observePanes(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when the active pane changes. */ + onDidChangeActivePane(callback: (pane: Pane) => void): Disposable; + + /** + * Invoke the given callback with the current active pane and when the + * active pane changes. + */ + observeActivePane(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when a pane item is added to the workspace. */ + onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + /** + * Invoke the given callback when a pane item is about to be destroyed, + * before the user is prompted to save it. + * @param callback The function to be called before pane items are destroyed. + * If this function returns a Promise, then the item will not be destroyed + * until the promise resolves. + */ + onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise): + Disposable; + + /** Invoke the given callback when a pane item is destroyed. */ + onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + /** Invoke the given callback when a text editor is added to the workspace. */ + onDidAddTextEditor(callback: (event: TextEditorObservedEvent) => void): Disposable; + + // Opening + /** + * Opens the given URI in Atom asynchronously. If the URI is already open, + * the existing item for that URI will be activated. If no URI is given, or + * no registered opener can open the URI, a new empty TextEditor will be created. + */ + open(uri: string, options?: WorkspaceOpenOptions): Promise; + /** + * Opens the given item in Atom asynchronously. If the item is already open, + * the existing item will be activated. If no item is given, a new empty TextEditor + * will be created. + */ + open(item: T, options?: WorkspaceOpenOptions): + Promise; + /** + * Opens the given URI in Atom asynchronously. If the URI is already open, + * the existing item for that URI will be activated. If no URI is given, or + * no registered opener can open the URI, a new empty TextEditor will be created. + */ + open(): Promise; + + /** + * Search the workspace for items matching the given URI and hide them. + * Returns a boolean indicating whether any items were found (and hidden). + */ + hide(itemOrURI: object|string): boolean; + + /** + * Search the workspace for items matching the given URI. If any are found, + * hide them. Otherwise, open the URL. + * Returns a Promise that resolves when the item is shown or hidden. + */ + toggle(itemOrURI: object|string): Promise; + + /** + * Creates a new item that corresponds to the provided URI. + * If no URI is given, or no registered opener can open the URI, a new empty TextEditor + * will be created. + */ + createItemForURI(uri: string): Promise; + + /** Returns a boolean that is true if object is a TextEditor. */ + isTextEditor(object: object): boolean; + + /** + * Asynchronously reopens the last-closed item's URI if it hasn't already + * been reopened. + */ + reopenItem(): Promise; + + /** Register an opener for a URI. */ + addOpener(opener: (uri: string, options?: WorkspaceOpenOptions) => + ViewModel|undefined): Disposable; + + /** Create a new text editor. */ + buildTextEditor(params: object): TextEditor; + + // Pane Items + /** Get all pane items in the workspace. */ + getPaneItems(): object[]; + + /** Get the active Pane's active item. */ + getActivePaneItem(): object; + + /** Get all text editors in the workspace. */ + getTextEditors(): TextEditor[]; + + /** Get the workspace center's active item if it is a TextEditor. */ + getActiveTextEditor(): TextEditor|undefined; + + // Panes + /** Get the most recently focused pane container. */ + getActivePaneContainer(): Dock|WorkspaceCenter; + + /** Get all panes in the workspace. */ + getPanes(): Pane[]; + + /** Get the active Pane. */ + getActivePane(): Pane; + + /** Make the next pane active. */ + activateNextPane(): boolean; + + /** Make the previous pane active. */ + activatePreviousPane(): boolean; + + /** Get the first pane container that contains an item with the given URI. */ + paneContainerForURI(uri: string): Dock|WorkspaceCenter|undefined; + + /** Get the first pane container that contains the given item. */ + paneContainerForItem(item: object): Dock|WorkspaceCenter|undefined; + + /** Get the first Pane with an item for the given URI. */ + paneForURI(uri: string): Pane|undefined; + + /** Get the Pane containing the given item. */ + paneForItem(item: object): Pane|undefined; + + // Pane Locations + /** Get the WorkspaceCenter at the center of the editor window. */ + getCenter(): WorkspaceCenter; + + /** Get the Dock to the left of the editor window. */ + getLeftDock(): Dock; + + /** Get the Dock to the right of the editor window. */ + getRightDock(): Dock; + + /** Get the Dock below the editor window. */ + getBottomDock(): Dock; + + /** Returns all Pane containers. */ + getPaneContainers(): [WorkspaceCenter, Dock, Dock, Dock]; + + // Panels + /** Get an Array of all the panel items at the bottom of the editor window. */ + getBottomPanels(): Panel[]; + + /** Adds a panel item to the bottom of the editor window. */ + addBottomPanel(options: { + item: T, + visible?: boolean, + priority?: number, + }): Panel; + + /** Get an Array of all the panel items to the left of the editor window. */ + getLeftPanels(): Panel[]; + + /** Adds a panel item to the left of the editor window. */ + addLeftPanel(options: { + item: T, + visible?: boolean, + priority?: number, + }): Panel; + + /** Get an Array of all the panel items to the right of the editor window. */ + getRightPanels(): Panel[]; + + /** Adds a panel item to the right of the editor window. */ + addRightPanel(options: { + item: T, + visible?: boolean, + priority?: number, + }): Panel; + + /** Get an Array of all the panel items at the top of the editor window. */ + getTopPanels(): Panel[]; + + /** Adds a panel item to the top of the editor window above the tabs. */ + addTopPanel(options: { + item: T, + visible?: boolean, + priority?: number + }): Panel; + + /** Get an Array of all the panel items in the header. */ + getHeaderPanels(): Panel[]; + + /** Adds a panel item to the header. */ + addHeaderPanel(options: { + item: T, + visible?: boolean, + priority?: number, + }): Panel; + + /** Get an Array of all the panel items in the footer. */ + getFooterPanels(): Panel[]; + + /** Adds a panel item to the footer. */ + addFooterPanel(options: { + item: T, + visible?: boolean, + priority?: number, + }): Panel; + + /** Get an Array of all the modal panel items. */ + getModalPanels(): Panel[]; + + /** Adds a panel item as a modal dialog. */ + addModalPanel(options: { + item: T, + visible?: boolean, + priority?: number, + autoFocus?: boolean, + }): Panel; + + /** + * Returns the Panel associated with the given item or null when the item + * has no panel. + */ + panelForItem(item: T): Panel|null; + + // Searching and Replacing + /** Performs a search across all files in the workspace. */ + scan(regex: RegExp, iterator: (result: ScandalResult) => void): + CancellablePromise; + /** Performs a search across all files in the workspace. */ + scan(regex: RegExp, options: WorkspaceScanOptions, iterator: + (result: ScandalResult) => void): CancellablePromise; + + /** Performs a replace across all the specified files in the project. */ + replace(regex: RegExp, replacementText: string, filePaths: ReadonlyArray, + iterator: (result: { filePath: string|undefined, replacements: number }) => void): + Promise; +} + +// https://github.com/atom/atom/blob/master/src/workspace-center.js +/** The central container for the editor window capable of holding items. */ +export interface WorkspaceCenter { + // Event Subscription + /** + * Invoke the given callback with all current and future text editors in the + * workspace center. + */ + observeTextEditors(callback: (editor: TextEditor) => void): Disposable; + + /** + * Invoke the given callback with all current and future panes items in the + * workspace center. + */ + observePaneItems(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the active pane item changes. */ + onDidChangeActivePaneItem(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the active pane item stops changing. */ + onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable; + + /** + * Invoke the given callback with the current active pane item and with all future + * active pane items in the workspace center. + */ + observeActivePaneItem(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when a pane is added to the workspace center. */ + onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback before a pane is destroyed in the workspace center. */ + onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback when a pane is destroyed in the workspace center. */ + onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback with all current and future panes in the workspace center. */ + observePanes(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when the active pane changes. */ + onDidChangeActivePane(callback: (pane: Pane) => void): Disposable; + + /** + * Invoke the given callback with the current active pane and when the active pane + * changes. + */ + observeActivePane(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when a pane item is added to the workspace center. */ + onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + /** + * Invoke the given callback when a pane item is about to be destroyed, before the user + * is prompted to save it. + * @param callback The function to be called before pane items are destroyed. + * If this function returns a Promise, then the item will not be destroyed + * until the promise resolves. + */ + onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise): + Disposable; + + /** Invoke the given callback when a pane item is destroyed. */ + onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + /** Invoke the given callback when a text editor is added to the workspace center. */ + onDidAddTextEditor(callback: (event: TextEditorObservedEvent) => void): Disposable; + + // Pane Items + /** Get all pane items in the workspace center. */ + getPaneItems(): object[]; + + /** Get the active Pane's active item. */ + getActivePaneItem(): object|undefined; + + /** Get all text editors in the workspace center. */ + getTextEditors(): TextEditor[]; + + /** Get the active item if it is an TextEditor. */ + getActiveTextEditor(): TextEditor|undefined; + + /** Save all pane items. */ + saveAll(): void; + + // Panes + /** Get all panes in the workspace center. */ + getPanes(): Pane[]; + + /** Get the active Pane. */ + getActivePane(): Pane; + + /** Make the next pane active. */ + activateNextPane(): void; + + /** Make the previous pane active. */ + activatePreviousPane(): void; + + /** Retrieve the Pane associated with the given URI. */ + paneForURI(uri: string): Pane|undefined; + + /** Retrieve the Pane associated with the given item. */ + paneForItem(item: object): Pane|undefined; + + /** Destroy (close) the active pane. */ + destroyActivePane(): void; +} + +// Extended Classes =========================================================== + +/** + * A wrapper which provides standard error/output line buffering for + * Node's ChildProcess. + */ +export class BufferedProcess { + process?: ChildProcess; + + constructor(options: ProcessOptions); + + // Event Subscription + /** + * Will call your callback when an error will be raised by the process. Usually + * this is due to the command not being available or not on the PATH. You can + * call handle() on the object passed to your callback to indicate that you + * have handled this error. + */ + onWillThrowError(callback: (errorObject: HandleableErrorEvent) => + void): Disposable; + + // Helper Methods + /** Terminate the process. */ + kill(): void; + + /** Runs the process. */ + start(): void; +} + +/** + * Like BufferedProcess, but accepts a Node script as the command to run. + * This is necessary on Windows since it doesn't support shebang #! lines. + */ +export class BufferedNodeProcess extends BufferedProcess { + /** Runs the given Node script by spawning a new child process. */ + constructor(options: NodeProcessOptions); +} + +/** Represents the clipboard used for copying and pasting in Atom. */ +export interface Clipboard { + /** Write the given text to the clipboard. */ + write(text: string, metadata?: object): void; + + /** Read the text from the clipboard. */ + read(): string; + + /** + * Read the text from the clipboard and return both the text and the associated + * metadata. + */ + readWithMetadata(): { text: string, metadata: object }; +} + +/** Provides a registry for commands that you'd like to appear in the context menu. */ +export interface ContextMenuManager { + /** Add context menu items scoped by CSS selectors. */ + add(itemsBySelector: { [key: string]: ReadonlyArray }): Disposable; +} + +/** + * The Cursor class represents the little blinking line identifying where text + * can be inserted. + */ +export interface Cursor { + // Event Subscription + /** Calls your callback when the cursor has been moved. */ + onDidChangePosition(callback: (event: CursorPositionChangedEvent) => void): Disposable; + + /** Calls your callback when the cursor is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** Calls your callback when the cursor's visibility has changed. */ + onDidChangeVisibility(callback: (visibility: boolean) => void): Disposable; + + // Managing Cursor Position + /** Moves a cursor to a given screen position. */ + setScreenPosition(screenPosition: PointCompatible, options?: { autoscroll?: boolean }): + void; + + /** Returns the screen position of the cursor as a Point. */ + getScreenPosition(): Point; + + /** Moves a cursor to a given buffer position. */ + setBufferPosition(bufferPosition: PointCompatible, options?: { autoscroll?: boolean }): + void; + + /** Returns the current buffer position as an Array. */ + getBufferPosition(): Point; + + /** Returns the cursor's current screen row. */ + getScreenRow(): number; + + /** Returns the cursor's current screen column. */ + getScreenColumn(): number; + + /** Retrieves the cursor's current buffer row. */ + getBufferRow(): number; + + /** Returns the cursor's current buffer column. */ + getBufferColumn(): number; + + /** Returns the cursor's current buffer row of text excluding its line ending. */ + getCurrentBufferLine(): string; + + /** Returns whether the cursor is at the start of a line. */ + isAtBeginningOfLine(): boolean; + + /** Returns whether the cursor is on the line return character. */ + isAtEndOfLine(): boolean; + + // Cursor Position Details + /** + * Returns the underlying DisplayMarker for the cursor. Useful with overlay + * Decorations. + */ + getMarker(): DisplayMarker; + + /** + * Identifies if the cursor is surrounded by whitespace. + * "Surrounded" here means that the character directly before and after the cursor + * are both whitespace. + */ + isSurroundedByWhitespace(): boolean; + + /** This method returns false if the character before or after the cursor is whitespace. */ + isBetweenWordAndNonWord(): boolean; + + /** Returns whether this cursor is between a word's start and end. */ + isInsideWord(options?: { wordRegex?: RegExp }): boolean; + + /** Returns the indentation level of the current line. */ + getIndentLevel(): number; + + /** Retrieves the scope descriptor for the cursor's current position. */ + getScopeDescriptor(): ScopeDescriptor; + + /** + * Returns true if this cursor has no non-whitespace characters before its + * current position. + */ + hasPrecedingCharactersOnLine(): boolean; + + /** + * Identifies if this cursor is the last in the TextEditor. + * "Last" is defined as the most recently added cursor. + */ + isLastCursor(): boolean; + + // Moving the Cursor + /** Moves the cursor up one screen row. */ + moveUp(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void; + + /** Moves the cursor down one screen row. */ + moveDown(rowCount?: number, options?: { moveToEndOfSelection?: boolean }): void; + + /** Moves the cursor left one screen column. */ + moveLeft(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void; + + /** Moves the cursor right one screen column. */ + moveRight(columnCount?: number, options?: { moveToEndOfSelection?: boolean }): void; + + /** Moves the cursor to the top of the buffer. */ + moveToTop(): void; + + /** Moves the cursor to the bottom of the buffer. */ + moveToBottom(): void; + + /** Moves the cursor to the beginning of the line. */ + moveToBeginningOfScreenLine(): void; + + /** Moves the cursor to the beginning of the buffer line. */ + moveToBeginningOfLine(): void; + + /** Moves the cursor to the beginning of the first character in the line. */ + moveToFirstCharacterOfLine(): void; + + /** Moves the cursor to the end of the line. */ + moveToEndOfScreenLine(): void; + + /** Moves the cursor to the end of the buffer line. */ + moveToEndOfLine(): void; + + /** Moves the cursor to the beginning of the word. */ + moveToBeginningOfWord(): void; + + /** Moves the cursor to the end of the word. */ + moveToEndOfWord(): void; + + /** Moves the cursor to the beginning of the next word. */ + moveToBeginningOfNextWord(): void; + + /** Moves the cursor to the previous word boundary. */ + moveToPreviousWordBoundary(): void; + + /** Moves the cursor to the next word boundary. */ + moveToNextWordBoundary(): void; + + /** Moves the cursor to the previous subword boundary. */ + moveToPreviousSubwordBoundary(): void; + + /** Moves the cursor to the next subword boundary. */ + moveToNextSubwordBoundary(): void; + + /** Moves the cursor to the beginning of the buffer line, skipping all whitespace. */ + skipLeadingWhitespace(): void; + + /** Moves the cursor to the beginning of the next paragraph. */ + moveToBeginningOfNextParagraph(): void; + + /** Moves the cursor to the beginning of the previous paragraph. */ + moveToBeginningOfPreviousParagraph(): void; + + // Local Positions and Ranges + /** + * Returns buffer position of previous word boundary. It might be on the current + * word, or the previous word. + */ + getPreviousWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): Point; + + /** + * Returns buffer position of the next word boundary. It might be on the current + * word, or the previous word. + */ + getNextWordBoundaryBufferPosition(options?: { wordRegex?: RegExp }): Point; + + /** Retrieves the buffer position of where the current word starts. */ + getBeginningOfCurrentWordBufferPosition(options?: { + wordRegex?: RegExp, + includeNonWordCharacters?: boolean, + allowPrevious?: boolean + }): Point; + + /** Retrieves the buffer position of where the current word ends. */ + getEndOfCurrentWordBufferPosition(options?: { + wordRegex?: RegExp, + includeNonWordCharacters?: boolean + }): Point; + + /** Retrieves the buffer position of where the next word starts. */ + getBeginningOfNextWordBufferPosition(options?: { wordRegex?: RegExp }): Point; + + /** Returns the buffer Range occupied by the word located under the cursor. */ + getCurrentWordBufferRange(options?: { wordRegex?: RegExp }): Range; + + /** Returns the buffer Range for the current line. */ + getCurrentLineBufferRange(options?: { includeNewline?: boolean }): Range; + + /** + * Retrieves the range for the current paragraph. + * A paragraph is defined as a block of text surrounded by empty lines or comments. + */ + getCurrentParagraphBufferRange(): Range; + + /** Returns the characters preceding the cursor in the current word. */ + getCurrentWordPrefix(): string; + + // Visibility + /** Sets whether the cursor is visible. */ + setVisible(visible: boolean): void; + + /** Returns the visibility of the cursor. */ + isVisible(): boolean; + + // Comparing to another cursor + /** + * Compare this cursor's buffer position to another cursor's buffer position. + * See Point::compare for more details. + */ + compare(otherCursor: Cursor): number; + + // Utilities + /** Prevents this cursor from causing scrolling. */ + clearAutoscroll(): void; + + /** Deselects the current selection. */ + clearSelection(): void; + + /** Get the RegExp used by the cursor to determine what a "word" is. */ + wordRegExp(options?: { includeNonWordCharacters?: boolean }): RegExp; + + /** Get the RegExp used by the cursor to determine what a "subword" is. */ + subwordRegExp(options?: { backwards?: boolean }): RegExp; +} + +/** Manages the deserializers used for serialized state. */ +export interface DeserializerManager { + /** Register the given class(es) as deserializers. */ + add(...deserializers: Deserializer[]): Disposable; + + /** Deserialize the state and params. */ + deserialize(state: object): object|undefined; +} + +/** Represents a directory on disk that can be watched for changes. */ +export class Directory { + // Construction + /** Configures a new Directory instance, no files are accessed. */ + constructor(directoryPath: string, symlink?: boolean); + + /** + * Creates the directory on disk that corresponds to ::getPath() if no such + * directory already exists. + */ + create(mode?: number): Promise; + + // Event Subscription + /** Invoke the given callback when the directory's contents change. */ + onDidChange(callback: () => void): Disposable; + + // Directory Metadata + /** Returns a boolean, always false. */ + isFile(): boolean; + + /** Returns a roolean, always true. */ + isDirectory(): boolean; + + /** Returns a boolean indicating whether or not this is a symbolic link. */ + isSymbolicLink(): boolean; + + /** + * Returns a promise that resolves to a boolean, true if the directory + * exists, false otherwise. + */ + exists(): Promise; + + /** Returns a boolean, true if the directory exists, false otherwise. */ + existsSync(): boolean; + + /** + * Return a boolean, true if this Directory is the root directory of the + * filesystem, or false if it isn't. + */ + isRoot(): boolean; + + // Managing Paths + /** + * This may include unfollowed symlinks or relative directory entries. + * Or it may be fully resolved, it depends on what you give it. + */ + getPath(): string; + + /** + * All relative directory entries are removed and symlinks are resolved to + * their final destination. + */ + getRealPathSync(): string; + + /** Returns the string basename of the directory. */ + getBaseName(): string; + + /** Returns the relative string path to the given path from this directory. */ + relativize(fullPath: string): string; + + // Traversing + /** Traverse to the parent directory. */ + getParent(): Directory; + + /** + * Traverse within this Directory to a child File. This method doesn't actually + * check to see if the File exists, it just creates the File object. + */ + getFile(filename: string): File; + + /** + * Traverse within this a Directory to a child Directory. This method doesn't actually + * check to see if the Directory exists, it just creates the Directory object. + */ + getSubdirectory(dirname: string): Directory; + + /** Reads file entries in this directory from disk synchronously. */ + getEntriesSync(): Array; + + /** Reads file entries in this directory from disk asynchronously. */ + getEntries(callback: (error: Error, entries: Array) => void): void; + + /** + * Determines if the given path (real or symbolic) is inside this directory. This + * method does not actually check if the path exists, it just checks if the path + * is under this directory. + */ + contains(pathToCheck: string): boolean; +} + +/** A container at the edges of the editor window capable of holding items. */ +export interface Dock { + // Methods + /** Show the dock and focus its active Pane. */ + activate(): void; + + /** Show the dock without focusing it. */ + show(): void; + + /** + * Hide the dock and activate the WorkspaceCenter if the dock was was previously + * focused. + */ + hide(): void; + + /** + * Toggle the dock's visibility without changing the Workspace's active pane + * container. + */ + toggle(): void; + + /** Check if the dock is visible. */ + isVisible(): boolean; + + // Event Subscription + /** Invoke the given callback when the visibility of the dock changes. */ + onDidChangeVisible(callback: (visible: boolean) => void): Disposable; + + /** + * Invoke the given callback with the current and all future visibilities of + * the dock. + */ + observeVisible(callback: (visible: boolean) => void): Disposable; + + /** Invoke the given callback with all current and future panes items in the dock. */ + observePaneItems(callback: (item: object) => void): Disposable; + + /** + * Invoke the given callback when the active pane item changes. + * + * Because observers are invoked synchronously, it's important not to perform any + * expensive operations via this method. Consider ::onDidStopChangingActivePaneItem + * to delay operations until after changes stop occurring. + */ + onDidChangeActivePaneItem(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the active pane item stops changing. */ + onDidStopChangingActivePaneItem(callback: (item: object) => void): Disposable; + + /** + * Invoke the given callback with the current active pane item and with all future + * active pane items in the dock. + */ + observeActivePaneItem(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when a pane is added to the dock. */ + onDidAddPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback before a pane is destroyed in the dock. */ + onWillDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback when a pane is destroyed in the dock. */ + onDidDestroyPane(callback: (event: { pane: Pane }) => void): Disposable; + + /** Invoke the given callback with all current and future panes in the dock. */ + observePanes(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when the active pane changes. */ + onDidChangeActivePane(callback: (pane: Pane) => void): Disposable; + + /** + * Invoke the given callback with the current active pane and when the active + * pane changes. + */ + observeActivePane(callback: (pane: Pane) => void): Disposable; + + /** Invoke the given callback when a pane item is added to the dock. */ + onDidAddPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + /** + * Invoke the given callback when a pane item is about to be destroyed, before the user is + * prompted to save it. + * @param callback The function to be called before pane items are destroyed. + * If this function returns a Promise, then the item will not be destroyed + * until the promise resolves. + */ + onWillDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void|Promise): + Disposable; + + /** Invoke the given callback when a pane item is destroyed. */ + onDidDestroyPaneItem(callback: (event: PaneItemObservedEvent) => void): Disposable; + + // Pane Items + /** Get all pane items in the dock. */ + getPaneItems(): object[]; + + /** Get the active Pane's active item. */ + getActivePaneItem(): object; + + // Panes + /** Returns an Array of Panes. */ + getPanes(): Pane[]; + + /** Get the active Pane. */ + getActivePane(): Pane; + + /** Make the next pane active. */ + activateNextPane(): boolean; + + /** Make the previous pane active. */ + activatePreviousPane(): boolean; +} + +/** Represents an individual file that can be watched, read from, and written to. */ +export class File { + // Construction + /** Configures a new File instance, no files are accessed. */ + constructor(filePath: string, symlink?: boolean); + + /** + * Creates the file on disk that corresponds to ::getPath() if no such file + * already exists. + */ + create(): Promise; + + // Event Subscription + /** Invoke the given callback when the file's contents change. */ + onDidChange(callback: () => void): Disposable; + + /** Invoke the given callback when the file's path changes. */ + onDidRename(callback: () => void): Disposable; + + /** Invoke the given callback when the file is deleted. */ + onDidDelete(callback: () => void): Disposable; + + /** + * Invoke the given callback when there is an error with the watch. When + * your callback has been invoked, the file will have unsubscribed from the + * file watches. + */ + onWillThrowWatchError(callback: (event: PathWatchErrorThrownEvent) => + void): Disposable; + + // File Metadata + /** Returns a boolean, always true. */ + isFile(): boolean; + + /** Returns a boolean, always false. */ + isDirectory(): boolean; + + /** Returns a boolean indicating whether or not this is a symbolic link. */ + isSymbolicLink(): boolean; + + /** + * Returns a promise that resolves to a boolean, true if the file exists, + * false otherwise. + */ + exists(): Promise; + + /** Returns a boolean, true if the file exists, false otherwise. */ + existsSync(): boolean; + + /** Get the SHA-1 digest of this file. */ + getDigest(): Promise; + + /** Get the SHA-1 digest of this file. */ + getDigestSync(): string; + + /** Sets the file's character set encoding name. */ + setEncoding(encoding: string): void; + + /** Returns the string encoding name for this file (default: "utf8"). */ + getEncoding(): string; + + // Managing Paths + /** Returns the string path for the file. */ + getPath(): string; + + /** Returns this file's completely resolved string path. */ + getRealPathSync(): string; + + /** + * Returns a promise that resolves to the file's completely resolved + * string path. + */ + getRealPath(): Promise; + + /** Return the string filename without any directory information. */ + getBaseName(): string; + + // Traversing + /** Return the Directory that contains this file. */ + getParent(): Directory; + + // Reading and Writing + /** Reads the contents of the file. */ + read(flushCache?: boolean): Promise; + + /** Returns a stream to read the content of the file. */ + createReadStream(): ReadStream; + + /** Overwrites the file with the given text. */ + write(text: string): Promise; + + /** Returns a stream to write content to the file. */ + createWriteStream(): WriteStream; + + /** Overwrites the file with the given text. */ + writeSync(text: string): undefined; +} + +/** Represents the underlying git operations performed by Atom. */ +export class GitRepository { + // Construction + /** Creates a new GitRepository instance. */ + static open(path: string, options?: { refreshOnWindowFocus?: boolean }): GitRepository; + + constructor(path: string, options?: { refreshOnWindowFocus?: boolean, config?: Config, + project?: Project }); + + // Lifecycle + /** Destroy this GitRepository object. */ + destroy(): void; + + /** Returns a boolean indicating if this repository has been destroyed. */ + isDestroyed(): boolean; + + // Event Subscription + /** + * Invoke the given callback when this GitRepository's destroy() method is + * invoked. + */ + onDidDestroy(callback: () => void): Disposable; + + /** + * Invoke the given callback when a specific file's status has changed. When + * a file is updated, reloaded, etc, and the status changes, this will be fired. + */ + onDidChangeStatus(callback: (event: RepoStatusChangedEvent) => void): Disposable; + + /** Invoke the given callback when a multiple files' statuses have changed. */ + onDidChangeStatuses(callback: () => void): Disposable; + + // Repository Details + /** A string indicating the type of version control system used by this repository. */ + getType(): "git"; + + /** Returns the string path of the repository. */ + getPath(): string; + + /** Returns the string working directory path of the repository. */ + getWorkingDirectory(): string; + + /** Returns true if at the root, false if in a subfolder of the repository. */ + isProjectAtRoot(): boolean; + + /** Makes a path relative to the repository's working directory. */ + relativize(): string; + + /** Returns true if the given branch exists. */ + hasBranch(branch: string): boolean; + + /** Retrieves a shortened version of the HEAD reference value. */ + getShortHead(path?: string): string; + + /** Is the given path a submodule in the repository? */ + isSubmodule(path: string): boolean; + + /** + * Returns the number of commits behind the current branch is from the its + * upstream remote branch. The default reference is the HEAD. + * @param reference The branch reference name. + * @param path The path in the repository to get this ifnromation for, only + * needed if the repository contains submodules. + * @return Returns the number of commits behind the current branch is from its + * upstream remote branch. + */ + getAheadBehindCount(reference: string, path?: string): { ahead: number, behind: number }; + + /** + * Get the cached ahead/behind commit counts for the current branch's + * upstream branch. + */ + getCachedUpstreamAheadBehindCount(path?: string): { ahead: number, behind: number }; + + /** Returns the git configuration value specified by the key. */ + getConfigValue(key: string, path?: string): string; + + /** Returns the origin url of the repository. */ + getOriginURL(path?: string): string; + + /** + * Returns the upstream branch for the current HEAD, or null if there is no + * upstream branch for the current HEAD. + */ + getUpstreamBranch(path?: string): string|null; + + /** Gets all the local and remote references. */ + getReferences(path?: string): { heads: string[], remotes: string[], tags: string[] }; + + /** Returns the current string SHA for the given reference. */ + getReferenceTarget(reference: string, path?: string): string; + + // Reading Status + /** Returns true if the given path is modified. */ + isPathModified(path: string): boolean; + + /** Returns true if the given path is new. */ + isPathNew(path: string): boolean; + + /** Is the given path ignored? */ + isPathIgnored(path: string): boolean; + + /** Get the status of a directory in the repository's working directory. */ + getDirectoryStatus(path: string): number; + + /** Get the status of a single path in the repository. */ + getPathStatus(path: string): number; + + /** Get the cached status for the given path. */ + getCachedPathStatus(path: string): number|null; + + /** Returns true if the given status indicates modification. */ + isStatusModified(status: number): boolean; + + /** Returns true if the given status indicates a new path. */ + isStatusNew(status: number): boolean; + + // Retrieving Diffs + /** + * Retrieves the number of lines added and removed to a path. + * This compares the working directory contents of the path to the HEAD version. + */ + getDiffStats(path: string): { added: number, deleted: number }; + + /** + * Retrieves the line diffs comparing the HEAD version of the given path + * and the given text. + */ + getLineDiffs(path: string, text: string): Array<{ oldStart: number, + newStart: number, oldLines: number, newLines: number }>; + + // Checking Out + /** + * Restore the contents of a path in the working directory and index to the + * version at HEAD. + */ + checkoutHead(path: string): boolean; + + /** Checks out a branch in your repository. */ + checkoutReference(reference: string, create: boolean): boolean; +} + +/** Grammar that tokenizes lines of text. */ +export interface Grammar { + /** The name of the Grammar. */ + name: string; + + // Event Subscription + onDidUpdate(callback: () => void): Disposable; + + // Tokenizing + /** + * Tokenize all lines in the given text. + * @param text A string containing one or more lines. + * @return An array of token arrays for each line tokenized. + */ + tokenizeLines(text: string): GrammarToken[][]; + + /** + * Tokenizes the line of text. + * @param line A string of text to tokenize. + * @param ruleStack An optional array of rules previously returned from this + * method. This should be null when tokenizing the first line in the file. + * @param firstLine A optional boolean denoting whether this is the first line + * in the file which defaults to `false`. + * @return An object representing the result of the tokenize. + */ + tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean): TokenizeLineResult; + /** + * Tokenizes the line of text. + * @param line A string of text to tokenize. + * @param ruleStack An optional array of rules previously returned from this + * method. This should be null when tokenizing the first line in the file. + * @param firstLine A optional boolean denoting whether this is the first line + * in the file which defaults to `false`. + * @return An object representing the result of the tokenize. + */ + tokenizeLine(line: string, ruleStack: GrammarRule[], firstLine?: false): + TokenizeLineResult; +} + +/** Registry containing one or more grammars. */ +export interface GrammarRegistry { + // Event Subscription + /** + * Invoke the given callback when a grammar is added to the registry. + * @param callback The callback to be invoked whenever a grammar is added. + * @return A Disposable on which `.dispose()` can be called to unsubscribe. + */ + onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable; + + /** + * Invoke the given callback when a grammar is updated due to a grammar it + * depends on being added or removed from the registry. + * @param callback The callback to be invoked whenever a grammar is updated. + * @return A Disposable on which `.dispose()` can be called to unsubscribe. + */ + onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable; + + // Managing Grammars + /** + * Get all the grammars in this registry. + * @return A non-empty array of Grammar instances. + */ + getGrammars(): Grammar[]; + + /** + * Get a grammar with the given scope name. + * @param scopeName A string such as `source.js`. + * @return A Grammar or undefined. + */ + grammarForScopeName(scopeName: string): Grammar|undefined; + + /** + * Add a grammar to this registry. + * A 'grammar-added' event is emitted after the grammar is added. + * @param grammar The Grammar to add. This should be a value previously returned + * from ::readGrammar or ::readGrammarSync. + * @return Returns a Disposable on which `.dispose()` can be called to remove + * the grammar. + */ + addGrammar(grammar: Grammar): Disposable; + + /** + * Remove the given grammar from this registry. + * @param grammar The grammar to remove. This should be a grammar previously + * added to the registry from ::addGrammar. + */ + removeGrammar(grammar: Grammar): void; + + /** + * Remove the grammar with the given scope name. + * @param scopeName A string such as `source.js`. + * @return Returns the removed Grammar or undefined. + */ + removeGrammarForScopeName(scopeName: string): Grammar|undefined; + + /** + * Read a grammar synchronously but don't add it to the registry. + * @param grammarPath The absolute file path to a grammar. + * @return The newly loaded Grammar. + */ + readGrammarSync(grammarPath: string): Grammar; + + /** + * Read a grammar asynchronously but don't add it to the registry. + * @param grammarPath The absolute file path to the grammar. + * @param callback The function to be invoked once the Grammar has been read in. + */ + readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => + void): void; + + /** + * Read a grammar synchronously and add it to this registry. + * @param grammarPath The absolute file path to the grammar. + * @return The newly loaded Grammar. + */ + loadGrammarSync(grammarPath: string): Grammar; + + /** + * Read a grammar asynchronously and add it to the registry. + * @param grammarPath The absolute file path to the grammar. + * @param callback The function to be invoked once the Grammar has been read in + * and added to the registry. + */ + loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => + void): void; + + /** + * Convert compact tags representation into convenient, space-inefficient tokens. + * @param lineText The text of the tokenized line. + * @param tags The tags returned from a call to Grammar::tokenizeLine(). + * @return An array of Token instances decoded from the given tags. + */ + decodeTokens(lineText: string, tags: Array): GrammarToken[]; +} + +/** Represents a gutter within a TextEditor. */ +export interface Gutter { + // Gutter Destruction + /** Destroys the gutter. */ + destroy(): void; + + // Event Subscription + /** Calls your callback when the gutter's visibility changes. */ + onDidChangeVisible(callback: (gutter: Gutter) => void): Disposable; + + /** Calls your callback when the gutter is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + // Visibility + /** Hide the gutter. */ + hide(): void; + + /** Show the gutter. */ + show(): void; + + /** Determine whether the gutter is visible. */ + isVisible(): boolean; + + /** + * Add a decoration that tracks a DisplayMarker. When the marker moves, is + * invalidated, or is destroyed, the decoration will be updated to reflect + * the marker's state. + */ + decorateMarker(marker: DisplayMarker, decorationParams: DecorationOptions): Decoration; +} + +/** + * History manager for remembering which projects have been opened. + * An instance of this class is always available as the atom.history global. + * The project history is used to enable the 'Reopen Project' menu. + */ +export interface HistoryManager { + /** Obtain a list of previously opened projects. */ + getProjects(): ProjectHistory[]; + + /** + * Clear all projects from the history. + * Note: This is not a privacy function - other traces will still exist, e.g. + * window state. + */ + clearProjects(): void; + + /** Invoke the given callback when the list of projects changes. */ + onDidChangeProjects(callback: (args: { reloaded: boolean }) => void): Disposable; +} + +/** + * Allows commands to be associated with keystrokes in a context-sensitive way. + * In Atom, you can access a global instance of this object via `atom.keymaps`. + */ +export interface KeymapManager { + /** Clear all registered key bindings and enqueued keystrokes. For use in tests. */ + clear(): void; + + /** Unwatch all watched paths. */ + destroy(): void; + + // Event Subscription + /** Invoke the given callback when one or more keystrokes completely match a key binding. */ + onDidMatchBinding(callback: (event: FullKeybindingMatchEvent) => void): Disposable; + + /** Invoke the given callback when one or more keystrokes partially match a binding. */ + onDidPartiallyMatchBindings(callback: (event: PartialKeybindingMatchEvent) => + void): Disposable; + + /** Invoke the given callback when one or more keystrokes fail to match any bindings. */ + onDidFailToMatchBinding(callback: (event: FailedKeybindingMatchEvent) => + void): Disposable; + + /** Invoke the given callback when a keymap file is reloaded. */ + onDidReloadKeymap(callback: (event: KeymapLoadedEvent) => void): Disposable; + + /** Invoke the given callback when a keymap file is unloaded. */ + onDidUnloadKeymap(callback: (event: KeymapLoadedEvent) => void): Disposable; + + /** Invoke the given callback when a keymap file not able to be loaded. */ + onDidFailToReadFile(callback: (error: FailedKeymapFileReadEvent) => void): Disposable; + + // Adding and Removing Bindings + /** Construct KeyBindings from an object grouping them by CSS selector. */ + build(source: string, bindings: { [key: string]: { [key: string]: string }}, + priority?: number): KeyBinding[]; + + /** Add sets of key bindings grouped by CSS selector. */ + add(source: string, bindings: { [key: string]: { [key: string]: string }}, + priority?: number): Disposable; + + // Accessing Bindings + /** Get all current key bindings. */ + getKeyBindings(): KeyBinding[]; + + /** Get the key bindings for a given command and optional target. */ + findKeyBindings(params?: { + keystrokes?: string, // e.g. 'ctrl-x ctrl-s' + command?: string, // e.g. 'editor:backspace' + target?: Element, + }): KeyBinding[]; + + // Managing Keymap Files + /** Load the key bindings from the given path. */ + loadKeymap(bindingsPath: string, options?: { watch?: boolean, priority?: number }): + void; + + /** + * Cause the keymap to reload the key bindings file at the given path whenever + * it changes. + */ + watchKeymap(filePath: string, options?: { priority: number }): void; + + // Managing Keyboard Events + /** + * Dispatch a custom event associated with the matching key binding for the + * given `KeyboardEvent` if one can be found. + */ + handleKeyboardEvent(event: KeyboardEvent): void; + + /** Translates a keydown event to a keystroke string. */ + keystrokeForKeyboardEvent(event: KeyboardEvent): string; + + /** Customize translation of raw keyboard events to keystroke strings. */ + addKeystrokeResolver(resolver: (event: AddedKeystrokeResolverEvent) => string): Disposable; + + /** + * Get the number of milliseconds allowed before pending states caused by + * partial matches of multi-keystroke bindings are terminated. + */ + getPartialMatchTimeout(): number; +} + +/** Provides a registry for menu items that you'd like to appear in the application menu. */ +export interface MenuManager { + /** Adds the given items to the application menu. */ + add(items: ReadonlyArray): Disposable; + + /** Refreshes the currently visible menu. */ + update(): void; +} + +/** + * Loads and activates a package's main module and resources such as stylesheets, + * keymaps, grammar, editor properties, and menus. + */ +export interface Package { + /** The name of the Package. */ + name: string; + + /** The path to the Package on disk. */ + path: string; + + // Event Subscription + /** Invoke the given callback when all packages have been activated. */ + onDidDeactivate(callback: () => void): Disposable; + + // Native Module Compatibility + /** + * Are all native modules depended on by this package correctly compiled + * against the current version of Atom? + */ + isCompatible(): boolean; + + /** + * Rebuild native modules in this package's dependencies for the current + * version of Atom. + */ + rebuild(): Promise<{ code: number, stdout: string, stderr: string }>; + + /** If a previous rebuild failed, get the contents of stderr. */ + getBuildFailureOutput(): string|null; +} + +/** Package manager for coordinating the lifecycle of Atom packages. */ +export interface PackageManager { + // Event Subscription + /** Invoke the given callback when all packages have been loaded. */ + onDidLoadInitialPackages(callback: () => void): Disposable; + + /** Invoke the given callback when all packages have been activated. */ + onDidActivateInitialPackages(callback: () => void): Disposable; + + /** Invoke the given callback when a package is activated. */ + onDidActivatePackage(callback: (package: Package) => void): Disposable; + + /** Invoke the given callback when a package is deactivated. */ + onDidDeactivatePackage(callback: (package: Package) => void): Disposable; + + /** Invoke the given callback when a package is loaded. */ + onDidLoadPackage(callback: (package: Package) => void): Disposable; + + /** Invoke the given callback when a package is unloaded. */ + onDidUnloadPackage(callback: (package: Package) => void): Disposable; + + // Package System Data + /** Get the path to the apm command. */ + getApmPath(): string; + + /** Get the paths being used to look for packages. */ + getPackageDirPaths(): string[]; + + // General Package Data + /** Resolve the given package name to a path on disk. */ + resolvePackagePath(name: string): string|undefined; + + /** Is the package with the given name bundled with Atom? */ + isBundledPackage(name: string): boolean; + + // Enabling and Disabling Packages + /** Enable the package with the given name. */ + enablePackage(name: string): Package|undefined; + + /** Disable the package with the given name. */ + disablePackage(name: string): Package|undefined; + + /** Is the package with the given name disabled? */ + isPackageDisabled(name: string): boolean; + + // Accessing Active Packages + /** Get an Array of all the active Packages. */ + getActivePackages(): Package[]; + + /** Get the active Package with the given name. */ + getActivePackage(name: string): Package|undefined; + + /** Is the Package with the given name active? */ + isPackageActive(name: string): boolean; + + /** Returns a boolean indicating whether package activation has occurred. */ + hasActivatedInitialPackages(): boolean; + + // Accessing Loaded Packages + /** Get an Array of all the loaded Packages. */ + getLoadedPackages(): Package[]; + + /** Get the loaded Package with the given name. */ + getLoadedPackage(name: string): Package|undefined; + + /** Is the package with the given name loaded? */ + isPackageLoaded(name: string): boolean; + + /** Returns a boolean indicating whether package loading has occurred. */ + hasLoadedInitialPackages(): boolean; + + // Accessing Available Packages + /** Returns an Array of strings of all the available package paths. */ + getAvailablePackagePaths(): string[]; + + /** Returns an Array of strings of all the available package names. */ + getAvailablePackageNames(): string[]; + + /** Returns an Array of strings of all the available package metadata. */ + getAvailablePackageMetadata(): string[]; + + /** Activate a single package by name or path. */ + activatePackage(nameOrPath: string): Promise; + + /** Triggers the given package activation hook. */ + triggerActivationHook(hook: string): void; + + /** Trigger all queued activation hooks immediately. */ + triggerDeferredActivationHooks(): void; +} + +/** A container for presenting content in the center of the workspace. */ +export interface Pane { + // Event Subscription + /** Invoke the given callback when the pane resizes. */ + onDidChangeFlexScale(callback: (flexScale: number) => void): Disposable; + + /** Invoke the given callback with the current and future values of ::getFlexScale. */ + observeFlexScale(callback: (flexScale: number) => void): Disposable; + + /** Invoke the given callback when the pane is activated. */ + onDidActivate(callback: () => void): Disposable; + + /** Invoke the given callback before the pane is destroyed. */ + onWillDestroy(callback: () => void): Disposable; + + /** Invoke the given callback when the pane is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** Invoke the given callback when the value of the ::isActive property changes. */ + onDidChangeActive(callback: (active: boolean) => void): Disposable; + + /** + * Invoke the given callback with the current and future values of the ::isActive + * property. + */ + observeActive(callback: (active: boolean) => void): Disposable; + + /** Invoke the given callback when an item is added to the pane. */ + onDidAddItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable; + + /** Invoke the given callback when an item is removed from the pane. */ + onDidRemoveItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable; + + /** Invoke the given callback before an item is removed from the pane. */ + onWillRemoveItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable; + + /** Invoke the given callback when an item is moved within the pane. */ + onDidMoveItem(callback: (event: PaneItemMovedEvent) => void): Disposable; + + /** Invoke the given callback with all current and future items. */ + observeItems(callback: (item: object) => void): Disposable; + + /** Invoke the given callback when the value of ::getActiveItem changes. */ + onDidChangeActiveItem(callback: (activeItem: object) => void): Disposable; + + /** + * Invoke the given callback when ::activateNextRecentlyUsedItem has been called, + * either initiating or continuing a forward MRU traversal of pane items. + */ + onChooseNextMRUItem(callback: (nextRecentlyUsedItem: object) => void): Disposable; + + /** + * Invoke the given callback when ::activatePreviousRecentlyUsedItem has been called, + * either initiating or continuing a reverse MRU traversal of pane items. + */ + onChooseLastMRUItem(callback: (previousRecentlyUsedItem: object) => void): Disposable; + + /** + * Invoke the given callback when ::moveActiveItemToTopOfStack has been called, + * terminating an MRU traversal of pane items and moving the current active item + * to the top of the stack. Typically bound to a modifier (e.g. CTRL) key up event. + */ + onDoneChoosingMRUItem(callback: () => void): Disposable; + + /** Invoke the given callback with the current and future values of ::getActiveItem. */ + observeActiveItem(callback: (activeItem: object) => void): Disposable; + + /** Invoke the given callback before items are destroyed. */ + onWillDestroyItem(callback: (event: PaneListItemShiftedEvent) => void): Disposable; + + // Items + /** Get the items in this pane. */ + getItems(): object[]; + + /** Get the active pane item in this pane. */ + getActiveItem(): object; + + /** Return the item at the given index. */ + itemAtIndex(index: number): object|undefined; + + /** Makes the next item active. */ + activateNextItem(): void; + + /** Makes the previous item active. */ + activatePreviousItem(): void; + + /** Move the active tab to the right. */ + moveItemRight(): void; + + /** Move the active tab to the left. */ + moveItemLeft(): void; + + /** Get the index of the active item. */ + getActiveItemIndex(): number; + + /** Activate the item at the given index. */ + activateItemAtIndex(index: number): void; + + /** Make the given item active, causing it to be displayed by the pane's view. */ + activateItem(item: object, options?: { pending: boolean }): void; + + /** Add the given item to the pane. */ + addItem(item: object, options?: { index?: number, pending?: boolean }): object; + + /** Add the given items to the pane. */ + addItems(items: object[], index?: number): object[]; + + /** Move the given item to the given index. */ + moveItem(item: object, index: number): void; + + /** Move the given item to the given index on another pane. */ + moveItemToPane(item: object, pane: Pane, index: number): void; + + /** Destroy the active item and activate the next item. */ + destroyActiveItem(): Promise; + + /** Destroy the given item. */ + destroyItem(item: object, force?: boolean): Promise; + + /** Destroy all items. */ + destroyItems(): Promise; + + /** Destroy all items except for the active item. */ + destroyInactiveItems(): Promise; + + /** Save the active item. */ + saveActiveItem(nextAction?: (error?: Error) => T): + Promise|undefined; + + /** + * Prompt the user for a location and save the active item with the path + * they select. + */ + saveActiveItemAs(nextAction?: (error?: Error) => T): + Promise|undefined; + + /** Save the given item. */ + saveItem(item: object, nextAction?: (error?: Error) => T): + Promise|undefined; + + /** + * Prompt the user for a location and save the active item with the path + * they select. + */ + saveItemAs(item: object, nextAction?: (error?: Error) => T): + Promise|undefined; + + /** Save all items. */ + saveItems(): void; + + /** Return the first item that matches the given URI or undefined if none exists. */ + itemForURI(uri: string): object|undefined; + + /** Activate the first item that matches the given URI. */ + activateItemForURI(uri: string): boolean; + + // Lifecycle + /** Determine whether the pane is active. */ + isActive(): boolean; + + /** Makes this pane the active pane, causing it to gain focus. */ + activate(): void; + + /** Close the pane and destroy all its items. */ + destroy(): void; + + /** Determine whether this pane has been destroyed. */ + isDestroyed(): boolean; + + // Splitting + /** Create a new pane to the left of this pane. */ + splitLeft(params?: { + items?: object[], + copyActiveItem?: boolean, + }): Pane; + + /** Create a new pane to the right of this pane. */ + splitRight(params?: { + items?: object[], + copyActiveItem?: boolean, + }): Pane; + + /** Creates a new pane above the receiver. */ + splitUp(params?: { + items?: object[], + copyActiveItem?: boolean, + }): Pane; + + /** Creates a new pane below the receiver. */ + splitDown(params?: { + items?: object[], + copyActiveItem?: boolean, + }): Pane; +} + +/** + * A container representing a panel on the edges of the editor window. You + * should not create a Panel directly, instead use Workspace::addTopPanel and + * friends to add panels. + */ +export interface Panel { + /** Whether or not the Panel is visible. */ + visible: boolean; + + // Construction and Destruction + /** Destroy and remove this panel from the UI. */ + destroy(): void; + + // Event Subscription + /** Invoke the given callback when the pane hidden or shown. */ + onDidChangeVisible(callback: (visible: boolean) => void): Disposable; + + /** Invoke the given callback when the pane is destroyed. */ + onDidDestroy(callback: (panel: Panel) => void): Disposable; + + // Panel Details + /** Returns the panel's item. */ + getItem(): T; + + /** Returns a number indicating this panel's priority. */ + getPriority(): number; + + /** Returns a boolean true when the panel is visible. */ + isVisible(): boolean; + + /** Hide this panel. */ + hide(): void; + + /** Show this panel. */ + show(): void; +} + +/** Manage a subscription to filesystem events that occur beneath a root directory. */ +export interface PathWatcher extends DisposableLike { + /** + * Return a Promise that will resolve when the underlying native watcher is + * ready to begin sending events. + */ + getStartPromise(): Promise; + + /** Invokes a function when any errors related to this watcher are reported. */ + onDidError(callback: (error: Error) => void): Disposable; + + /** + * Unsubscribe all subscribers from filesystem events. Native resources will be + * release asynchronously, but this watcher will stop broadcasting events + * immediately. + */ + dispose(): void; +} + +/** Represents a project that's opened in Atom. */ +export interface Project { + // Event Subscription + /** Invoke the given callback when the project paths change. */ + onDidChangePaths(callback: (projectPaths: string[]) => void): Disposable; + + /** Invoke the given callback when a text buffer is added to the project. */ + onDidAddBuffer(callback: (buffer: TextBuffer) => void): Disposable; + + /** + * Invoke the given callback with all current and future text buffers in + * the project. + */ + observeBuffers(callback: (buffer: TextBuffer) => void): Disposable; + + /** Invoke a callback when a filesystem change occurs within any open project path. */ + onDidChangeFiles(callback: (events: FilesystemChangeEvent) => void): Disposable; + + // Accessing the Git Repository + /** Get an Array of GitRepositorys associated with the project's directories. */ + getRepositories(): GitRepository[]; + + /** Get the repository for a given directory asynchronously. */ + repositoryForDirectory(directory: Directory): Promise; + + // Managing Paths + /** Get an Array of strings containing the paths of the project's directories. */ + getPaths(): string[]; + + /** Set the paths of the project's directories. */ + setPaths(projectPaths: string[]): void; + + /** Add a path to the project's list of root paths. */ + addPath(projectPath: string): void; + + /** + * Access a promise that resolves when the filesystem watcher associated with a + * project root directory is ready to begin receiving events. + */ + getWatcherPromise(projectPath: string): Promise; + + /** Remove a path from the project's list of root paths. */ + removePath(projectPath: string): void; + + /** Get an Array of Directorys associated with this project. */ + getDirectories(): Directory[]; + + /** Get the relative path from the project directory to the given path. */ + relativize(fullPath: string): string; + + /** + * Get the path to the project directory that contains the given path, and + * the relative path from that project directory to the given path. + */ + relativizePath(fullPath: string): [string|null, string]; + + /** + * Determines whether the given path (real or symbolic) is inside the + * project's directory. + */ + contains(pathToCheck: string): boolean; +} + +/** + * Wraps an array of strings. The Array describes a path from the root of the + * syntax tree to a token including all scope names for the entire path. + */ +export interface ScopeDescriptor { + scopes: string[]; + + /** Returns all scopes for this descriptor. */ + getScopesArray(): string[]; +} + +/** Represents a selection in the TextEditor. */ +export interface Selection { + // Event Subscription + /** Calls your callback when the selection was moved. */ + onDidChangeRange(callback: (event: SelectionChangedEvent) => void): Disposable; + + /** Calls your callback when the selection was destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + // Managing the selection range + /** Returns the screen Range for the selection. */ + getScreenRange(): Range; + + /** Modifies the screen range for the selection. */ + setScreenRange(screenRange: RangeCompatible, options?: { + preserveFolds?: boolean, + autoscroll?: boolean + }): void; + + /** Returns the buffer Range for the selection. */ + getBufferRange(): Range; + + /** Modifies the buffer Range for the selection. */ + setBufferRange(bufferRange: RangeCompatible, options?: { + preserveFolds?: boolean, + autoscroll?: boolean, + }): void; + + /** Returns the starting and ending buffer rows the selection is highlighting. */ + getBufferRowRange(): [number, number]; + + // Info about the selection + /** Determines if the selection contains anything. */ + isEmpty(): boolean; + + /** + * Determines if the ending position of a marker is greater than the starting position. + * This can happen when, for example, you highlight text "up" in a TextBuffer. + */ + isReversed(): boolean; + + /** Returns whether the selection is a single line or not. */ + isSingleScreenLine(): boolean; + + /** Returns the text in the selection. */ + getText(): string; + + // NOTE: this calls into Range.intersectsWith(), which is one of the few functions + // that doesn't take a range-compatible range, despite what the API says. + /** Identifies if a selection intersects with a given buffer range. */ + intersectsBufferRange(bufferRange: RangeLike): boolean; + + /** Identifies if a selection intersects with another selection. */ + intersectsWith(otherSelection: Selection): boolean; + + // Modifying the selected range + /** Clears the selection, moving the marker to the head. */ + clear(options?: { autoscroll?: boolean }): void; + + /** Selects the text from the current cursor position to a given screen position. */ + selectToScreenPosition(position: PointCompatible): void; + + /** Selects the text from the current cursor position to a given buffer position. */ + selectToBufferPosition(position: PointCompatible): void; + + /** Selects the text one position right of the cursor. */ + selectRight(columnCount?: number): void; + + /** Selects the text one position left of the cursor. */ + selectLeft(columnCount?: number): void; + + /** Selects all the text one position above the cursor. */ + selectUp(rowCount?: number): void; + + /** Selects all the text one position below the cursor. */ + selectDown(rowCount?: number): void; + + /** + * Selects all the text from the current cursor position to the top of the + * buffer. + */ + selectToTop(): void; + + /** + * Selects all the text from the current cursor position to the bottom of + * the buffer. + */ + selectToBottom(): void; + + /** Selects all the text in the buffer. */ + selectAll(): void; + + /** + * Selects all the text from the current cursor position to the beginning of + * the line. + */ + selectToBeginningOfLine(): void; + + /** + * Selects all the text from the current cursor position to the first character + * of the line. + */ + selectToFirstCharacterOfLine(): void; + + /** + * Selects all the text from the current cursor position to the end of the + * screen line. + */ + selectToEndOfLine(): void; + + /** + * Selects all the text from the current cursor position to the end of the + * buffer line. + */ + selectToEndOfBufferLine(): void; + + /** + * Selects all the text from the current cursor position to the beginning + * of the word. + */ + selectToBeginningOfWord(): void; + + /** Selects all the text from the current cursor position to the end of the word. */ + selectToEndOfWord(): void; + + /** + * Selects all the text from the current cursor position to the beginning of + * the next word. + */ + selectToBeginningOfNextWord(): void; + + /** Selects text to the previous word boundary. */ + selectToPreviousWordBoundary(): void; + + /** Selects text to the next word boundary. */ + selectToNextWordBoundary(): void; + + /** Selects text to the previous subword boundary. */ + selectToPreviousSubwordBoundary(): void; + + /** Selects text to the next subword boundary. */ + selectToNextSubwordBoundary(): void; + + /** + * Selects all the text from the current cursor position to the beginning of + * the next paragraph. + */ + selectToBeginningOfNextParagraph(): void; + + /** + * Selects all the text from the current cursor position to the beginning of + * the previous paragraph. + */ + selectToBeginningOfPreviousParagraph(): void; + + /** Modifies the selection to encompass the current word. */ + selectWord(): void; + + /** + * Expands the newest selection to include the entire word on which the + * cursors rests. + */ + expandOverWord(): void; + + /** Selects an entire line in the buffer. */ + selectLine(row: number): void; + + /** + * Expands the newest selection to include the entire line on which the cursor + * currently rests. + * It also includes the newline character. + */ + expandOverLine(): void; + + // Modifying the selected text + /** Replaces text at the current selection. */ + insertText(text: string, options?: TextInsertionOptions): void; + + /** + * Removes the first character before the selection if the selection is empty + * otherwise it deletes the selection. + */ + backspace(): void; + + /** + * Removes the selection or, if nothing is selected, then all characters from + * the start of the selection back to the previous word boundary. + */ + deleteToPreviousWordBoundary(): void; + + /** + * Removes the selection or, if nothing is selected, then all characters from + * the start of the selection up to the next word boundary. + */ + deleteToNextWordBoundary(): void; + + /** + * Removes from the start of the selection to the beginning of the current + * word if the selection is empty otherwise it deletes the selection. + */ + deleteToBeginningOfWord(): void; + + /** + * Removes from the beginning of the line which the selection begins on all + * the way through to the end of the selection. + */ + deleteToBeginningOfLine(): void; + + /** + * Removes the selection or the next character after the start of the selection + * if the selection is empty. + */ + delete(): void; + + /** + * If the selection is empty, removes all text from the cursor to the end of + * the line. If the cursor is already at the end of the line, it removes the following + * newline. If the selection isn't empty, only deletes the contents of the selection. + */ + deleteToEndOfLine(): void; + + /** + * Removes the selection or all characters from the start of the selection to + * the end of the current word if nothing is selected. + */ + deleteToEndOfWord(): void; + + /** + * Removes the selection or all characters from the start of the selection to + * the end of the current word if nothing is selected. + */ + deleteToBeginningOfSubword(): void; + + /** + * Removes the selection or all characters from the start of the selection to + * the end of the current word if nothing is selected. + */ + deleteToEndOfSubword(): void; + + /** Removes only the selected text. */ + deleteSelectedText(): void; + + /** + * Removes the line at the beginning of the selection if the selection is empty + * unless the selection spans multiple lines in which case all lines are removed. + */ + deleteLine(): void; + + /** + * Joins the current line with the one below it. Lines will be separated by a single space. + * If there selection spans more than one line, all the lines are joined together. + */ + joinLines(): void; + + /** Removes one level of indent from the currently selected rows. */ + outdentSelectedRows(): void; + + /** + * Sets the indentation level of all selected rows to values suggested by the + * relevant grammars. + */ + autoIndentSelectedRows(): void; + + /** + * Wraps the selected lines in comments if they aren't currently part of a comment. + * Removes the comment if they are currently wrapped in a comment. + */ + toggleLineComments(): void; + + /** Cuts the selection until the end of the screen line. */ + cutToEndOfLine(): void; + + /** Cuts the selection until the end of the buffer line. */ + cutToEndOfBufferLine(): void; + + /** Copies the selection to the clipboard and then deletes it. */ + cut(maintainClipboard?: boolean, fullLine?: boolean): void; + + /** Copies the current selection to the clipboard. */ + copy(maintainClipboard?: boolean, fullLine?: boolean): void; + + /** Creates a fold containing the current selection. */ + fold(): void; + + /** If the selection spans multiple rows, indent all of them. */ + indentSelectedRows(): void; + + // Managing multiple selections + /** Moves the selection down one row. */ + addSelectionBelow(): void; + + /** Moves the selection up one row. */ + addSelectionAbove(): void; + + /** + * Combines the given selection into this selection and then destroys the + * given selection. + */ + merge(otherSelection: Selection, options?: { preserveFolds?: boolean, + autoscroll?: boolean }): void; + + // Comparing to other selections + /** + * Compare this selection's buffer range to another selection's buffer range. + * See Range::compare for more details. + */ + compare(otherSelection: Selection): number; +} + +/** + * A singleton instance of this class available via atom.styles, which you can + * use to globally query and observe the set of active style sheets. + */ +export interface StyleManager { + // Event Subscription + /** Invoke callback for all current and future style elements. */ + observeStyleElements(callback: (styleElement: StyleElementObservedEvent) => + void): Disposable; + + /** Invoke callback when a style element is added. */ + onDidAddStyleElement(callback: (styleElement: StyleElementObservedEvent) => + void): Disposable; + + /** Invoke callback when a style element is removed. */ + onDidRemoveStyleElement(callback: (styleElement: HTMLStyleElement) => void): Disposable; + + /** Invoke callback when an existing style element is updated. */ + onDidUpdateStyleElement(callback: (styleElement: StyleElementObservedEvent) => + void): Disposable; + + // Reading Style Elements + /** Get all loaded style elements. */ + getStyleElements(): HTMLStyleElement[]; + + // Paths + /** Get the path of the user style sheet in ~/.atom. */ + getUserStyleSheetPath(): string; +} + +/** Run a node script in a separate process. */ +export class Task { + // NOTE: this is actually the best we can do here with the REST parameter for + // this appearing in the middle of the parameter list, which isn't aligned with + // the ES6 spec. Maybe when they rewrite it in JavaScript this will change. + /** A helper method to easily launch and run a task once. */ + // tslint:disable-next-line:no-any + static once(taskPath: string, ...args: any[]): Task; + + /** Creates a task. You should probably use .once */ + constructor(taskPath: string); + + // NOTE: this is actually the best we can do here with the REST parameter + // for this appearing in the beginning of the parameter list, which isn't + // aligned with the ES6 spec. + /** + * Starts the task. + * Throws an error if this task has already been terminated or if sending a + * message to the child process fails. + */ + // tslint:disable-next-line:no-any + start(...args: any[]): void; + + /** + * Send message to the task. + * Throws an error if this task has already been terminated or if sending a + * message to the child process fails. + */ + send(message: string): void; + + /** Call a function when an event is emitted by the child process. */ + // tslint:disable-next-line:no-any + on(eventName: string, callback: (param: any) => void): Disposable; + + /** + * Forcefully stop the running task. + * No more events are emitted once this method is called. + */ + terminate(): void; + + /** Cancel the running task and emit an event if it was canceled. */ + cancel(): boolean; +} + +/** + * A mutable text container with undo/redo support and the ability to + * annotate logical regions in the text. + */ +export class TextBuffer { + /** The unique identifier for this buffer. */ + id: string; + + /** The number of retainers for the buffer. */ + refcount: number; + + /** Whether or not the bufffer has been destroyed. */ + destroyed: boolean; + + /** Create a new buffer backed by the given file path. */ + static load(filePath: string, params?: BufferLoadOptions): Promise; + + /** + * Create a new buffer backed by the given file path. For better performance, + * use TextBuffer.load instead. + */ + static loadSync(filePath: string, params?: BufferLoadOptions): TextBuffer; + + /** + * Restore a TextBuffer based on an earlier state created using the + * TextBuffer::serialize method. + */ + static deserialize(params: object): Promise; + + /** Create a new buffer with the given starting text. */ + constructor(text: string); + /** Create a new buffer with the given params. */ + constructor(params?: { + /** The initial string text of the buffer. */ + text?: string + /** + * A function that returns a Boolean indicating whether the buffer should + * be destroyed if its file is deleted. + */ + shouldDestroyOnFileDelete?(): boolean + }); + + /** Returns a plain javascript object representation of the TextBuffer. */ + serialize(options?: { markerLayers?: boolean, history?: boolean }): object; + + /** Returns the unique identifier for this buffer. */ + getId(): string; + + // Event Subscription + /** + * Invoke the given callback synchronously before the content of the buffer + * changes. + */ + onWillChange(callback: (event: BufferChangingEvent) => void): Disposable; + + /** + * Invoke the given callback synchronously when the content of the buffer + * changes. You should probably not be using this in packages. + */ + onDidChange(callback: (event: BufferChangedEvent) => void): Disposable; + + /** + * Invoke the given callback synchronously when a transaction finishes with + * a list of all the changes in the transaction. + */ + onDidChangeText(callback: (event: BufferStoppedChangingEvent) => void): Disposable; + + /** + * Invoke the given callback asynchronously following one or more changes after + * ::getStoppedChangingDelay milliseconds elapse without an additional change. + */ + onDidStopChanging(callback: (event: BufferStoppedChangingEvent) => void): + Disposable; + + /** + * Invoke the given callback when the in-memory contents of the buffer become + * in conflict with the contents of the file on disk. + */ + onDidConflict(callback: () => void): Disposable; + + /** Invoke the given callback if the value of ::isModified changes. */ + onDidChangeModified(callback: (modified: boolean) => void): Disposable; + + /** + * Invoke the given callback when all marker ::onDidChange observers have been + * notified following a change to the buffer. + */ + onDidUpdateMarkers(callback: () => void): Disposable; + + onDidCreateMarker(callback: (marker: Marker) => void): Disposable; + + /** Invoke the given callback when the value of ::getPath changes. */ + onDidChangePath(callback: (path: string) => void): Disposable; + + /** Invoke the given callback when the value of ::getEncoding changes. */ + onDidChangeEncoding(callback: (encoding: string) => void): Disposable; + + /** + * Invoke the given callback before the buffer is saved to disk. If the + * given callback returns a promise, then the buffer will not be saved until + * the promise resolves. + */ + onWillSave(callback: () => Promise|void): Disposable; + + /** Invoke the given callback after the buffer is saved to disk. */ + onDidSave(callback: (event: FileSavedEvent) => void): Disposable; + + /** Invoke the given callback after the file backing the buffer is deleted. */ + onDidDelete(callback: () => void): Disposable; + + /** + * Invoke the given callback before the buffer is reloaded from the contents + * of its file on disk. + */ + onWillReload(callback: () => void): Disposable; + + /** + * Invoke the given callback after the buffer is reloaded from the contents + * of its file on disk. + */ + onDidReload(callback: () => void): Disposable; + + /** Invoke the given callback when the buffer is destroyed. */ + onDidDestroy(callback: () => void): Disposable; + + /** Invoke the given callback when there is an error in watching the file. */ + onWillThrowWatchError(callback: (errorObject: HandleableErrorEvent) => void): + Disposable; + + /** + * Get the number of milliseconds that will elapse without a change before + * ::onDidStopChanging observers are invoked following a change. + */ + getStoppedChangingDelay(): number; + + // File Details + /** + * Determine if the in-memory contents of the buffer differ from its contents + * on disk. + * If the buffer is unsaved, always returns true unless the buffer is empty. + */ + isModified(): boolean; + + /** + * Determine if the in-memory contents of the buffer conflict with the on-disk + * contents of its associated file. + */ + isInConflict(): boolean; + + /** Get the path of the associated file. */ + getPath(): string|undefined; + + /** Set the path for the buffer's associated file. */ + setPath(filePath: string): void; + + /** Sets the character set encoding for this buffer. */ + setEncoding(encoding: string): void; + + /** Returns the string encoding of this buffer. */ + getEncoding(): string; + + /** Get the path of the associated file. */ + getUri(): string; + + // Reading Text + /** Determine whether the buffer is empty. */ + isEmpty(): boolean; + + /** Get the entire text of the buffer. */ + getText(): string; + + /** Get the text in a range. */ + getTextInRange(range: RangeCompatible): string; + + /** Get the text of all lines in the buffer, without their line endings. */ + getLines(): string[]; + + /** Get the text of the last line of the buffer, without its line ending. */ + getLastLine(): string; + + /** Get the text of the line at the given row, without its line ending. */ + lineForRow(row: number): string|undefined; + + /** Get the line ending for the given 0-indexed row. */ + lineEndingForRow(row: number): string|undefined; + + /** + * Get the length of the line for the given 0-indexed row, without its line + * ending. + */ + lineLengthForRow(row: number): number; + + /** Determine if the given row contains only whitespace. */ + isRowBlank(row: number): boolean; + + /** + * Given a row, find the first preceding row that's not blank. + * Returns a number or null if there's no preceding non-blank row. + */ + previousNonBlankRow(startRow: number): number|null; + + /** + * Given a row, find the next row that's not blank. + * Returns a number or null if there's no next non-blank row. + */ + nextNonBlankRow(startRow: number): number|null; + + // Mutating Text + /** Replace the entire contents of the buffer with the given text. */ + setText(text: string): Range; + + /** + * Replace the current buffer contents by applying a diff based on the + * given text. + */ + setTextViaDiff(text: string): void; + + /** Set the text in the given range. */ + setTextInRange(range: RangeCompatible, text: string, options?: + { normalizeLineEndings?: boolean, undo?: "skip" }): Range; + + /** Insert text at the given position. */ + insert(position: PointCompatible, text: string, options?: + { normalizeLineEndings?: boolean, undo?: "skip" }): Range; + + /** Append text to the end of the buffer. */ + append(text: string, options?: { normalizeLineEndings?: boolean, undo?: + "skip" }): Range; + + /** Delete the text in the given range. */ + delete(range: RangeCompatible): Range; + + /** Delete the line associated with a specified row. */ + deleteRow(row: number): Range; + + /** Delete the lines associated with the specified row range. */ + deleteRows(startRow: number, endRow: number): Range; + + // Markers + /** Create a layer to contain a set of related markers. */ + addMarkerLayer(options?: { maintainHistory?: boolean, persistent?: boolean }): + MarkerLayer; + + /** + * Get a MarkerLayer by id. + * Returns a MarkerLayer or `` if no layer exists with the given id. + */ + getMarkerLayer(id: string): MarkerLayer|undefined; + + /** Get the default MarkerLayer. */ + getDefaultMarkerLayer(): MarkerLayer; + + /** Create a marker with the given range in the default marker layer. */ + markRange(range: RangeCompatible, properties?: { reversed?: boolean, + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch", + exclusive?: boolean }): Marker; + + /** Create a marker at the given position with no tail in the default marker layer. */ + markPosition(position: PointCompatible, options?: { invalidate?: "never"|"surround" + |"overlap"|"inside"|"touch", exclusive?: boolean }): Marker; + + /** Get all existing markers on the default marker layer. */ + getMarkers(): Marker[]; + + /** Get an existing marker by its id from the default marker layer. */ + getMarker(id: number): Marker; + + /** Find markers conforming to the given parameters in the default marker layer. */ + findMarkers(params: FindMarkerOptions): Marker[]; + + /** Get the number of markers in the default marker layer. */ + getMarkerCount(): number; + + // History + /** Undo the last operation. If a transaction is in progress, aborts it. */ + undo(): boolean; + + /** Redo the last operation. */ + redo(): boolean; + + /** Batch multiple operations as a single undo/redo step. */ + transact(groupingInterval: number, fn: () => T): T; + transact(fn: () => T): T; + + /** + * Call within a transaction to terminate the function's execution and + * revert any changes performed up to the abortion. + */ + abortTransaction(): void; + + /** + * Clear the undo stack. When calling this method within a transaction, + * the ::onDidChangeText event will not be triggered because the information + * describing the changes is lost. + */ + clearUndoStack(): void; + + /** + * Create a pointer to the current state of the buffer for use with + * ::revertToCheckpoint and ::groupChangesSinceCheckpoint. + */ + createCheckpoint(): number; + + /** + * Revert the buffer to the state it was in when the given checkpoint was created. + * Returns a boolean indicating whether the operation succeeded. + */ + revertToCheckpoint(checkpoint: number): boolean; + + /** + * Group all changes since the given checkpoint into a single transaction for + * purposes of undo/redo. + * Returns a boolean indicating whether the operation succeeded. + */ + groupChangesSinceCheckpoint(checkpoint: number): boolean; + + /** + * Returns a list of changes since the given checkpoint. + * If the given checkpoint is no longer present in the undo history, this method + * will return an empty Array. + */ + getChangesSinceCheckpoint(checkpoint: number): Array<{ + /** A Point representing where the change started. */ + start: Point, + + /** A Point representing the replaced extent. */ + oldExtent: Point, + + /** A Point representing the replacement extent. */ + newExtent: Point, + + /** A String representing the replacement text. */ + newText: string + }>; + + // Search and Replace + /** + * Scan regular expression matches in the entire buffer, calling the given + * iterator function on each match. + */ + scan(regex: RegExp, iterator: (params: BufferScanResult) => void): void; + /** + * Scan regular expression matches in the entire buffer, calling the given + * iterator function on each match. + */ + scan(regex: RegExp, options: ScanContextOptions, iterator: (params: + ContextualBufferScanResult) => void): void; + + /** + * Scan regular expression matches in the entire buffer in reverse order, + * calling the given iterator function on each match. + */ + backwardsScan(regex: RegExp, iterator: (params: BufferScanResult) => void): void; + /** + * Scan regular expression matches in the entire buffer in reverse order, + * calling the given iterator function on each match. + */ + backwardsScan(regex: RegExp, options: ScanContextOptions, iterator: (params: + ContextualBufferScanResult) => void): void; + + /** + * Scan regular expression matches in a given range , calling the given + * iterator function on each match. + */ + scanInRange(regex: RegExp, range: RangeCompatible, iterator: + (params: BufferScanResult) => void): void; + /** + * Scan regular expression matches in a given range , calling the given + * iterator function on each match. + */ + scanInRange(regex: RegExp, range: RangeCompatible, options: ScanContextOptions, + iterator: (params: ContextualBufferScanResult) => void): void; + + /** + * Scan regular expression matches in a given range in reverse order, + * calling the given iterator function on each match. + */ + backwardsScanInRange(regex: RegExp, range: RangeCompatible, iterator: + (params: BufferScanResult) => void): void; + /** + * Scan regular expression matches in a given range in reverse order, + * calling the given iterator function on each match. + */ + backwardsScanInRange(regex: RegExp, range: RangeCompatible, options: ScanContextOptions, + iterator: (params: ContextualBufferScanResult) => void): void; + + /** Replace all regular expression matches in the entire buffer. */ + replace(regex: RegExp, replacementText: string): number; + + // Buffer Range Details + /** Get the range spanning from [0, 0] to ::getEndPosition. */ + getRange(): Range; + + /** Get the number of lines in the buffer. */ + getLineCount(): number; + + /** Get the last 0-indexed row in the buffer. */ + getLastRow(): number; + + /** Get the first position in the buffer, which is always [0, 0]. */ + getFirstPosition(): Point; + + /** Get the maximal position in the buffer, where new text would be appended. */ + getEndPosition(): Point; + + /** Get the length of the buffer in characters. */ + getMaxCharacterIndex(): number; + + /** Get the range for the given row. */ + rangeForRow(row: number, includeNewline: boolean): Range; + + /** + * Convert a position in the buffer in row/column coordinates to an absolute + * character offset, inclusive of line ending characters. + */ + characterIndexForPosition(position: Point|[number, number]): number; + + /** + * Convert an absolute character offset, inclusive of newlines, to a position + * in the buffer in row/column coordinates. + */ + positionForCharacterIndex(offset: number): Point; + + /** Clip the given range so it starts and ends at valid positions. */ + clipRange(range: RangeCompatible): Range; + + /** Clip the given point so it is at a valid position in the buffer. */ + clipPosition(position: PointCompatible): Point; + + // Buffer Operations + /** Save the buffer. */ + save(): Promise; + + /** Save the buffer at a specific path. */ + saveAs(filePath: string): Promise; + + /** Reload the buffer's contents from disk. */ + reload(): void; + + /** Destroy the buffer, even if there are retainers for it. */ + destroy(): void; + + /** Returns whether or not this buffer is alive. */ + isAlive(): boolean; + + /** Returns whether or not this buffer has been destroyed. */ + isDestroyed(): boolean; + + /** Returns whether or not this buffer has a retainer. */ + isRetained(): boolean; + + /** + * Places a retainer on the buffer, preventing its destruction until the + * final retainer has called ::release(). + */ + retain(): TextBuffer; + + /** + * Releases a retainer on the buffer, destroying the buffer if there are + * no additional retainers. + */ + release(): TextBuffer; + + /** Identifies if the buffer belongs to multiple editors. */ + hasMultipleEditors(): boolean; +} + +/** Handles loading and activating available themes. */ +export interface ThemeManager { + // Event Subscription + /** + * Invoke callback when style sheet changes associated with updating the + * list of active themes have completed. + */ + onDidChangeActiveThemes(callback: () => void): Disposable; + + // Accessing Loaded Themes + /** Returns an Array of strings of all the loaded theme names. */ + getLoadedThemeNames(): string[]|undefined; + + /** Returns an Array of all the loaded themes. */ + getLoadedThemes(): Package[]|undefined; + + // Accessing Active Themes + /** Returns an Array of strings all the active theme names. */ + getActiveThemeNames(): string[]|undefined; + + /** Returns an Array of all the active themes. */ + getActiveThemes(): Package[]|undefined; + + // Managing Enabled Themes + /** Get the enabled theme names from the config. */ + getEnabledThemeNames(): string[]; +} + +// Events ===================================================================== +// The event objects that are passed into the callbacks which the user provides to +// specific API calls. + +export interface AddedKeystrokeResolverEvent { + /** + * The currently resolved keystroke string. If your function returns a falsy + * value, this is how Atom will resolve your keystroke. + */ + keystroke: string; + + /** + * The raw DOM 3 `KeyboardEvent` being resolved. See the DOM API documentation + * for more details. + */ + event: KeyboardEvent; + + /** The OS-specific name of the current keyboard layout. */ + layoutName: string; + + /** + * An object mapping DOM 3 `KeyboardEvent.code` values to objects with the + * typed character for that key in each modifier state, based on the current + * operating system layout. + */ + keymap: object; +} + +export interface BufferChangingEvent { + /** Range of the old text. */ + oldRange: Range; +} + +export interface BufferChangedEvent { + /** Range of the old text. */ + oldRange: Range; + + /** Range of the new text. */ + newRange: Range; + + /** String containing the text that was replaced. */ + oldText: string; + + /** String containing the text that was inserted. */ + newText: string; +} + +export interface BufferStoppedChangingEvent { + changes: TextChange[]; +} + +/** + * This custom subclass of CustomEvent exists to provide the ::abortKeyBinding + * method, as well as versions of the ::stopPropagation methods that record the + * intent to stop propagation so event bubbling can be properly simulated for + * detached elements. + */ +export interface CommandEvent extends CustomEvent { + keyBindingAborted: boolean; + propagationStopped: boolean; + + abortKeyBinding(): void; + stopPropagation(): CustomEvent; + stopImmediatePropagation(): CustomEvent; +} + +export interface CursorPositionChangedEvent { + oldBufferPosition: Point; + oldScreenPosition: Point; + newBufferPosition: Point; + newScreenPosition: Point; + textChanged: boolean; + cursor: Cursor; +} + +export interface DecorationPropsChangedEvent { + /** Object the old parameters the decoration used to have. */ + oldProperties: DecorationOptions; + + /** Object the new parameters the decoration now has */ + newProperties: DecorationOptions; +} + +export interface DisplayMarkerChangedEvent { + /** Point representing the former head buffer position. */ + oldHeadBufferPosition: Point; + + /** Point representing the new head buffer position. */ + newHeadBufferPosition: Point; + + // Point representing the former tail buffer position. */ + oldTailBufferPosition: Point; + + /** Point representing the new tail buffer position. */ + newTailBufferPosition: Point; + + /** Point representing the former head screen position. */ + oldHeadScreenPosition: Point; + + /** Point representing the new head screen position. */ + newHeadScreenPosition: Point; + + /** Point representing the former tail screen position. */ + oldTailScreenPosition: Point; + + /** Point representing the new tail screen position. */ + newTailScreenPosition: Point; + + /** Boolean indicating whether the marker was valid before the change. */ + wasValid: boolean; + + /** Boolean indicating whether the marker is now valid. */ + isValid: boolean; + + /** Boolean indicating whether the marker had a tail before the change. */ + hadTail: boolean; + + /** Boolean indicating whether the marker now has a tail */ + hasTail: boolean; + + /** + * -DEPRECATED- Object containing the marker's custom properties before the change. + * @deprecated + */ + oldProperties: object; + + /** + * -DEPRECATED- Object containing the marker's custom properties after the change. + * @deprecated + */ + newProperties: object; + + /** + * Boolean indicating whether this change was caused by a textual change to the + * buffer or whether the marker was manipulated directly via its public API. + */ + textChanged: boolean; +} + +export interface EditorChangedEvent { + /** A Point representing where the change started. */ + start: Point; + + /** A Point representing the replaced extent. */ + oldExtent: Point; + + /** A Point representing the replacement extent. */ + newExtent: Point; +} + +export interface ExceptionThrownEvent { + originalError: Error; + message: string; + url: string; + line: number; + column: number; +} + +export interface FailedKeybindingMatchEvent { + /** The string of keystrokes that failed to match the binding. */ + keystrokes: string; + + /** The DOM element that was the target of the most recent keyboard event. */ + keyboardEventTarget: Element; +} + +export interface FailedKeymapFileReadEvent { + /** The error message. */ + message: string; + + /** The error stack trace. */ + stack: string; +} + +export interface FileSavedEvent { + /** The path to which the buffer was saved. */ + path: string; +} + +export type FilesystemChangeEvent = Array<{ + /** A string describing the filesystem action that occurred. */ + action: "created"|"modified"|"deleted"|"renamed"; + + /** The absolute path to the filesystem entry that was acted upon. */ + path: string; + + /** + * For rename events, a string containing the filesystem entry's former + * absolute path. + */ + oldPath?: string; +}>; + +export interface FullKeybindingMatchEvent { + /** The string of keystrokes that matched the binding. */ + keystrokes: string; + + /** The KeyBinding that the keystrokes matched. */ + binding: KeyBinding; + + /** The DOM element that was the target of the most recent keyboard event. */ + keyboardEventTarget: Element; +} + +export interface HandleableErrorEvent { + /** The error object. */ + error: Error; + + /** + * Call this function to indicate you have handled the error. + * The error will not be thrown if this function is called. + */ + handle(): void; +} + +export interface KeymapLoadedEvent { + /** The path of the keymap file. */ + path: string; +} + +export interface MarkerChangedEvent { + /** Point representing the former head position. */ + oldHeadPosition: Point; + + /** Point representing the new head position. */ + newHeadPosition: Point; + + /** Point representing the former tail position. */ + oldTailPosition: Point; + + /** Point representing the new tail position. */ + newTailPosition: Point; + + /** Boolean indicating whether the marker was valid before the change. */ + wasValid: boolean; + + /** Boolean indicating whether the marker is now valid. */ + isValid: boolean; + + /** Boolean indicating whether the marker had a tail before the change. */ + hadTail: boolean; + + /** Boolean indicating whether the marker now has a tail. */ + hasTail: boolean; + + /** + * -DEPRECATED- Object containing the marker's custom properties before the change. + * @deprecated + */ + oldProperties: object; + + /** + * -DEPRECATED- Object containing the marker's custom properties after the change. + * @deprecated + */ + newProperties: object; + + /** + * Boolean indicating whether this change was caused by a textual + * change to the buffer or whether the marker was manipulated directly + * via its public API. + */ + textChanged: boolean; +} + +export interface PaneItemObservedEvent { + item: object; + pane: Pane; + index: number; +} + +export interface PaneListItemShiftedEvent { + /** The pane item that was added or removed. */ + item: object; + + /** A number indicating where the item is located. */ + index: number; +} + +export interface PaneItemMovedEvent { + /** The removed pane item. */ + item: object; + + /** A number indicating where the item was located. */ + oldIndex: number; + + /** A number indicating where the item is now located. */ + newIndex: number; +} + +export interface PaneItemOpenedEvent extends PaneItemObservedEvent { + uri: string; +} + +export interface PartialKeybindingMatchEvent { + /** The string of keystrokes that matched the binding. */ + keystrokes: string; + + /** The KeyBindings that the keystrokes partially matched. */ + partiallyMatchedBindings: KeyBinding[]; + + /** DOM element that was the target of the most recent keyboard event. */ + keyboardEventTarget: Element; +} + +export interface PathWatchErrorThrownEvent { + /** The error object. */ + error: Error; + + /** + * Call this function to indicate you have handled the error. + * The error will not be thrown if this function is called. + */ + handle(): void; +} + +export interface PreventableExceptionThrownEvent extends ExceptionThrownEvent { + preventDefault(): void; +} + +export interface RepoStatusChangedEvent { + path: string; + + /** + * This value can be passed to ::isStatusModified or ::isStatusNew to get more + * information. + */ + pathStatus: number; +} + +export interface SelectionChangedEvent { + oldBufferRange: Range; + oldScreenRange: Range; + newBufferRange: Range; + newScreenRange: Range; + selection: Selection; +} + +export interface StyleElementObservedEvent extends HTMLStyleElement { + sourcePath: string; + context: string; +} + +export interface TextEditorObservedEvent { + textEditor: TextEditor; + pane: Pane; + index: number; +} + +// Extendables ================================================================ +// Interfaces which can be augmented in order to provide additional type +// information under certain contexts. + +// NOTE: the config schema with these defaults can be found here: +// https://github.com/atom/atom/blob/v1.22.0/src/config-schema.js +/** + * Allows you to strongly type Atom configuration variables. Additional key:value + * pairings merged into this interface will result in configuration values under + * the value of each key being templated by the type of the associated value. + */ +export interface ConfigValues { + /** + * List of glob patterns. Files and directories matching these patterns will be + * ignored by some packages, such as the fuzzy finder and tree view. Individual + * packages might have additional config settings for ignoring names. + */ + "core.ignoredNames": string[]; + + /** + * Files and directories ignored by the current project's VCS system will be ignored + * by some packages, such as the fuzzy finder and find and replace. For example, + * projects using Git have these paths defined in the .gitignore file. Individual + * packages might have additional config settings for ignoring VCS ignored files and + * folders. + */ + "core.excludeVcsIgnoredPaths": boolean; + + /** + * Follow symbolic links when searching files and when opening files with the fuzzy + * finder. + */ + "core.followSymlinks": boolean; + + /** List of names of installed packages which are not loaded at startup. */ + "core.disabledPackages": string[]; + + /** List of names of installed packages which are not automatically updated. */ + "core.versionPinnedPackages": string[]; + + /** + * Associates scope names (e.g. "source.coffee") with arrays of file extensions + * and file names (e.g. ["Cakefile", ".coffee2"]). + */ + "core.customFileTypes": { + [key: string]: string[]; + }; + + /** Names of UI and syntax themes which will be used when Atom starts. */ + "core.themes": string[]; + + /** + * Trigger the system's beep sound when certain actions cannot be executed or + * there are no results. + */ + "core.audioBeep": boolean; + + /** Close corresponding editors when a file is deleted outside Atom. */ + "core.closeDeletedFileTabs": boolean; + + /** When the last tab of a pane is closed, remove that pane as well. */ + "core.destroyEmptyPanes": boolean; + + /** + * When a window with no open tabs or panes is given the 'Close Tab' command, + * close that window. + */ + "core.closeEmptyWindows": boolean; + + /** Default character set encoding to use when reading and writing files. */ + "core.fileEncoding": FileEncoding; + + /** + * When checked opens an untitled editor when loading a blank environment (such as + * with 'File > New Window' or when "Restore Previous Windows On Start" is unchecked); + * otherwise, no editor is opened when loading a blank environment. + * This setting has no effect when restoring a previous state. + */ + "core.openEmptyEditorOnStart": boolean; + + /** + * When selected 'no', a blank environment is loaded. When selected 'yes' and Atom + * is started from the icon or `atom` by itself from the command line, restores the + * last state of all Atom windows; otherwise a blank environment is loaded. When + * selected 'always', restores the last state of all Atom windows always, no matter + * how Atom is started. + */ + "core.restorePreviousWindowsOnStart": "no"|"yes"|"always"; + + /** How many recent projects to show in the Reopen Project menu. */ + "core.reopenProjectMenuCount": number; + + /** Automatically update Atom when a new release is available. */ + "core.automaticallyUpdate": boolean; + + /** Use detected proxy settings when calling the `apm` command-line tool. */ + "core.useProxySettingsWhenCallingApm": boolean; + + /** + * Allow items to be previewed without adding them to a pane permanently, such as + * when single clicking files in the tree view. + */ + "core.allowPendingPaneItems": boolean; + + /** + * Allow usage statistics and exception reports to be sent to the Atom team to help + * improve the product. + */ + "core.telemetryConsent": "limited"|"no"|"undecided"; + + /** Warn before opening files larger than this number of megabytes. */ + "core.warnOnLargeFileLimit": number; + + /** + * Choose the underlying implementation used to watch for filesystem changes. Emulating + * changes will miss any events caused by applications other than Atom, but may help + * prevent crashes or freezes. + */ + "core.fileSystemWatcher": "native"|"atom"; + + "editor.commentStart": string|null; + + "editor.commentEnd": string|null; + + "editor.increaseIndentPattern": string|null; + + "editor.decreaseIndentPattern": string|null; + + "editor.foldEndPattern": string|null; + + /** The name of the font family used for editor text. */ + "editor.fontFamily": string; + + /** Height in pixels of editor text. */ + "editor.fontSize": number; + + /** Height of editor lines, as a multiplier of font size. */ + "editor.lineHeight": string|number; + + /** Show cursor while there is a selection. */ + "editor.showCursorOnSelection": boolean; + + /** Render placeholders for invisible characters, such as tabs, spaces and newlines. */ + "editor.showInvisibles": boolean; + + /** Show indentation indicators in the editor. */ + "editor.showIndentGuide": boolean; + + /** Show line numbers in the editor's gutter. */ + "editor.showLineNumbers": boolean; + + /** Skip over tab-length runs of leading whitespace when moving the cursor. */ + "editor.atomicSoftTabs": boolean; + + /** Automatically indent the cursor when inserting a newline. */ + "editor.autoIndent": boolean; + + /** Automatically indent pasted text based on the indentation of the previous line. */ + "editor.autoIndentOnPaste": boolean; + + /** A string of non-word characters to define word boundaries. */ + "editor.nonWordCharacters": string; + + /** + * Identifies the length of a line which is used when wrapping text with the + * `Soft Wrap At Preferred Line Length` setting enabled, in number of characters. + */ + "editor.preferredLineLength": number; + + /** + * Defines the maximum width of the editor window before soft wrapping is enforced, + * in number of characters. + */ + "editor.maxScreenLineLength": number; + + /** Number of spaces used to represent a tab. */ + "editor.tabLength": number; + + /** + * Wraps lines that exceed the width of the window. When `Soft Wrap At Preferred + * Line Length` is set, it will wrap to the number of characters defined by the + * `Preferred Line Length` setting. + */ + "editor.softWrap": boolean; + + /** + * If the `Tab Type` config setting is set to "auto" and autodetection of tab type + * from buffer content fails, then this config setting determines whether a soft tab + * or a hard tab will be inserted when the Tab key is pressed. + */ + "editor.softTabs": boolean; + + /** + * Determine character inserted when Tab key is pressed. Possible values: "auto", + * "soft" and "hard". When set to "soft" or "hard", soft tabs (spaces) or hard tabs + * (tab characters) are used. When set to "auto", the editor auto-detects the tab + * type based on the contents of the buffer (it uses the first leading whitespace + * on a non-comment line), or uses the value of the Soft Tabs config setting if + * auto-detection fails. + */ + "editor.tabType": "auto"|"soft"|"hard"; + + /** + * Instead of wrapping lines to the window's width, wrap lines to the number of + * characters defined by the `Preferred Line Length` setting. This will only take + * effect when the soft wrap config setting is enabled globally or for the current + * language. + * **Note:** If you want to hide the wrap guide (the vertical line) you can disable + * the `wrap-guide` package. + */ + "editor.softWrapAtPreferredLineLength": boolean; + + /** + * When soft wrap is enabled, defines length of additional indentation applied to + * wrapped lines, in number of characters. + */ + "editor.softWrapHangingIndent": number; + + /** Determines how fast the editor scrolls when using a mouse or trackpad. */ + "editor.scrollSensitivity": number; + + /** Allow the editor to be scrolled past the end of the last line. */ + "editor.scrollPastEnd": boolean; + + /** + * Time interval in milliseconds within which text editing operations will be + * grouped together in the undo history. + */ + "editor.undoGroupingInterval": number; + + /** + * Show confirmation dialog when checking out the HEAD revision and discarding + * changes to current file since last commit. + */ + "editor.confirmCheckoutHeadRevision": boolean; + + /** + * A hash of characters Atom will use to render whitespace characters. Keys are + * whitespace character types, values are rendered characters (use value false to + * turn off individual whitespace character types). + */ + "editor.invisibles": Invisibles; + + /** + * Change the editor font size when pressing the Ctrl key and scrolling the mouse + * up/down. + */ + "editor.zoomFontWhenCtrlScrolling": boolean; + + // tslint:disable-next-line:no-any + [key: string]: any; +} + +/** + * Allows you to strongly type event emissions across your codebase. Additional + * key:value pairings merged into this interface will result in emissions under + * the value of each key being templated by the type of the associated value. + */ +export interface Emissions { + // tslint:disable-next-line:no-any + [key: string]: any; +} + +// Options ==================================================================== +// The option objects that the user is expected to fill out and provide to +// specific API call. + +export interface BufferLoadOptions { + /** The file's encoding. */ + encoding?: string; + + /** + * A function that returns a boolean indicating whether the buffer should + * be destroyed if its file is deleted. + */ + shouldDestroyOnFileDelete?(): boolean; +} + +export interface BuildEnvironmentOptions { + /** + * An object responsible for Atom's interaction with the browser process and host OS. + * Use buildDefaultApplicationDelegate for a default instance. + */ + applicationDelegate?: object; + + /** A window global. */ + window?: Window; + + /** A document global. */ + document?: Document; + + /** A path to the configuration directory (usually ~/.atom). */ + configDirPath?: string; + + /** + * A boolean indicating whether the Atom environment should save or load state + * from the file system. You probably want this to be false. + */ + enablePersistence?: boolean; +} + +export interface ContextMenuOptions { + /** The menu item's label. */ + label?: string; + + /** + * The command to invoke on the target of the right click that invoked the + * context menu. + */ + command?: string; + + /** + * Whether the menu item should be clickable. Disabled menu items typically + * appear grayed out. Defaults to true. + */ + enabled?: boolean; + + /** An array of additional items. */ + submenu?: ReadonlyArray; + + /** + * If you want to create a separator, provide an item with type: 'separator' + * and no other keys. + */ + type?: "separator"; + + /** Whether the menu item should appear in the menu. Defaults to true. */ + visible?: boolean; + + /** + * A function that is called on the item each time a context menu is created + * via a right click. + */ + created?(event: Event): void; + + /** + * A function that is called to determine whether to display this item on a + * given context menu deployment. + */ + shouldDisplay?(event: Event): void; +} + +export interface CopyMarkerOptions { + /** Whether or not the marker should be tailed. */ + tailed?: boolean; + + /** Creates the marker in a reversed orientation. */ + reversed?: boolean; + + /** Determines the rules by which changes to the buffer invalidate the marker. */ + invalidate?: "never"|"surround"|"overlap"|"inside"|"touch"; + + /** + * Indicates whether insertions at the start or end of the marked range should + * be interpreted as happening outside the marker. + */ + exclusive?: boolean; + + /** -DEPRECATED- Custom properties to be associated with the marker. */ + properties?: object; +} + +export interface DecorationLayerOptions extends SharedDecorationOptions { + /** One of several supported decoration types. */ + type?: "line"|"line-number"|"highlight"|"block"; +} + +export interface DecorationOptions extends SharedDecorationOptions { + /** One of several supported decoration types. */ + type?: "line"|"line-number"|"highlight"|"overlay"|"gutter"|"block"; + + /** The name of the gutter we're decorating, if type is "gutter". */ + gutterName?: string; +} + +export interface ErrorNotificationOptions extends NotificationOptions { + stack?: string; +} + +export interface FindDisplayMarkerOptions { + /** Only include markers starting at this Point in buffer coordinates. */ + startBufferPosition?: PointCompatible; + + /** Only include markers ending at this Point in buffer coordinates. */ + endBufferPosition?: PointCompatible; + + /** Only include markers starting at this Point in screen coordinates. */ + startScreenPosition?: PointCompatible; + + /** Only include markers ending at this Point in screen coordinates. */ + endScreenPosition?: PointCompatible; + + /** Only include markers starting inside this Range in buffer coordinates. */ + startsInBufferRange?: RangeCompatible; + + /** Only include markers ending inside this Range in buffer coordinates. */ + endsInBufferRange?: RangeCompatible; + + /** Only include markers starting inside this Range in screen coordinates. */ + startsInScreenRange?: RangeCompatible; + + /** Only include markers ending inside this Range in screen coordinates. */ + endsInScreenRange?: RangeCompatible; + + /** Only include markers starting at this row in buffer coordinates. */ + startBufferRow?: number; + + /** Only include markers ending at this row in buffer coordinates. */ + endBufferRow?: number; + + /** Only include markers starting at this row in screen coordinates. */ + startScreenRow?: number; + + /** Only include markers ending at this row in screen coordinates. */ + endScreenRow?: number; + + /** + * Only include markers intersecting this Array of [startRow, endRow] in + * buffer coordinates. + */ + intersectsBufferRowRange?: [number, number]; + + /** + * Only include markers intersecting this Array of [startRow, endRow] in + * screen coordinates. + */ + intersectsScreenRowRange?: [number, number]; + + /** Only include markers containing this Range in buffer coordinates. */ + containsBufferRange?: RangeCompatible; + + /** Only include markers containing this Point in buffer coordinates. */ + containsBufferPosition?: PointCompatible; + + /** Only include markers contained in this Range in buffer coordinates. */ + containedInBufferRange?: RangeCompatible; + + /** Only include markers contained in this Range in screen coordinates. */ + containedInScreenRange?: RangeCompatible; + + /** Only include markers intersecting this Range in buffer coordinates. */ + intersectsBufferRange?: RangeCompatible; + + /** Only include markers intersecting this Range in screen coordinates. */ + intersectsScreenRange?: RangeCompatible; +} + +export interface FindMarkerOptions { + /** Only include markers that start at the given Point. */ + startPosition?: PointCompatible; + + /** Only include markers that end at the given Point. */ + endPosition?: PointCompatible; + + /** Only include markers that start inside the given Range. */ + startsInRange?: RangeCompatible; + + /** Only include markers that end inside the given Range. */ + endsInRange?: RangeCompatible; + + /** Only include markers that contain the given Point, inclusive. */ + containsPoint?: PointCompatible; + + /** Only include markers that contain the given Range, inclusive. */ + containsRange?: RangeCompatible; + + /** Only include markers that start at the given row number. */ + startRow?: number; + + /** Only include markers that end at the given row number. */ + endRow?: number; + + /** Only include markers that intersect the given row number. */ + intersectsRow?: number; +} + +export interface MenuOptions { + /** The menu itme's label. */ + label: string; + + /** An array of sub menus. */ + submenu?: ReadonlyArray; + + /** The command to trigger when the item is clicked. */ + command?: string; +} + +export interface NodeProcessOptions { + /** The command to execute. */ + command: string; + + /** The array of arguments to pass to the command. */ + args?: ReadonlyArray; + + /** The options object to pass to Node's ChildProcess.spawn method. */ + options?: SpawnProcessOptions; + + /** + * The callback that receives a single argument which contains the standard + * output from the command. + */ + stdout?(data: string): void; + + /** + * The callback that receives a single argument which contains the standard + * error output from the command. + */ + stderr?(data: string): void; + + /** The callback which receives a single argument containing the exit status. */ + exit?(code: number): void; +} + +export interface NotificationOptions { + buttons?: Array<{ + className?: string; + onDidClick?(event: MouseEvent): void; + text?: string; + }>; + description?: string; + detail?: string; + dismissable?: boolean; + icon?: string; +} + +export interface ProcessOptions extends NodeProcessOptions { + /** + * Whether the command will automatically start when this BufferedProcess is + * created. + */ + autoStart?: boolean; +} + +export interface ScanContextOptions { + /** The number of lines before the matched line to include in the results object. */ + leadingContextLineCount?: number; + + /** The number of lines after the matched line to include in the results object. */ + trailingContextLineCount?: number; +} + +export interface SharedDecorationOptions { + /** + * This CSS class will be applied to the decorated line number, line, highlight, + * or overlay. + */ + class?: string; + + /** + * An HTMLElement or a model Object with a corresponding view registered. Only + * applicable to the gutter, overlay and block types. + */ + item?: HTMLElement; + + /** + * If true, the decoration will only be applied to the head of the DisplayMarker. + * Only applicable to the line and line-number types. + */ + onlyHead?: boolean; + + /** + * If true, the decoration will only be applied if the associated DisplayMarker + * is empty. Only applicable to the gutter, line, and line-number types. + */ + onlyEmpty?: boolean; + + /** + * If true, the decoration will only be applied if the associated DisplayMarker + * is non-empty. Only applicable to the gutter, line, and line-number types. + */ + onlyNonEmpty?: boolean; + + /** + * Only applicable to decorations of type overlay and block. Controls where the + * view is positioned relative to the TextEditorMarker. Values can be + * 'head' (the default) or 'tail' for overlay decorations, and 'before' (the default) + * or 'after' for block decorations. + */ + position?: "head"|"tail"|"before"|"after"; + + /** + * Only applicable to decorations of type overlay. Determines whether the decoration + * adjusts its horizontal or vertical position to remain fully visible when it would + * otherwise overflow the editor. Defaults to true. + */ + avoidOverflow?: boolean; +} + +export interface SpawnProcessOptions { + /** Current working directory of the child process. */ + cwd?: string; + + /** Environment key-value pairs. */ + env?: { [key: string]: string }; + + /** The child's stdio configuration. */ + stdio?: string|Array; + + /** Prepare child to run independently of its parent process. */ + detached?: boolean; + + /** Sets the user identity of the process. */ + uid?: number; + + /** Sets the group identity of the process. */ + gid?: number; + + /** + * If true, runs command inside of a shell. Uses "/bin/sh" on UNIX, and process.env.ComSpec + * on Windows. A different shell can be specified as a string. + */ + shell?: boolean | string; +} + +export interface TextInsertionOptions { + select?: boolean; + autoIndent?: boolean; + autoIndentNewline?: boolean; + autoDecreaseIndent?: boolean; + normalizeLineEndings?: boolean; + undo?: "skip"; +} + +/** The options for a Bootstrap 3 Tooltip class, which Atom uses a variant of. */ +export interface TooltipOptions { + /** Apply a CSS fade transition to the tooltip. */ + animation?: boolean; + + /** Appends the tooltip to a specific element. */ + container?: string|HTMLElement|false; + + /** + * Delay showing and hiding the tooltip (ms) - does not apply to manual + * trigger type. + */ + delay?: number|{ show: number, hide: number }; + + /** Allow HTML in the tooltip. */ + html?: boolean; + + /** How to position the tooltip. */ + placement?: "top"|"bottom"|"left"|"right"|"auto"; + + /** + * If a selector is provided, tooltip objects will be delegated to the + * specified targets. + */ + selector?: string; + + /** Base HTML to use when creating the tooltip. */ + template?: string; + + /** + * Default title value if title attribute isn't present. + * If a function is given, it will be called with its this reference set to + * the element that the tooltip is attached to. + */ + title?: string|HTMLElement|(() => string); + + /** + * How tooltip is triggered - click | hover | focus | manual. + * You may pass multiple triggers; separate them with a space. + */ + trigger?: string; +} + +export interface WorkspaceOpenOptions { + /** A number indicating which row to move the cursor to initially. Defaults to 0. */ + initialLine?: number; + + /** A number indicating which column to move the cursor to initially. Defaults to 0. */ + initialColumn?: number; + + /** + * Either 'left', 'right', 'up' or 'down'. If 'left', the item will be opened in + * leftmost pane of the current active pane's row. If 'right', the item will be + * opened in the rightmost pane of the current active pane's row. If only one pane + * exists in the row, a new pane will be created. If 'up', the item will be opened + * in topmost pane of the current active pane's column. If 'down', the item will be + * opened in the bottommost pane of the current active pane's column. If only one pane + * exists in the column, a new pane will be created. + */ + split?: "left"|"right"|"up"|"down"; + + /** + * A boolean indicating whether to call Pane::activate on containing pane. + * Defaults to true. + */ + activatePane?: boolean; + + /** + * A boolean indicating whether to call Pane::activateItem on containing pane. + * Defaults to true. + */ + activateItem?: boolean; + + /** + * A Boolean indicating whether or not the item should be opened in a pending state. + * Existing pending items in a pane are replaced with new pending items when they + * are opened. + */ + pending?: boolean; + + /** + * A boolean. If true, the workspace will attempt to activate an existing item for + * the given URI on any pane. If false, only the active pane will be searched for + * an existing item for the same URI. Defaults to false. + */ + searchAllPanes?: boolean; + + /** + * A String containing the name of the location in which this item should be opened. + * If omitted, Atom will fall back to the last location in which a user has placed + * an item with the same URI or, if this is a new URI, the default location specified + * by the item. + * NOTE: This option should almost always be omitted to honor user preference. + */ + location?: "left"|"right"|"bottom"|"center"; +} + +export interface WorkspaceScanOptions { + /** An array of glob patterns to search within. */ + paths?: ReadonlyArray; + + /** A function to be periodically called with the number of paths searched. */ + onPathsSearched?(pathsSearched: number): void; + + /** The number of lines before the matched line to include in the results object. */ + leadingContextLineCount?: number; + + /** The number of lines after the matched line to include in the results object. */ + trailingContextLineCount?: number; +} + +// Interfaces ================================================================= +// The requirements placed on object parameters for specific API calls. + +export interface Deserializer { + name: string; + deserialize(state: object): object; +} + +export interface DisposableLike { + dispose(): void; +} + +/** The types usable when constructing a point via the Point::fromObject method. */ +export type PointCompatible = PointLike|[number, number]; + +/** The interface that should be implemented for all "point-compatible" objects. */ +export interface PointLike { + /** A zero-indexed number representing the row of the Point. */ + row: number; + + /** A zero-indexed number representing the column of the Point. */ + column: number; +} + +/** The types usable when constructing a range via the Range::fromObject method. */ +export type RangeCompatible = + | RangeLike + | [PointLike, PointLike] + | [PointLike, [number, number]] + | [[number, number], PointLike] + | [[number, number], [number, number]]; + +/** The interface that should be implemented for all "range-compatible" objects. */ +export interface RangeLike { + /** A Point representing the start of the Range. */ + start: PointLike; + + /** A Point representing the end of the Range. */ + end: PointLike; +} + +/** An interface which all custom test runners should implement. */ +export type TestRunner = (params: TestRunnerParams) => Promise; + +// Structures ================================================================= +// The structures that are passed to the user by Atom following specific API calls. + +export interface BufferScanResult { + buffer: TextBuffer; + lineText: string; + match: RegExpExecArray; + matchText: string; + range: Range; + replace(replacementText: string): void; + stop(): void; + stopped: boolean; +} + +export interface CancellablePromise extends Promise { + cancel(): void; +} + +export interface ContextualBufferScanResult extends BufferScanResult { + leadingContextLines: string[]; + trailingContextLines: string[]; +} + +export type FileEncoding = + | "iso88596" // Arabic (ISO 8859-6) + | "windows1256" // Arabic (Windows 1256) + | "iso88594" // Baltic (ISO 8859-4) + | "windows1257" // Baltic (Windows 1257) + | "iso885914" // Celtic (ISO 8859-14) + | "iso88592" // Central European (ISO 8859-2) + | "windows1250" // Central European (Windows 1250) + | "gb18030" // Chinese (GB18030) + | "gbk" // Chinese (GBK) + | "cp950" // Traditional Chinese (Big5) + | "big5hkscs" // Traditional Chinese (Big5-HKSCS) + | "cp866" // Cyrillic (CP 866) + | "iso88595" // Cyrillic (ISO 8859-5) + | "koi8r" // Cyrillic (KOI8-R) + | "koi8u" // Cyrillic (KOI8-U) + | "windows1251" // Cyrillic (Windows 1251) + | "cp437" // DOS (CP 437) + | "cp850" // DOS (CP 850) + | "iso885913" // Estonian (ISO 8859-13) + | "iso88597" // Greek (ISO 8859-7) + | "windows1253" // Greek (Windows 1253) + | "iso88598" // Hebrew (ISO 8859-8) + | "windows1255" // Hebrew (Windows 1255) + | "cp932" // Japanese (CP 932) + | "eucjp" // Japanese (EUC-JP) + | "shiftjis" // Japanese (Shift JIS) + | "euckr" // Korean (EUC-KR) + | "iso885910" // Nordic (ISO 8859-10) + | "iso885916" // Romanian (ISO 8859-16) + | "iso88599" // Turkish (ISO 8859-9) + | "windows1254" // Turkish (Windows 1254) + | "utf8" // Unicode (UTF-8) + | "utf16le" // Unicode (UTF-16 LE) + | "utf16be" // Unicode (UTF-16 BE) + | "windows1258" // Vietnamese (Windows 1258) + | "iso88591" // Western (ISO 8859-1) + | "iso88593" // Western (ISO 8859-3) + | "iso885915" // Western (ISO 8859-15) + | "macroman" // Western (Mac Roman) + | "windows1252"; // Western (Windows 1252) + +export interface GrammarRule { + // https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee + // This is private. Don't go down the rabbit hole. + rule: object; + scopeName: string; + contentScopeName: string; +} + +export interface GrammarToken { + value: string; + scopes: string[]; +} + +export interface Invisibles { + /** + * Character used to render newline characters (\n) when the `Show Invisibles` + * setting is enabled. + */ + eol?: boolean|string; + + /** + * Character used to render leading and trailing space characters when the + * `Show Invisibles` setting is enabled. + */ + space?: boolean|string; + + /** + * Character used to render hard tab characters (\t) when the `Show Invisibles` + * setting is enabled. + */ + tab?: boolean|string; + + /** + * Character used to render carriage return characters (for Microsoft-style line + * endings) when the `Show Invisibles` setting is enabled. + */ + cr?: boolean|string; +} + +export interface KeyBinding { + // Properties + enabled: boolean; + source: string; + command: string; + keystrokes: string; + keystrokeArray: string[]; + keystrokeCount: number; + selector: string; + specificity: number; + + // Comparison + /** Determines whether the given keystroke matches any contained within this binding. */ + matches(keystroke: string): boolean; + + /** + * Compare another KeyBinding to this instance. + * Returns <= -1 if the argument is considered lesser or of lower priority. + * Returns 0 if this binding is equivalent to the argument. + * Returns >= 1 if the argument is considered greater or of higher priority. + */ + compare(other: KeyBinding): number; +} + +export interface ProjectHistory { + paths: string[]; + lastOpened: Date; +} + +export interface ScandalResult { + filePath: string; + matches: Array<{ + matchText: string; + lineText: string; + lineTextOffset: number; + range: [[number, number], [number, number]]; + leadingContextLines: string[]; + trailingContextLines: string[]; + }>; +} + +export interface TestRunnerParams { + /** An array of paths to tests to run. Could be paths to files or directories. */ + testPaths: string[]; + + /** + * A function that can be called to construct an instance of the atom global. + * No atom global will be explicitly assigned, but you can assign one in your + * runner if desired. + */ + buildAtomEnvironment(options: BuildEnvironmentOptions): AtomEnvironment; + + /** + * A function that builds a default instance of the application delegate, suitable + * to be passed as the applicationDelegate parameter to buildAtomEnvironment. + */ + buildDefaultApplicationDelegate(): object; + + /** An optional path to a log file to which test output should be logged. */ + logFile: string; + + /** + * A boolean indicating whether or not the tests are being run from the command + * line via atom --test. + */ + headless: boolean; +} + +export interface TextChange { + newExtent: Point; + oldExtent: Point; + newRange: Range; + oldRange: Range; + newText: string; + oldText: string; + start: Point; +} + +/** Result returned by `Grammar.tokenizeLine`. */ +export interface TokenizeLineResult { + /** The string of text that was tokenized. */ + line: string; + + /** + * An array of integer scope ids and strings. Positive ids indicate the + * beginning of a scope, and negative tags indicate the end. To resolve ids + * to scope names, call GrammarRegistry::scopeForId with the absolute + * value of the id. + */ + tags: Array; + + /** + * This is a dynamic property. Invoking it will incur additional overhead, + * but will automatically translate the `tags` into token objects with `value` + * and `scopes` properties. + */ + tokens: GrammarToken[]; + + /** + * An array of rules representing the tokenized state at the end of the line. + * These should be passed back into this method when tokenizing the next line + * in the file. + */ + ruleStack: GrammarRule[]; +} + +/** + * This tooltip class is derived from Bootstrap 3, but modified to not require + * jQuery, which is an expensive dependency we want to eliminate. + */ +export interface Tooltip { + options: TooltipOptions; + enabled: boolean; + timeout: number; + hoverState: "in"|"out"|null; + element: JQuery|HTMLElement; + + getTitle(): string; + getTooltipElement(): HTMLElement; + getArrowElement(): HTMLElement; + enable(): void; + disable(): void; + toggleEnabled(): void; + toggle(): void; + recalculatePosition(): void; +} + +export interface ViewModel { + getTitle: () => string; +} + +export interface WindowLoadSettings { + appVersion: string; + atomHome: string; + devMode: boolean; + resourcePath: string; + safeMode: boolean; + env?: { [key: string]: string|undefined }; + profileStartup?: boolean; +} diff --git a/types/atom/linter/config.d.ts b/types/atom/linter/config.d.ts new file mode 100644 index 0000000000..c70728fff5 --- /dev/null +++ b/types/atom/linter/config.d.ts @@ -0,0 +1,26 @@ +import "../index"; + +declare module "atom" { + interface ConfigValues { + /** Lint tabs while they are still in preview status. */ + "linter.lintPreviewTabs": boolean; + + /** Lint files automatically when they are opened. */ + "linter.lintOnOpen": boolean; + + /** + * Lint files while typing, without the need to save (only for supported + * providers). + */ + "linter.lintOnChange": boolean; + + /** Interval at which linting is done as you type (in ms). */ + "linter.lintOnChangeInterval": number; + + /** Ignore files matching this Glob. */ + "linter.ignoreGlob": string; + + /** Disabled providers. */ + "linter.disabledProviders": string[]; + } +} diff --git a/types/atom/linter.d.ts b/types/atom/linter/index.d.ts similarity index 79% rename from types/atom/linter.d.ts rename to types/atom/linter/index.d.ts index 32f6923adc..bf085d9859 100644 --- a/types/atom/linter.d.ts +++ b/types/atom/linter/index.d.ts @@ -1,9 +1,13 @@ // Linter 2.x // https://atom.io/packages/linter +/// + +import { Disposable, Point, Range, TextEditor } from "../index"; + export interface ReplacementSolution { title?: string; - position: TextBuffer.Range; + position: Range; priority?: number; currentText?: string; replaceWith: string; @@ -11,7 +15,7 @@ export interface ReplacementSolution { export interface CallbackSolution { title?: string; - position: TextBuffer.Range; + position: Range; priority?: number; // tslint:disable-next-line:no-any apply(): any; @@ -24,7 +28,7 @@ export interface Message { file: string; /** The range of the message in the editor. */ - position: TextBuffer.Range; + position: Range; }; /** A reference to a different location in the editor. */ @@ -33,7 +37,7 @@ export interface Message { file: string; /** The point being referenced in that file. */ - position?: TextBuffer.Point; + position?: Point; }; /** An HTTP link to a resource explaining the issue. Default is a google search. */ @@ -51,7 +55,8 @@ export interface Message { /** Possible solutions (which the user can invoke at will). */ solutions?: Array; - /** Markdown long description of the error. Accepts a callback so that you can + /** + * Markdown long description of the error. Accepts a callback so that you can * do things like HTTP requests. */ description?: string|(() => Promise|string); @@ -63,8 +68,8 @@ export interface IndieDelegate { clearMessages(): void; setMessages(filePath: string, messages: Message[]): void; setAllMessages(messages: Message[]): void; - onDidUpdate(callback: () => void): EventKit.Disposable; - onDidDestroy(callback: () => void): EventKit.Disposable; + onDidUpdate(callback: () => void): Disposable; + onDidDestroy(callback: () => void): Disposable; dispose(): void; } @@ -73,5 +78,5 @@ export interface LinterProvider { scope: "file"|"project"; lintsOnChange: boolean; grammarScopes: string[]; - lint(textEditor: AtomCore.TextEditor): Message[]|void|Promise; + lint(textEditor: TextEditor): Message[]|void|Promise; } diff --git a/types/atom/status-bar/config.d.ts b/types/atom/status-bar/config.d.ts new file mode 100644 index 0000000000..1561030a84 --- /dev/null +++ b/types/atom/status-bar/config.d.ts @@ -0,0 +1,23 @@ +import "../index"; + +declare module "atom" { + interface ConfigValues { + /** Show status bar at the bottom of the workspace. */ + "status-bar.isVisible": boolean; + + /** Fit the status-bar to the window's full-width. */ + "status-bar.fullWidth": boolean; + + /** + * Format for the cursor position status bar element, where %L is the line + * number and %C is the column number. + */ + "status-bar.cursorPositionFormat": string; + + /** + * Format for the selection count status bar element, where %L is the line + * count and %C is the character count. + */ + "status-bar.selectionCountFormat": string; + } +} diff --git a/types/atom/status-bar.d.ts b/types/atom/status-bar/index.d.ts similarity index 75% rename from types/atom/status-bar.d.ts rename to types/atom/status-bar/index.d.ts index 9921209241..3cc4a99a59 100644 --- a/types/atom/status-bar.d.ts +++ b/types/atom/status-bar/index.d.ts @@ -1,13 +1,17 @@ // Status Bar 1.x // https://atom.io/packages/status-bar +/// + export interface AddTileOptions { - /** A DOM element, a jQuery object, or a model object for which a view provider + /** + * A DOM element, a jQuery object, or a model object for which a view provider * has been registered in the the view registry. */ item: object; - /** Determines the placement of the tile within the status bar. Lower priority + /** + * Determines the placement of the tile within the status bar. Lower priority * will result in closer placement to the anchor. */ priority: number; @@ -25,12 +29,14 @@ export interface Tile { } export interface StatusBar { - /** Add a tile to the left side of the status bar. Lower priority tiles are placed + /** + * Add a tile to the left side of the status bar. Lower priority tiles are placed * further to the left. */ addLeftTile(options: AddTileOptions): Tile; - /** Add a tile to the right side of the status bar. Lower priority tiles are placed + /** + * Add a tile to the right side of the status bar. Lower priority tiles are placed * further to the right. */ addRightTile(options: AddTileOptions): Tile; diff --git a/types/atom/tsconfig.json b/types/atom/tsconfig.json index a91f83aa7b..a58ec7b74c 100644 --- a/types/atom/tsconfig.json +++ b/types/atom/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,8 +20,8 @@ "files": [ "index.d.ts", "atom-tests.ts", - "autocomplete-plus.d.ts", - "linter.d.ts", - "status-bar.d.ts" + "autocomplete-plus/index.d.ts", + "linter/index.d.ts", + "status-bar/index.d.ts" ] } diff --git a/types/atom/tslint.json b/types/atom/tslint.json index de840b74fe..4c3e6e9036 100644 --- a/types/atom/tslint.json +++ b/types/atom/tslint.json @@ -2,36 +2,8 @@ "extends": "dtslint/dt.json", "rules": { "await-promise": [true, "CancellablePromise"], - "class-name": true, "indent": [true, "spaces", 4], - "jsdoc-format": true, - "max-line-length": [true, 110], - "quotemark": [true, "double", "avoid-escape"], - "trailing-comma": [true, { - "multiline": { "objects": "always", "arrays": "always", "functions": "never" }, - "singleline": { "objects": "never", "arrays": "never", "functions": "never" } - }], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type", - "check-typecast", - "check-rest-spread", - "check-preblock" - ], - // Soon to be defaults. - "arrow-return-shorthand": [true, "multiline"], - "no-any": true, - "no-floating-promises": true, - "no-unbound-method": true, - "no-unsafe-any": true, - "number-literal-format": true, - "restrict-plus-operands": true, - "return-undefined": true, - "switch-final-break": true + "max-line-length": [true, 100], + "no-any": true } } diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 65c5b55846..76a2c5f319 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -355,6 +355,12 @@ export class Popup { domain: string, /** your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard */ clientId?: string, + /** + * identity provider whose login page will be displayed in the popup. + * If omitted the hosted login page is used. + * {@link https://auth0.com/docs/identityproviders} + */ + connection?: string, /** url that the Auth0 will redirect after Auth with the Authorization Response */ redirectUri: string, /** diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 0a7c799cc2..d24cb40081 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for auth0 2.4 +// Type definitions for auth0 2.5 // Project: https://github.com/auth0/node-auth0 // Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -87,6 +87,84 @@ export interface Rule { order?: number; } + +export interface Client { + /** + * The name of the client. + */ + name?: string; + /** + * Free text description of the purpose of the Client. (Max character length: `140`). + */ + description?: string; + /** + * The id of the client. + */ + client_id?: string; + /** + * The client secret, it must not be public. + */ + client_secret?: string; + /** + * The type of application this client represents. + */ + app_type?: string; + /** + * The URL of the client logo (recommended size: 150x150). + */ + logo_uri?: string; + /** + * Whether this client a first party client or not. + */ + is_first_party?: boolean; + /** + * Whether this client will conform to strict OIDC specifications. + */ + oidc_conformant?: boolean; + /** + * The URLs that Auth0 can use to as a callback for the client. + */ + callbacks?: string[]; + allowed_origins?: string[]; + web_origins?: string[]; + client_aliases?: string[]; + allowed_clients?: string[]; + allowed_logout_urls?: string[]; + jwt_configuration?: any; + /** + * Client signing keys. + */ + signing_keys?: string[]; + encryption_key?: any; + sso?: boolean; + /** + * `true` to disable Single Sign On, `false` otherwise (default: `false`) + */ + sso_disabled?: boolean; + /** + * `true` if this client can be used to make cross-origin authentication requests, `false` otherwise (default: `false`) + */ + cross_origin_auth?: boolean; + /** + * Url fo the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page. + */ + cross_origin_loc?: string; + /** + * `true` if the custom login page is to be used, `false` otherwise. (default: `true`) + */ + custom_login_page_on?: boolean; + custom_login_page?: string; + custom_login_page_preview?: string; + form_template?: string; + addons?: any; + /** + * Defines the requested authentication method for the token endpoint. Possible values are 'none' (public client without a client secret), 'client_secret_post' (client uses HTTP POST parameters) or 'client_secret_basic' (client uses HTTP Basic) ['none' or 'client_secret_post' or 'client_secret_basic'] + */ + token_endpoint_auth_method?: string; + client_metadata?: any; + mobile?: any; +} + export interface User { email?: string; email_verified?: boolean; @@ -338,21 +416,22 @@ export class ManagementClient { // Clients - getClients(): Promise; - getClients(cb: (err: Error, data: any) => void): void; + getClients(): Promise; + getClients(cb: (err: Error, clients: Client[]) => void): void; - getClient(params: ClientParams): Promise; - getClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + getClient(params: ClientParams): Promise; + getClient(params: ClientParams, cb: (err: Error, client: Client) => void): void; - createClient(data: Data): Promise; - createClient(data: Data, cb: (err: Error, data: any) => void): void; + createClient(data: Data): Promise; + createClient(data: Data, cb: (err: Error, client: Client) => void): void; - updateClient(params: ClientParams, data: Data): Promise; - updateClient(params: ClientParams, data: Data, cb: (err: Error, data: any) => void): void; + updateClient(params: ClientParams, data: Data): Promise; + updateClient(params: ClientParams, data: Data, cb: (err: Error, client: Client) => void): void; - deleteClient(params: ClientParams): Promise; - deleteClient(params: ClientParams, cb: (err: Error, data: any) => void): void; + deleteClient(params: ClientParams): Promise; + deleteClient(params: ClientParams, cb: (err: Error) => void): void; + // Client Grants getClientGrants(): Promise; getClientGrants(cb: (err: Error, data: any) => void): void; @@ -450,8 +529,8 @@ export class ManagementClient { deleteEmailProvider(): Promise; deleteEmailProvider(cb?: (err: Error, data: any) => void): void; - updateEmailProvider(data: Data): Promise; - updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void; + updateEmailProvider(params: {}, data: Data): Promise; + updateEmailProvider(params: {}, data: Data, cb?: (err: Error, data: any) => void): void; // Statistics diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 7f01a53e3a..969c703478 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -179,6 +179,7 @@ declare namespace autobahn { interface ISubscribeOptions { match?: string; + get_retained?: boolean; } interface IRegisterOptions { diff --git a/types/aws-iot-device-sdk/index.d.ts b/types/aws-iot-device-sdk/index.d.ts index 38cf00840d..f2bcab818c 100644 --- a/types/aws-iot-device-sdk/index.d.ts +++ b/types/aws-iot-device-sdk/index.d.ts @@ -32,19 +32,19 @@ export interface DeviceOptions extends mqtt.IClientOptions { * same as certPath, but can also accept a buffer containing client * certificate data */ - clientCert?: string; + clientCert?: string | Buffer; /** * same as keyPath, but can also accept a buffer containing private key * data */ - privateKey?: string; + privateKey?: string | Buffer; /** * same as caPath, but can also accept a buffer containing CA certificate * data */ - caCert?: string; + caCert?: string | Buffer; /** * set to "true" to automatically re-subscribe to topics after diff --git a/types/aws-lambda-mock-context/index.d.ts b/types/aws-lambda-mock-context/index.d.ts index 0ccd43c876..6fc5fda67a 100644 --- a/types/aws-lambda-mock-context/index.d.ts +++ b/types/aws-lambda-mock-context/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/moskalyk/typed-aws-lambda-mock-context // Definitions by: Morgan Moskalyk , Anand Nimkar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 declare function context(options?: Options): Context; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 4e404fcd55..ebd31429de 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -4,6 +4,7 @@ var anyObj: any = { abc: 123 }; var num: number = 5; var error: Error = new Error(); var b: boolean = true; +var apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; var apiGwEvt: AWSLambda.APIGatewayEvent; var customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; var clientCtx: AWSLambda.ClientContext; @@ -22,33 +23,33 @@ var snsEvtRec: AWSLambda.SNSEventRecord; var snsMsg: AWSLambda.SNSMessage; var snsMsgAttr: AWSLambda.SNSMessageAttribute; var snsMsgAttrs: AWSLambda.SNSMessageAttributes; -var S3EvtRec: AWSLambda.S3EventRecord = { +var S3EvtRec: AWSLambda.S3EventRecord = { eventVersion: '2.0', eventSource: 'aws:s3', awsRegion: 'us-east-1', eventTime: '1970-01-01T00:00:00.000Z', eventName: 'ObjectCreated:Put', - userIdentity: { + userIdentity: { principalId: 'AIDAJDPLRKLG7UEXAMPLE' }, - requestParameters:{ + requestParameters:{ sourceIPAddress: '127.0.0.1' }, - responseElements: { + responseElements: { 'x-amz-request-id': 'C3D13FE58DE4C810', 'x-amz-id-2': 'FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD' }, - s3: { + s3: { s3SchemaVersion: '1.0', configurationId: 'testConfigRule', - bucket: { + bucket: { name: 'mybucket', - ownerIdentity: { + ownerIdentity: { principalId: 'A3NL1KOZZKExample' }, arn: 'arn:aws:s3:::mybucket' }, - object: { + object: { key: 'HappyFace.jpg', size: 1024, eTag: 'd41d8cd98f00b204e9800998ecf8427e', @@ -65,6 +66,28 @@ var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; +/* API Gateway Event request context */ +str = apiGwEvtReqCtx.accountId; +str = apiGwEvtReqCtx.apiId; +authResponseContext = apiGwEvtReqCtx.authorizer; +str = apiGwEvtReqCtx.httpMethod; +str = apiGwEvtReqCtx.identity.accessKey; +str = apiGwEvtReqCtx.identity.accountId; +str = apiGwEvtReqCtx.identity.apiKey; +str = apiGwEvtReqCtx.identity.caller; +str = apiGwEvtReqCtx.identity.cognitoAuthenticationProvider; +str = apiGwEvtReqCtx.identity.cognitoAuthenticationType; +str = apiGwEvtReqCtx.identity.cognitoIdentityId; +str = apiGwEvtReqCtx.identity.cognitoIdentityPoolId; +str = apiGwEvtReqCtx.identity.sourceIp; +str = apiGwEvtReqCtx.identity.user; +str = apiGwEvtReqCtx.identity.userAgent; +str = apiGwEvtReqCtx.identity.userArn; +str = apiGwEvtReqCtx.stage; +str = apiGwEvtReqCtx.requestId; +str = apiGwEvtReqCtx.resourceId; +str = apiGwEvtReqCtx.resourcePath; + /* API Gateway Event */ str = apiGwEvt.body; str = apiGwEvt.headers["example"]; @@ -74,31 +97,17 @@ str = apiGwEvt.path; str = apiGwEvt.pathParameters["example"]; str = apiGwEvt.queryStringParameters["example"]; str = apiGwEvt.stageVariables["example"]; -str = apiGwEvt.requestContext.accountId; -str = apiGwEvt.requestContext.apiId; -str = apiGwEvt.requestContext.httpMethod; -str = apiGwEvt.requestContext.identity.accessKey; -str = apiGwEvt.requestContext.identity.accountId; -str = apiGwEvt.requestContext.identity.apiKey; -str = apiGwEvt.requestContext.identity.caller; -str = apiGwEvt.requestContext.identity.cognitoAuthenticationProvider; -str = apiGwEvt.requestContext.identity.cognitoAuthenticationType; -str = apiGwEvt.requestContext.identity.cognitoIdentityId; -str = apiGwEvt.requestContext.identity.cognitoIdentityPoolId; -str = apiGwEvt.requestContext.identity.sourceIp; -str = apiGwEvt.requestContext.identity.user; -str = apiGwEvt.requestContext.identity.userAgent; -str = apiGwEvt.requestContext.identity.userArn; -str = apiGwEvt.requestContext.stage; -str = apiGwEvt.requestContext.requestId; -str = apiGwEvt.requestContext.resourceId; -str = apiGwEvt.requestContext.resourcePath; +apiGwEvtReqCtx = apiGwEvt.requestContext; str = apiGwEvt.resource; /* API Gateway CustomAuthorizer Event */ str = customAuthorizerEvt.type; -str = customAuthorizerEvt.authorizationToken; str = customAuthorizerEvt.methodArn; +str = customAuthorizerEvt.authorizationToken; +str = apiGwEvt.pathParameters["example"]; +str = apiGwEvt.queryStringParameters["example"]; +str = apiGwEvt.stageVariables["example"]; +apiGwEvtReqCtx = apiGwEvt.requestContext; /* SNS Event */ snsEvtRecs = snsEvt.Records; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index b1ca69405b..3b9e31f14c 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -8,9 +8,36 @@ // Yoriki Yamaguchi // wwwy3y3 // Ishaan Malhi +// Daniel Cottone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +// API Gateway "event" request context +interface APIGatewayEventRequestContext { + accountId: string; + apiId: string; + authorizer?: AuthResponseContext | null | undefined; + httpMethod: string; + identity: { + accessKey: string | null; + accountId: string | null; + apiKey: string | null; + caller: string | null; + cognitoAuthenticationProvider: string | null; + cognitoAuthenticationType: string | null; + cognitoIdentityId: string | null; + cognitoIdentityPoolId: string | null; + sourceIp: string; + user: string | null; + userAgent: string | null; + userArn: string | null; + }, + stage: string; + requestId: string; + resourceId: string; + resourcePath: string; +} + // API Gateway "event" interface APIGatewayEvent { body: string | null; @@ -21,37 +48,19 @@ interface APIGatewayEvent { pathParameters: { [name: string]: string } | null; queryStringParameters: { [name: string]: string } | null; stageVariables: { [name: string]: string } | null; - requestContext: { - accountId: string; - apiId: string; - httpMethod: string; - identity: { - accessKey: string | null; - accountId: string | null; - apiKey: string | null; - caller: string | null; - cognitoAuthenticationProvider: string | null; - cognitoAuthenticationType: string | null; - cognitoIdentityId: string | null; - cognitoIdentityPoolId: string | null; - sourceIp: string; - user: string | null; - userAgent: string | null; - userArn: string | null; - }, - stage: string; - requestId: string; - resourceId: string; - resourcePath: string; - }; + requestContext: APIGatewayEventRequestContext; resource: string; } // API Gateway CustomAuthorizer "event" interface CustomAuthorizerEvent { type: string; - authorizationToken: string; methodArn: string; + authorizationToken?: string; + headers?: { [name: string]: string }; + pathParameters?: { [name: string]: string } | null; + queryStringParameters?: { [name: string]: string } | null; + requestContext?: APIGatewayEventRequestContext; } // SNS "event" @@ -323,9 +332,9 @@ interface PolicyDocument { * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ interface Statement { - Action: string | [string]; + Action: string | string[]; Effect: string; - Resource: string | [string]; + Resource: string | string[]; } /** diff --git a/types/aws-serverless-express/index.d.ts b/types/aws-serverless-express/index.d.ts index e612d5d8d6..02ef0d846a 100644 --- a/types/aws-serverless-express/index.d.ts +++ b/types/aws-serverless-express/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/awslabs/aws-serverless-express // Definitions by: Ben Speakman , Josh Caffey , Matthias Meyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// import * as http from 'http'; diff --git a/types/babel-generator/index.d.ts b/types/babel-generator/index.d.ts index 3b3d8126e9..2e34d158fc 100644 --- a/types/babel-generator/index.d.ts +++ b/types/babel-generator/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Troy Gerwien // Johnny Estilles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as t from 'babel-types'; diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 682550b161..df420c17bd 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -600,185 +600,185 @@ export class NodePath { addComments(type: string, comments: any[]): void; // ------------------------- isXXX ------------------------- - isArrayExpression(opts?: object): boolean; - isAssignmentExpression(opts?: object): boolean; - isBinaryExpression(opts?: object): boolean; - isDirective(opts?: object): boolean; - isDirectiveLiteral(opts?: object): boolean; - isBlockStatement(opts?: object): boolean; - isBreakStatement(opts?: object): boolean; - isCallExpression(opts?: object): boolean; - isCatchClause(opts?: object): boolean; - isConditionalExpression(opts?: object): boolean; - isContinueStatement(opts?: object): boolean; - isDebuggerStatement(opts?: object): boolean; - isDoWhileStatement(opts?: object): boolean; - isEmptyStatement(opts?: object): boolean; - isExpressionStatement(opts?: object): boolean; - isFile(opts?: object): boolean; - isForInStatement(opts?: object): boolean; - isForStatement(opts?: object): boolean; - isFunctionDeclaration(opts?: object): boolean; - isFunctionExpression(opts?: object): boolean; - isIdentifier(opts?: object): boolean; - isIfStatement(opts?: object): boolean; - isLabeledStatement(opts?: object): boolean; - isStringLiteral(opts?: object): boolean; - isNumericLiteral(opts?: object): boolean; - isNullLiteral(opts?: object): boolean; - isBooleanLiteral(opts?: object): boolean; - isRegExpLiteral(opts?: object): boolean; - isLogicalExpression(opts?: object): boolean; - isMemberExpression(opts?: object): boolean; - isNewExpression(opts?: object): boolean; - isProgram(opts?: object): boolean; - isObjectExpression(opts?: object): boolean; - isObjectMethod(opts?: object): boolean; - isObjectProperty(opts?: object): boolean; - isRestElement(opts?: object): boolean; - isReturnStatement(opts?: object): boolean; - isSequenceExpression(opts?: object): boolean; - isSwitchCase(opts?: object): boolean; - isSwitchStatement(opts?: object): boolean; - isThisExpression(opts?: object): boolean; - isThrowStatement(opts?: object): boolean; - isTryStatement(opts?: object): boolean; - isUnaryExpression(opts?: object): boolean; - isUpdateExpression(opts?: object): boolean; - isVariableDeclaration(opts?: object): boolean; - isVariableDeclarator(opts?: object): boolean; - isWhileStatement(opts?: object): boolean; - isWithStatement(opts?: object): boolean; - isAssignmentPattern(opts?: object): boolean; - isArrayPattern(opts?: object): boolean; - isArrowFunctionExpression(opts?: object): boolean; - isClassBody(opts?: object): boolean; - isClassDeclaration(opts?: object): boolean; - isClassExpression(opts?: object): boolean; - isExportAllDeclaration(opts?: object): boolean; - isExportDefaultDeclaration(opts?: object): boolean; - isExportNamedDeclaration(opts?: object): boolean; - isExportSpecifier(opts?: object): boolean; - isForOfStatement(opts?: object): boolean; - isImportDeclaration(opts?: object): boolean; - isImportDefaultSpecifier(opts?: object): boolean; - isImportNamespaceSpecifier(opts?: object): boolean; - isImportSpecifier(opts?: object): boolean; - isMetaProperty(opts?: object): boolean; - isClassMethod(opts?: object): boolean; - isObjectPattern(opts?: object): boolean; - isSpreadElement(opts?: object): boolean; - isSuper(opts?: object): boolean; - isTaggedTemplateExpression(opts?: object): boolean; - isTemplateElement(opts?: object): boolean; - isTemplateLiteral(opts?: object): boolean; - isYieldExpression(opts?: object): boolean; - isAnyTypeAnnotation(opts?: object): boolean; - isArrayTypeAnnotation(opts?: object): boolean; - isBooleanTypeAnnotation(opts?: object): boolean; - isBooleanLiteralTypeAnnotation(opts?: object): boolean; - isNullLiteralTypeAnnotation(opts?: object): boolean; - isClassImplements(opts?: object): boolean; - isClassProperty(opts?: object): boolean; - isDeclareClass(opts?: object): boolean; - isDeclareFunction(opts?: object): boolean; - isDeclareInterface(opts?: object): boolean; - isDeclareModule(opts?: object): boolean; - isDeclareTypeAlias(opts?: object): boolean; - isDeclareVariable(opts?: object): boolean; - isExistentialTypeParam(opts?: object): boolean; - isFunctionTypeAnnotation(opts?: object): boolean; - isFunctionTypeParam(opts?: object): boolean; - isGenericTypeAnnotation(opts?: object): boolean; - isInterfaceExtends(opts?: object): boolean; - isInterfaceDeclaration(opts?: object): boolean; - isIntersectionTypeAnnotation(opts?: object): boolean; - isMixedTypeAnnotation(opts?: object): boolean; - isNullableTypeAnnotation(opts?: object): boolean; - isNumericLiteralTypeAnnotation(opts?: object): boolean; - isNumberTypeAnnotation(opts?: object): boolean; - isStringLiteralTypeAnnotation(opts?: object): boolean; - isStringTypeAnnotation(opts?: object): boolean; - isThisTypeAnnotation(opts?: object): boolean; - isTupleTypeAnnotation(opts?: object): boolean; - isTypeofTypeAnnotation(opts?: object): boolean; - isTypeAlias(opts?: object): boolean; - isTypeAnnotation(opts?: object): boolean; - isTypeCastExpression(opts?: object): boolean; - isTypeParameterDeclaration(opts?: object): boolean; - isTypeParameterInstantiation(opts?: object): boolean; - isObjectTypeAnnotation(opts?: object): boolean; - isObjectTypeCallProperty(opts?: object): boolean; - isObjectTypeIndexer(opts?: object): boolean; - isObjectTypeProperty(opts?: object): boolean; - isQualifiedTypeIdentifier(opts?: object): boolean; - isUnionTypeAnnotation(opts?: object): boolean; - isVoidTypeAnnotation(opts?: object): boolean; - isJSXAttribute(opts?: object): boolean; - isJSXClosingElement(opts?: object): boolean; - isJSXElement(opts?: object): boolean; - isJSXEmptyExpression(opts?: object): boolean; - isJSXExpressionContainer(opts?: object): boolean; - isJSXIdentifier(opts?: object): boolean; - isJSXMemberExpression(opts?: object): boolean; - isJSXNamespacedName(opts?: object): boolean; - isJSXOpeningElement(opts?: object): boolean; - isJSXSpreadAttribute(opts?: object): boolean; - isJSXText(opts?: object): boolean; - isNoop(opts?: object): boolean; - isParenthesizedExpression(opts?: object): boolean; - isAwaitExpression(opts?: object): boolean; - isBindExpression(opts?: object): boolean; - isDecorator(opts?: object): boolean; - isDoExpression(opts?: object): boolean; - isExportDefaultSpecifier(opts?: object): boolean; - isExportNamespaceSpecifier(opts?: object): boolean; - isRestProperty(opts?: object): boolean; - isSpreadProperty(opts?: object): boolean; - isExpression(opts?: object): boolean; - isBinary(opts?: object): boolean; - isScopable(opts?: object): boolean; - isBlockParent(opts?: object): boolean; - isBlock(opts?: object): boolean; - isStatement(opts?: object): boolean; - isTerminatorless(opts?: object): boolean; - isCompletionStatement(opts?: object): boolean; - isConditional(opts?: object): boolean; - isLoop(opts?: object): boolean; - isWhile(opts?: object): boolean; - isExpressionWrapper(opts?: object): boolean; - isFor(opts?: object): boolean; - isForXStatement(opts?: object): boolean; - isFunction(opts?: object): boolean; - isFunctionParent(opts?: object): boolean; - isPureish(opts?: object): boolean; - isDeclaration(opts?: object): boolean; - isLVal(opts?: object): boolean; - isLiteral(opts?: object): boolean; - isImmutable(opts?: object): boolean; - isUserWhitespacable(opts?: object): boolean; - isMethod(opts?: object): boolean; - isObjectMember(opts?: object): boolean; - isProperty(opts?: object): boolean; - isUnaryLike(opts?: object): boolean; - isPattern(opts?: object): boolean; - isClass(opts?: object): boolean; - isModuleDeclaration(opts?: object): boolean; - isExportDeclaration(opts?: object): boolean; - isModuleSpecifier(opts?: object): boolean; - isFlow(opts?: object): boolean; - isFlowBaseAnnotation(opts?: object): boolean; - isFlowDeclaration(opts?: object): boolean; - isJSX(opts?: object): boolean; - isNumberLiteral(opts?: object): boolean; - isRegexLiteral(opts?: object): boolean; - isReferencedIdentifier(opts?: object): boolean; - isReferencedMemberExpression(opts?: object): boolean; - isBindingIdentifier(opts?: object): boolean; - isScope(opts?: object): boolean; + isArrayExpression(opts?: object): this is NodePath ; + isAssignmentExpression(opts?: object): this is NodePath; + isBinaryExpression(opts?: object): this is NodePath; + isDirective(opts?: object): this is NodePath; + isDirectiveLiteral(opts?: object): this is NodePath; + isBlockStatement(opts?: object): this is NodePath; + isBreakStatement(opts?: object): this is NodePath; + isCallExpression(opts?: object): this is NodePath; + isCatchClause(opts?: object): this is NodePath; + isConditionalExpression(opts?: object): this is NodePath; + isContinueStatement(opts?: object): this is NodePath; + isDebuggerStatement(opts?: object): this is NodePath; + isDoWhileStatement(opts?: object): this is NodePath; + isEmptyStatement(opts?: object): this is NodePath; + isExpressionStatement(opts?: object): this is NodePath; + isFile(opts?: object): this is NodePath; + isForInStatement(opts?: object): this is NodePath; + isForStatement(opts?: object): this is NodePath; + isFunctionDeclaration(opts?: object): this is NodePath; + isFunctionExpression(opts?: object): this is NodePath; + isIdentifier(opts?: object): this is NodePath; + isIfStatement(opts?: object): this is NodePath; + isLabeledStatement(opts?: object): this is NodePath; + isStringLiteral(opts?: object): this is NodePath; + isNumericLiteral(opts?: object): this is NodePath; + isNullLiteral(opts?: object): this is NodePath; + isBooleanLiteral(opts?: object): this is NodePath; + isRegExpLiteral(opts?: object): this is NodePath; + isLogicalExpression(opts?: object): this is NodePath; + isMemberExpression(opts?: object): this is NodePath; + isNewExpression(opts?: object): this is NodePath; + isProgram(opts?: object): this is NodePath; + isObjectExpression(opts?: object): this is NodePath; + isObjectMethod(opts?: object): this is NodePath; + isObjectProperty(opts?: object): this is NodePath; + isRestElement(opts?: object): this is NodePath; + isReturnStatement(opts?: object): this is NodePath; + isSequenceExpression(opts?: object): this is NodePath; + isSwitchCase(opts?: object): this is NodePath; + isSwitchStatement(opts?: object): this is NodePath; + isThisExpression(opts?: object): this is NodePath; + isThrowStatement(opts?: object): this is NodePath; + isTryStatement(opts?: object): this is NodePath; + isUnaryExpression(opts?: object): this is NodePath; + isUpdateExpression(opts?: object): this is NodePath; + isVariableDeclaration(opts?: object): this is NodePath; + isVariableDeclarator(opts?: object): this is NodePath; + isWhileStatement(opts?: object): this is NodePath; + isWithStatement(opts?: object): this is NodePath; + isAssignmentPattern(opts?: object): this is NodePath; + isArrayPattern(opts?: object): this is NodePath; + isArrowFunctionExpression(opts?: object): this is NodePath; + isClassBody(opts?: object): this is NodePath; + isClassDeclaration(opts?: object): this is NodePath; + isClassExpression(opts?: object): this is NodePath; + isExportAllDeclaration(opts?: object): this is NodePath; + isExportDefaultDeclaration(opts?: object): this is NodePath; + isExportNamedDeclaration(opts?: object): this is NodePath; + isExportSpecifier(opts?: object): this is NodePath; + isForOfStatement(opts?: object): this is NodePath; + isImportDeclaration(opts?: object): this is NodePath; + isImportDefaultSpecifier(opts?: object): this is NodePath; + isImportNamespaceSpecifier(opts?: object): this is NodePath; + isImportSpecifier(opts?: object): this is NodePath; + isMetaProperty(opts?: object): this is NodePath; + isClassMethod(opts?: object): this is NodePath; + isObjectPattern(opts?: object): this is NodePath; + isSpreadElement(opts?: object): this is NodePath; + isSuper(opts?: object): this is NodePath; + isTaggedTemplateExpression(opts?: object): this is NodePath; + isTemplateElement(opts?: object): this is NodePath; + isTemplateLiteral(opts?: object): this is NodePath; + isYieldExpression(opts?: object): this is NodePath; + isAnyTypeAnnotation(opts?: object): this is NodePath; + isArrayTypeAnnotation(opts?: object): this is NodePath; + isBooleanTypeAnnotation(opts?: object): this is NodePath; + isBooleanLiteralTypeAnnotation(opts?: object): this is NodePath; + isNullLiteralTypeAnnotation(opts?: object): this is NodePath; + isClassImplements(opts?: object): this is NodePath; + isClassProperty(opts?: object): this is NodePath; + isDeclareClass(opts?: object): this is NodePath; + isDeclareFunction(opts?: object): this is NodePath; + isDeclareInterface(opts?: object): this is NodePath; + isDeclareModule(opts?: object): this is NodePath; + isDeclareTypeAlias(opts?: object): this is NodePath; + isDeclareVariable(opts?: object): this is NodePath; + isExistentialTypeParam(opts?: object): this is NodePath; + isFunctionTypeAnnotation(opts?: object): this is NodePath; + isFunctionTypeParam(opts?: object): this is NodePath; + isGenericTypeAnnotation(opts?: object): this is NodePath; + isInterfaceExtends(opts?: object): this is NodePath; + isInterfaceDeclaration(opts?: object): this is NodePath; + isIntersectionTypeAnnotation(opts?: object): this is NodePath; + isMixedTypeAnnotation(opts?: object): this is NodePath; + isNullableTypeAnnotation(opts?: object): this is NodePath; + isNumericLiteralTypeAnnotation(opts?: object): this is NodePath; + isNumberTypeAnnotation(opts?: object): this is NodePath; + isStringLiteralTypeAnnotation(opts?: object): this is NodePath; + isStringTypeAnnotation(opts?: object): this is NodePath; + isThisTypeAnnotation(opts?: object): this is NodePath; + isTupleTypeAnnotation(opts?: object): this is NodePath; + isTypeofTypeAnnotation(opts?: object): this is NodePath; + isTypeAlias(opts?: object): this is NodePath; + isTypeAnnotation(opts?: object): this is NodePath; + isTypeCastExpression(opts?: object): this is NodePath; + isTypeParameterDeclaration(opts?: object): this is NodePath; + isTypeParameterInstantiation(opts?: object): this is NodePath; + isObjectTypeAnnotation(opts?: object): this is NodePath; + isObjectTypeCallProperty(opts?: object): this is NodePath; + isObjectTypeIndexer(opts?: object): this is NodePath; + isObjectTypeProperty(opts?: object): this is NodePath; + isQualifiedTypeIdentifier(opts?: object): this is NodePath; + isUnionTypeAnnotation(opts?: object): this is NodePath; + isVoidTypeAnnotation(opts?: object): this is NodePath; + isJSXAttribute(opts?: object): this is NodePath; + isJSXClosingElement(opts?: object): this is NodePath; + isJSXElement(opts?: object): this is NodePath; + isJSXEmptyExpression(opts?: object): this is NodePath; + isJSXExpressionContainer(opts?: object): this is NodePath; + isJSXIdentifier(opts?: object): this is NodePath; + isJSXMemberExpression(opts?: object): this is NodePath; + isJSXNamespacedName(opts?: object): this is NodePath; + isJSXOpeningElement(opts?: object): this is NodePath; + isJSXSpreadAttribute(opts?: object): this is NodePath; + isJSXText(opts?: object): this is NodePath; + isNoop(opts?: object): this is NodePath; + isParenthesizedExpression(opts?: object): this is NodePath; + isAwaitExpression(opts?: object): this is NodePath; + isBindExpression(opts?: object): this is NodePath; + isDecorator(opts?: object): this is NodePath; + isDoExpression(opts?: object): this is NodePath; + isExportDefaultSpecifier(opts?: object): this is NodePath; + isExportNamespaceSpecifier(opts?: object): this is NodePath; + isRestProperty(opts?: object): this is NodePath; + isSpreadProperty(opts?: object): this is NodePath; + isExpression(opts?: object): this is NodePath; + isBinary(opts?: object): this is NodePath; + isScopable(opts?: object): this is NodePath; + isBlockParent(opts?: object): this is NodePath; + isBlock(opts?: object): this is NodePath; + isStatement(opts?: object): this is NodePath; + isTerminatorless(opts?: object): this is NodePath; + isCompletionStatement(opts?: object): this is NodePath; + isConditional(opts?: object): this is NodePath; + isLoop(opts?: object): this is NodePath; + isWhile(opts?: object): this is NodePath; + isExpressionWrapper(opts?: object): this is NodePath; + isFor(opts?: object): this is NodePath; + isForXStatement(opts?: object): this is NodePath; + isFunction(opts?: object): this is NodePath; + isFunctionParent(opts?: object): this is NodePath; + isPureish(opts?: object): this is NodePath; + isDeclaration(opts?: object): this is NodePath; + isLVal(opts?: object): this is NodePath; + isLiteral(opts?: object): this is NodePath; + isImmutable(opts?: object): this is NodePath; + isUserWhitespacable(opts?: object): this is NodePath; + isMethod(opts?: object): this is NodePath; + isObjectMember(opts?: object): this is NodePath; + isProperty(opts?: object): this is NodePath; + isUnaryLike(opts?: object): this is NodePath; + isPattern(opts?: object): this is NodePath; + isClass(opts?: object): this is NodePath; + isModuleDeclaration(opts?: object): this is NodePath; + isExportDeclaration(opts?: object): this is NodePath; + isModuleSpecifier(opts?: object): this is NodePath; + isFlow(opts?: object): this is NodePath; + isFlowBaseAnnotation(opts?: object): this is NodePath; + isFlowDeclaration(opts?: object): this is NodePath; + isJSX(opts?: object): this is NodePath; + isNumberLiteral(opts?: object): this is NodePath; + isRegexLiteral(opts?: object): this is NodePath; + isReferencedIdentifier(opts?: object): this is NodePath; + isReferencedMemberExpression(opts?: object): this is NodePath; + isBindingIdentifier(opts?: object): this is NodePath; + isScope(opts?: object): this is NodePath; isReferenced(opts?: object): boolean; - isBlockScoped(opts?: object): boolean; - isVar(opts?: object): boolean; + isBlockScoped(opts?: object): this is NodePath; + isVar(opts?: object): this is NodePath; isUser(opts?: object): boolean; isGenerated(opts?: object): boolean; isPure(opts?: object): boolean; diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 1879c81e85..a49909ed4a 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1265,13 +1265,13 @@ export function isJSX(node: object, opts?: object): node is JSX; export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: object, opts?: object): boolean; -export function isReferencedMemberExpression(node: object, opts?: object): boolean; -export function isBindingIdentifier(node: object, opts?: object): boolean; -export function isScope(node: object, opts?: object): boolean; +export function isReferencedIdentifier(node: object, opts?: object): node is Identifier | JSXIdentifier; +export function isReferencedMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isBindingIdentifier(node: object, opts?: object): node is Identifier; +export function isScope(node: object, opts?: object): node is Scopable; export function isReferenced(node: object, opts?: object): boolean; -export function isBlockScoped(node: object, opts?: object): boolean; -export function isVar(node: object, opts?: object): boolean; +export function isBlockScoped(node: object, opts?: object): node is FunctionDeclaration | ClassDeclaration | VariableDeclaration; +export function isVar(node: object, opts?: object): node is VariableDeclaration; export function isUser(node: object, opts?: object): boolean; export function isGenerated(node: object, opts?: object): boolean; export function isPure(node: object, opts?: object): boolean; diff --git a/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts b/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts new file mode 100644 index 0000000000..89b8efc6e6 --- /dev/null +++ b/types/babel-webpack-plugin/babel-webpack-plugin-tests.ts @@ -0,0 +1,10 @@ +import BabelWebpackPlugin = require('babel-webpack-plugin'); + +new BabelWebpackPlugin(); +new BabelWebpackPlugin({}); +new BabelWebpackPlugin({ + test: /\.js$/, + presets: ['es2015'], + sourceMaps: false, + compact: false +}); diff --git a/types/babel-webpack-plugin/index.d.ts b/types/babel-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..3f16d154ac --- /dev/null +++ b/types/babel-webpack-plugin/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for babel-webpack-plugin 0.1 +// Project: https://github.com/simlrh/babel-webpack-plugin +// Definitions by: Jed Fox +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; +import { TransformOptions } from 'babel-core'; + +export = BabelWebpackPlugin; + +declare class BabelWebpackPlugin extends Plugin { + constructor(options?: BabelWebpackPlugin.Options); +} + +declare namespace BabelWebpackPlugin { + type Matcher = RegExp | string | Array; + interface Options extends TransformOptions { + test?: Matcher; + include?: Matcher; + exclude?: Matcher; + } +} diff --git a/types/babel-webpack-plugin/tsconfig.json b/types/babel-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..3e73343283 --- /dev/null +++ b/types/babel-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "babel-webpack-plugin-tests.ts" + ] +} diff --git a/types/babel-webpack-plugin/tslint.json b/types/babel-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 7bf31f0a7b..7b6fad9b56 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -159,6 +159,9 @@ function test_collection() { var book1: Book = new Book({ title: "Title 1", author: "Mike" }); books.add(book1); + // Test adding sort option to add. + books.add(new Book(), { sort: true }); + // Objects can be added to collection by casting to model type. // Compiler will check if object properties are valid for the cast. // This gives better type checking than declaring an `any` overload. @@ -180,6 +183,8 @@ function test_collection() { var alphabetical = books.sortBy((book: Book): number => null); + var copy = books.clone(); + let one: Book; let models: Book[]; let bool: boolean; @@ -188,6 +193,7 @@ function test_collection() { let modelsDict: _.Dictionary; let num: number; + models = books.slice(); models = books.slice(1); models = books.slice(1, 3); @@ -403,6 +409,12 @@ namespace v1Changes { validate: false }); } + + function test_set() { + var collection = new EmployeeCollection(); + var model = new Employee(); + collection.set([model], { add: false, remove: true, merge: false }); + } } namespace Router { @@ -413,4 +425,10 @@ namespace v1Changes { router.navigate('/employees', true); } } + + namespace Sync { + // Test for Backbone.sync override. + Backbone.sync('create', new Employee()); + Backbone.sync('read', new EmployeeCollection()); + } } diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 6475ba1e4a..1a186d9924 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -16,6 +16,13 @@ declare namespace Backbone { interface AddOptions extends Silenceable { at?: number; merge?: boolean; + sort?: boolean; + } + + interface CollectionSetOptions extends Silenceable { + add?: boolean; + remove?: boolean; + merge?: boolean; } interface HistoryOptions extends Silenceable { @@ -235,6 +242,7 @@ declare namespace Backbone { **/ get(id: number|string|Model): TModel; has(key: number|string|Model): boolean; + clone(): this; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; @@ -242,7 +250,19 @@ declare namespace Backbone { remove(model: {}|TModel, options?: Silenceable): TModel; remove(models: ({}|TModel)[], options?: Silenceable): TModel[]; reset(models?: TModel[], options?: Silenceable): TModel[]; - set(models?: TModel[], options?: Silenceable): TModel[]; + + /** + * + * The set method performs a "smart" update of the collection with the passed list of models. + * If a model in the list isn't yet in the collection it will be added; if the model is already in the + * collection its attributes will be merged; and if the collection contains any models that aren't present + * in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as + * this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can + * disable it with options: {add: false}, {remove: false}, or {merge: false}. + * @param models + * @param options + */ + set(models?: TModel[], options?: CollectionSetOptions): TModel[]; shift(options?: Silenceable): TModel; sort(options?: Silenceable): Collection; unshift(model: TModel, options?: AddOptions): TModel; @@ -258,7 +278,7 @@ declare namespace Backbone { /** * Return a shallow copy of this collection's models, using the same options as native Array#slice. */ - slice(min: number, max?: number): TModel[]; + slice(min?: number, max?: number): TModel[]; // mixins from underscore @@ -440,7 +460,7 @@ declare namespace Backbone { } // SYNC - function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; + function sync(method: string, model: Model | Collection, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; var emulateJSON: boolean; diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index 75560d4e42..2755bec595 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -165,7 +165,12 @@ function CommonMethodsInEventStreamsAndProperties() { { // Calculator for grouped consecutive values until group is cancelled: - var events = [ + interface Event { + id:number; + type:string; + val?:number; + } + var events: Event[] = [ {id: 1, type: "add", val: 3}, {id: 2, type: "add", val: -1}, {id: 1, type: "add", val: 2}, @@ -177,16 +182,16 @@ function CommonMethodsInEventStreamsAndProperties() { {id: 1, type: "cancel"} ], keyF = (event:{id:number}) => event.id, - limitF = (groupedStream:Bacon.EventStream) => { + limitF = (groupedStream:Bacon.EventStream) => { var cancel = groupedStream.filter(x => x.type === "cancel").take(1), adds = groupedStream.filter(x => x.type === "add"); return adds.takeUntil(cancel).map(x => x.val); }; - Bacon.sequentially(2, events) + Bacon.sequentially(2, events) .groupBy(keyF, limitF) .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) - .onValue(sum => { + .onValue((sum: number) => { console.log(sum); // returns [-1, 2, 8] in an order }); } diff --git a/types/bash-glob/bash-glob-tests.ts b/types/bash-glob/bash-glob-tests.ts new file mode 100644 index 0000000000..cf63412653 --- /dev/null +++ b/types/bash-glob/bash-glob-tests.ts @@ -0,0 +1,21 @@ +import bashGlob = require('bash-glob'); + +bashGlob('pattern', (err, files) => {}); +bashGlob(['pattern'], (err, files) => {}); +bashGlob(['pattern'], {}, (err, files) => {}); +bashGlob(['pattern'], { cwd: 'cwd' }, (err, files) => { }); + +bashGlob.on('match', (match, cwd) => {}); +bashGlob.on('files', (files, cwd) => {}); +bashGlob.on('end', (files) => {}); + +bashGlob.each('pattern', (err, files) => {}); +bashGlob.each(['pattern'], (err, files) => {}); +bashGlob.each(['pattern'], {}, (err, files) => {}); +bashGlob.each(['pattern'], { cwd: 'cwd' }, (err, files) => {}); + +// $ExpectType string[] +bashGlob.sync('pattern'); +bashGlob.sync(['pattern']); +bashGlob.sync(['pattern'], {}); +bashGlob.sync(['pattern'], { cwd: 'cwd' }); diff --git a/types/bash-glob/index.d.ts b/types/bash-glob/index.d.ts new file mode 100644 index 0000000000..29582ea9bd --- /dev/null +++ b/types/bash-glob/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for bash-glob 2.0 +// Project: https://github.com/micromatch/bash-glob +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type Patterns = string | string[]; +type Callback = (err: Error, files: string[]) => void; + +declare function bashGlob(pattern: Patterns, callback: Callback): void; +declare function bashGlob(pattern: Patterns, options: bashGlob.Options, callback: Callback): void; + +declare namespace bashGlob { + interface Options { + cwd?: string; + dot?: boolean; + dotglob?: boolean; + extglob?: boolean; + failglob?: boolean; + globstar?: boolean; + nocase?: boolean; + nocaseglob?: boolean; + nullglob?: boolean; + } + + function on(event: 'match' | 'files', callback: (files: string, cwd: string) => void): void; + function on(event: 'end', callback: (files: string) => void): void; + + function each(patterns: Patterns, callback: Callback): void; + function each(patterns: Patterns, options: Options, callback: Callback): void; + + function promise(patterns: Patterns, options?: Options): Promise; + + function sync(patterns: Patterns, options?: Options): string[]; +} + +export = bashGlob; diff --git a/types/bash-glob/tsconfig.json b/types/bash-glob/tsconfig.json new file mode 100644 index 0000000000..6a45a2d74d --- /dev/null +++ b/types/bash-glob/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bash-glob-tests.ts" + ] +} diff --git a/types/bash-glob/tslint.json b/types/bash-glob/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bash-glob/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/beats/beats-tests.ts b/types/beats/beats-tests.ts new file mode 100644 index 0000000000..00659af2e5 --- /dev/null +++ b/types/beats/beats-tests.ts @@ -0,0 +1,11 @@ +import beats = require('beats'); + +const bins: beats.Bin[] = [ + { lo: 0, hi: 512, threshold: 0, decay: 0.005 }, + { lo: 512, hi: 1024, threshold: 0, decay: 0.005 }, +]; + +const detect = beats(bins, 1); + +const frequencies = new Uint8Array(1024); +const result = detect(frequencies); diff --git a/types/beats/index.d.ts b/types/beats/index.d.ts new file mode 100644 index 0000000000..e95f008c1f --- /dev/null +++ b/types/beats/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for beats 0.0 +// Project: https://github.com/hughsk/beats/ +// Definitions by: Uri Shaked +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beats; + +declare function beats(bins: ReadonlyArray, minSeparation?: number): (frequencies: Uint8Array | Float32Array | ReadonlyArray, dt?: number) => Float32Array; + +declare namespace beats { + interface Bin { + lo: number; + hi: number; + threshold: number; + decay: number; + } +} diff --git a/types/beats/tsconfig.json b/types/beats/tsconfig.json new file mode 100644 index 0000000000..89bd0b5995 --- /dev/null +++ b/types/beats/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "beats-tests.ts" + ] +} diff --git a/types/beats/tslint.json b/types/beats/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beats/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/benchmark/benchmark-tests.ts b/types/benchmark/benchmark-tests.ts index 8fbe2b1d92..cb02940b37 100644 --- a/types/benchmark/benchmark-tests.ts +++ b/types/benchmark/benchmark-tests.ts @@ -229,6 +229,27 @@ suite.add({ 'onComplete': onComplete }); +// unregister a listener for an event type +suite.off('cycle', listener) as Benchmark.Suite; + +// unregister a listener for multiple event types +suite.off('start cycle', listener) as Benchmark.Suite; + +// unregister all listeners for an event type +suite.off('cycle') as Benchmark.Suite; + +// unregister all listeners for multiple event types +suite.off('start cycle complete') as Benchmark.Suite; + +// unregister all listeners for all event types +suite.off() as Benchmark.Suite; + +// register a listener for an event type +suite.on('cycle', listener) as Benchmark.Suite; + +// register a listener for multiple event types +suite.on('start cycle', listener) as Benchmark.Suite; + // basic usage suite.run(); diff --git a/types/benchmark/index.d.ts b/types/benchmark/index.d.ts index 01bb379a48..d8c72aef68 100644 --- a/types/benchmark/index.d.ts +++ b/types/benchmark/index.d.ts @@ -170,10 +170,10 @@ declare namespace Benchmark { join(separator?: string): string; listeners(type: string): Function[]; map(callback: Function): any[]; - off(type?: string, callback?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, callback?: Function): Benchmark; - on(types: string[]): Benchmark; + off(type?: string, callback?: Function): Suite; + off(types: string[]): Suite; + on(type?: string, callback?: Function): Suite; + on(types: string[]): Suite; pluck(property: string): any[]; pop(): Function; push(benchmark: Benchmark): number; diff --git a/types/better-scroll/better-scroll-tests.ts b/types/better-scroll/better-scroll-tests.ts new file mode 100644 index 0000000000..1c8f336f4f --- /dev/null +++ b/types/better-scroll/better-scroll-tests.ts @@ -0,0 +1,70 @@ +import BScroll = require("better-scroll"); + +const BScroll1 = new BScroll('#wrapper'); +const BScroll2 = new BScroll('#wrapper', { scrollX: false, scrollY: false }); +const BScroll3 = new BScroll('#wrapper', { + snap: true, + wheel: false, + scrollbar: false, + pullDownRefresh: false, +}); +const BScroll4 = new BScroll('#wrapper', { + wheel: { + selectedIndex: 0, + }, +}); +if (document.querySelector('div-test')) { + const BScroll6 = new BScroll('#wrapper', { + snap: { + loop: false, + el: document.querySelector('div-test')!, + threshold: 0.1, + stepX: 100, + stepY: 100, + listenFlick: true, + }, + }); +} +const BScroll7 = new BScroll('#wrapper', { + scrollbar: { + fade: true, + }, +}); + +const BScroll8 = new BScroll('#wrapper', { + pullDownRefresh: { + threshold: 50, + stop: 20, + }, +}); + +BScroll1.refresh(); +BScroll1.scrollTo(0, 100); +BScroll1.scrollTo(0, 100, 200); + +BScroll1.scrollToElement('selectedElement'); +BScroll1.scrollToElement('selectedElement', 250); + +BScroll1.scrollToElement(document.getElementById('selectedElement')!); +BScroll1.scrollToElement(document.getElementById('selectedElement')!, 250); + +BScroll2.on('scrollStart', () => { console.log('scroll started'); }); + +const BScroll9 = new BScroll(document.getElementById('wrapper')!); +const BScroll10 = new BScroll(document.getElementById('wrapper')!, { freeScroll: true }); +const BScroll11 = new BScroll(document.getElementById('wrapper')!, { + preventDefaultException: { + tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/, + }, +}); +const BScroll12 = new BScroll(document.getElementById('wrapper')!, { + preventDefaultException: { + className: /(^|\s)test(\s|$)/, + }, +}); + +const BScroll13 = new BScroll(document.getElementById('wrapper')!, { + swipeBounceTime: 1000, +}); + +const BScroll14 = new BScroll('#wrapper', { disableMouse: true, disableTouch: false }); diff --git a/types/better-scroll/index.d.ts b/types/better-scroll/index.d.ts new file mode 100644 index 0000000000..559b21bba2 --- /dev/null +++ b/types/better-scroll/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for better-scroll.js 1.3 +// Project: https://github.com/ustbhuangyi/better-scroll +// Definitions by: linxiaowu66 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface WheelOption { + selectedIndex?: number; + rotate?: number; + adjustTime?: number; +} + +interface SlideOption { + loop?: boolean; + el?: Element; + threshold?: number; + stepX?: number; + stepY?: number; + listenFlick?: boolean; +} +interface ScrollBarOption { + fade?: boolean; +} +interface PullDownOption { + threshold?: number; + stop?: number; +} +interface PullUpOption { + threshold?: number; +} +interface BsOption { + startX?: number; + startY?: number; + scrollX?: boolean; + scrollY?: boolean; + freeScroll?: boolean; + directionLockThreshold?: number; + eventPassthrough?: string | boolean; + click?: boolean; + tap?: boolean; + bounce?: boolean; + bounceTime?: number; + momentum?: boolean; + momentumLimitTime?: number; + momentumLimitDistance?: number; + swipeTime?: number; + swipeBounceTime?: number; + deceleration?: number; + flickLimitTime?: number; + flickLimitDistance?: number; + resizePolling?: number; + probeType?: number; + preventDefault?: boolean; + preventDefaultException?: object; + HWCompositing?: boolean; + useTransition?: boolean; + useTransform?: boolean; + bindToWrapper?: boolean; + disableMouse?: boolean; + disableTouch?: boolean; + /** + * for picker + * wheel: { + * selectedIndex: 0; + * rotate: 25; + * adjustTime: 400 + * } + */ + wheel?: WheelOption | boolean; + /** + * for slide + * snap: { + * loop?: boolean; + * el: domEl; + * threshold: 0.1; + * stepX: 100; + * stepY: 100; + * listenFlick: true + * } + */ + snap?: SlideOption | boolean; + /** + * for scrollbar + * scrollbar: { + * fade: true + * } + */ + scrollbar?: ScrollBarOption | boolean; + /** + * for pull down and refresh + * pullDownRefresh: { + * threshold: 50; + * stop: 20 + * } + */ + pullDownRefresh?: PullDownOption | boolean; + /** + * for pull up and load + * pullUpLoad: { + * threshold: 50 + * } + */ + pullUpLoad?: PullUpOption | boolean; +} +declare class BScroll { + constructor(element: Element | string, options?: BsOption); + // 重新计算 better-scroll,当 DOM 结构发生变化的时候务必要调用确保滚动的效果正常 + x: number; + y: number; + + refresh(): void; + // 启用 better-scroll; 默认 开启 + enable(): void; + // 禁用 better-scroll,DOM 事件(如 touchstart、touchmove、touchend)的回调函数不再响应 + disable(): void; + // 相对于当前位置偏移滚动 x;y 的距离 + scrollBy(x: number, y: number, time?: number, easing?: object): void; + // 滚动到指定的位置 + scrollTo(x: number, y: number, time?: number, easing?: object): void; + // 滚动到指定的目标元素 + scrollToElement(el: HTMLElement | string, time?: number, offsetX?: number | boolean, offsetY?: number | boolean, easing?: object): void; + // 立即停止当前运行的滚动动画 + stop(): void; + // 销毁 better-scroll,解绑事件 + destroy(): void; + + // 当我们做 slide 组件的时候,slide 通常会分成多个页面。调用此方法可以滚动到指定的页面。 + goToPage(x: number, y: number, time?: number, easing?: object): void; + // 滚动到下一个页面 + next(time: number, easing: object): void; + // 滚动到上一个页面 + prev(time: number, easing: object): void; + // 获取当前页面的信息 + getCurrentPage(): void; + // 当我们做 picker 组件的时候,调用该方法可以滚动到索引对应的位置 + wheelTo(index: number): void; + // 获取当前选中的索引值 + getSelectedIndex(): void; + // 当下拉刷新数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 + finishPullDown(): void; + // 当上拉加载数据加载完毕后,需要调用此方法告诉 better-scroll 数据已加载 + finishPullUp(): void; + + // 监听事件 + on(type: string, fn: (evt?: any) => void): void; + off(type: string, fn?: (evt?: any) => void): void; +} + +export = BScroll; diff --git a/types/better-scroll/tsconfig.json b/types/better-scroll/tsconfig.json new file mode 100644 index 0000000000..774ffc076f --- /dev/null +++ b/types/better-scroll/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "better-scroll-tests.ts" + ] +} \ No newline at end of file diff --git a/types/better-scroll/tslint.json b/types/better-scroll/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/better-scroll/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bezier-js/index.d.ts b/types/bezier-js/index.d.ts index 7706a46472..b44b027dc2 100644 --- a/types/bezier-js/index.d.ts +++ b/types/bezier-js/index.d.ts @@ -203,5 +203,5 @@ declare namespace BezierJs { } declare module "bezier-js" { - export = BezierJs; + export = BezierJs.Bezier; } diff --git a/types/binary-parser/binary-parser-tests.ts b/types/binary-parser/binary-parser-tests.ts new file mode 100644 index 0000000000..d0d09e5ef7 --- /dev/null +++ b/types/binary-parser/binary-parser-tests.ts @@ -0,0 +1,95 @@ +import { Parser } from "binary-parser"; + +// Build an IP packet header Parser +const ipHeader = new Parser() + .endianess('big') + .bit4('version') + .bit4('headerLength') + .uint8('tos') + .uint16('packetLength') + .uint16('id') + .bit3('offset') + .bit13('fragOffset') + .uint8('ttl') + .uint8('protocol') + .uint16('checksum') + .array('src', { + type: 'uint8', + length: 4 + }) + .array('dst', { + type: 'uint8', + length: 4 + }); + +// Prepare buffer to parse. +const buf = new Buffer('450002c5939900002c06ef98adc24f6c850186d1', 'hex'); + +// Parse buffer and show result +ipHeader.parse(buf); + +const parser2 = new Parser() + // Signed 32-bit integer (little endian) + .int32le('a') + // Unsigned 8-bit integer + .uint8('b') + // Signed 16-bit integer (big endian) + .int16be('c'); + +const parser3 = new Parser() + // 32-bit floating value (big endian) + .floatbe('a') + // 64-bit floating value (little endian) + .doublele('b'); + +const parser4 = new Parser() + // Statically sized array + .array('data', { + type: 'int32', + length: 8 + }) + + // Dynamically sized array (references another variable) + .uint8('dataLength') + .array('data2', { + type: 'int32', + length: 'dataLength' + }) + + // Dynamically sized array (with some calculation) + .array('data3', { + type: 'int32', + length: () => 4 // other fields are available through this + }) + + // Statically sized array + .array('data4', { + type: 'int32', + lengthInBytes: 16 + }) + + // Dynamically sized array (references another variable) + .uint8('dataLengthInBytes') + .array('data5', { + type: 'int32', + lengthInBytes: 'dataLengthInBytes' + }) + + // Dynamically sized array (with some calculation) + .array('data6', { + type: 'int32', + lengthInBytes: () => 4, // other fields are available through this + }) + + // Dynamically sized array (with stop-check on parsed item) + .array('data7', { + type: 'int32', + readUntil: (item, buffer) => true // stop when specific item is parsed. buffer can be used to perform a read-ahead. + }); + +const parser5 = new Parser() + .array('ipv4', { + type: 'uint8', + length: '4', + formatter: (arr) => { } + }); diff --git a/types/binary-parser/index.d.ts b/types/binary-parser/index.d.ts new file mode 100644 index 0000000000..657996bd8d --- /dev/null +++ b/types/binary-parser/index.d.ts @@ -0,0 +1,147 @@ +// Type definitions for binary-parser 1.3 +// Project: https://github.com/keichi/binary-parser +// Definitions by: Benjamin Riggs , Dolan Miu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface Parser { + parse(buffer: Buffer, callback?: (err?: Error, result?: any) => void): Parser.Parsed; + + create(constructorFunction: ObjectConstructor): Parser; + + int8(name: string, options?: Parser.Options): Parser; + uint8(name: string, options?: Parser.Options): Parser; + + int16(name: string, options?: Parser.Options): Parser; + uint16(name: string, options?: Parser.Options): Parser; + int16le(name: string, options?: Parser.Options): Parser; + int16be(name: string, options?: Parser.Options): Parser; + uint16le(name: string, options?: Parser.Options): Parser; + uint16be(name: string, options?: Parser.Options): Parser; + + int32(name: string, options?: Parser.Options): Parser; + uint32(name: string, options?: Parser.Options): Parser; + int32le(name: string, options?: Parser.Options): Parser; + int32be(name: string, options?: Parser.Options): Parser; + uint32le(name: string, options?: Parser.Options): Parser; + uint32be(name: string, options?: Parser.Options): Parser; + + bit1(name: string, options?: Parser.Options): Parser; + bit2(name: string, options?: Parser.Options): Parser; + bit3(name: string, options?: Parser.Options): Parser; + bit4(name: string, options?: Parser.Options): Parser; + bit5(name: string, options?: Parser.Options): Parser; + bit6(name: string, options?: Parser.Options): Parser; + bit7(name: string, options?: Parser.Options): Parser; + bit8(name: string, options?: Parser.Options): Parser; + bit9(name: string, options?: Parser.Options): Parser; + bit10(name: string, options?: Parser.Options): Parser; + bit11(name: string, options?: Parser.Options): Parser; + bit12(name: string, options?: Parser.Options): Parser; + bit13(name: string, options?: Parser.Options): Parser; + bit14(name: string, options?: Parser.Options): Parser; + bit15(name: string, options?: Parser.Options): Parser; + bit16(name: string, options?: Parser.Options): Parser; + bit17(name: string, options?: Parser.Options): Parser; + bit18(name: string, options?: Parser.Options): Parser; + bit19(name: string, options?: Parser.Options): Parser; + bit20(name: string, options?: Parser.Options): Parser; + bit21(name: string, options?: Parser.Options): Parser; + bit22(name: string, options?: Parser.Options): Parser; + bit23(name: string, options?: Parser.Options): Parser; + bit24(name: string, options?: Parser.Options): Parser; + bit25(name: string, options?: Parser.Options): Parser; + bit26(name: string, options?: Parser.Options): Parser; + bit27(name: string, options?: Parser.Options): Parser; + bit28(name: string, options?: Parser.Options): Parser; + bit29(name: string, options?: Parser.Options): Parser; + bit30(name: string, options?: Parser.Options): Parser; + bit31(name: string, options?: Parser.Options): Parser; + bit32(name: string, options?: Parser.Options): Parser; + + float(name: string, options?: Parser.Options): Parser; + floatle(name: string, options?: Parser.Options): Parser; + floatbe(name: string, options?: Parser.Options): Parser; + + double(name: string, options?: Parser.Options): Parser; + doublele(name: string, options?: Parser.Options): Parser; + doublebe(name: string, options?: Parser.Options): Parser; + + string(name: string, options?: Parser.StringOptions): Parser; + + buffer(name: string, options: Parser.BufferOptions): Parser; + + array(name: string, options: Parser.ArrayOptions): Parser; + + choice(name: string, options: Parser.ChoiceOptions): Parser; + + nest(name: string, options: Parser.NestOptions): Parser; + + skip(length: number): Parser; + + endianess(endianess: Parser.Endianness): Parser; /* [sic] */ + + namely(alias: string): Parser; + + compile(): void; + + getCode(): string; +} + +export interface ParserConstructor { + new(): Parser; +} + +export const Parser: ParserConstructor; + +export namespace Parser { + type Data = number | string | Array | Parsed | Buffer; + interface Parsed { + [name: string]: Data; + } + + interface Options { + formatter?: ((value: Data) => any); + assert?: string | number | ((value: Data) => boolean); + } + + interface StringOptions extends Options { + encoding?: string; + length?: number | string | ((this: Parsed) => number); + zeroTerminated?: boolean; + greedy?: boolean; + stripNull?: boolean; + } + + interface BufferOptions extends Options { + clone?: boolean; + length?: number | string | ((this: Parsed) => number); + readUntil?: string | ((item: number, buffer: Buffer) => boolean); + } + + interface ArrayOptions extends Options { + type: string | Parser; + length?: number | string | ((this: Parsed) => number); + lengthInBytes?: number | string | ((this: Parsed) => number); + readUntil?: string | ((item: number, buffer: Buffer) => boolean); + } + + interface ChoiceOptions extends Options { + tag: string | ((this: Parsed) => number); + choices: { [item: number]: Parser | string }; + defaultChoice?: Parser | string; + } + + interface NestOptions extends Options { + type: Parser | string; + } + + type Endianness = + 'little' | + 'big'; + + interface Context { + [name: string]: Parsed; + } +} diff --git a/types/binary-parser/tsconfig.json b/types/binary-parser/tsconfig.json new file mode 100644 index 0000000000..cb361f52c5 --- /dev/null +++ b/types/binary-parser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "binary-parser-tests.ts" + ] +} diff --git a/types/binary-parser/tslint.json b/types/binary-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/binary-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index ac78171dc8..1f5abfd2f3 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -10,12 +10,12 @@ /// import BigInteger = require("bigi"); -export interface Output { +export interface Out { script: Buffer; value: number; } -export interface Input { +export interface In { script: Buffer; hash: Buffer; index: number; @@ -152,8 +152,8 @@ export class HDNode { export class Transaction { version: number; locktime: number; - ins: Input[]; - outs: Output[]; + ins: In[]; + outs: Out[]; constructor(); addInput(hash: Buffer, index: number, sequence?: number, scriptSig?: Buffer): number; @@ -205,21 +205,25 @@ export class Transaction { static isCoinbaseHash(buffer: Buffer): boolean; } +export interface Input { + pubKeys: Buffer[]; + signatures: Buffer[]; + prevOutScript: Buffer; + prevOutType: string; + signType: string; + signScript: Buffer; + witness: boolean; +} + export class TransactionBuilder { tx: Transaction; - inputs: Array<{ pubKeys: Buffer[], - signatures: Buffer[], - prevOutScript: Buffer, - prevOutType: string, - signType: string, - signScript: Buffer, - witness: boolean} >; + inputs: Input[]; constructor(network?: Network, maximumFeeRate?: number); addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; - addOutput(scriptPubKey: Buffer, value: number): number; + addOutput(scriptPubKey: Buffer | string, value: number): number; build(): Transaction; @@ -537,7 +541,7 @@ export namespace script { output: { check(script: Buffer): boolean; decode(buffer: Buffer): Buffer; - encode(data: Buffer[]): Buffer; + encode(data: Buffer): Buffer; }; }; } diff --git a/types/blessed/blessed-tests.ts b/types/blessed/blessed-tests.ts index b143703b18..c5f857146f 100644 --- a/types/blessed/blessed-tests.ts +++ b/types/blessed/blessed-tests.ts @@ -1,150 +1,138 @@ -import * as blessed from 'blessed' +import * as blessed from "blessed"; +import { readFileSync } from "fs"; let screen: blessed.Widgets.Screen = null; // https://github.com/chjj/blessed/blob/master/test/widget-autopad.js screen = blessed.screen({ - dump: __dirname + '/logs/autopad.log', + dump: __dirname + "/logs/autopad.log", smartCSR: true, autoPadding: true, warnings: true }); -var box1 = blessed.box({ +const box1 = blessed.box({ parent: screen, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line' + border: "line" }); -var box2 = blessed.box({ +const box2 = blessed.box({ parent: box1, top: 0, left: 0, width: 10, height: 5, - border: 'line' + border: "line" }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js screen = blessed.screen({ - dump: __dirname + '/logs/bigtext.log', + dump: __dirname + "/logs/bigtext.log", smartCSR: true, warnings: true }); -var box = blessed.bigtext({ +const box3 = blessed.bigtext({ parent: screen, - content: 'Hello', + content: "Hello", shrink: true, - width: '80%', + width: "80%", // height: '80%', - height: 'shrink', + height: "shrink", // width: 'shrink', - border: 'line', - fch: ' ', - ch: '\u2592', + border: "line", + fch: " ", + ch: "\u2592", style: { - fg: 'red', - bg: 'blue', + fg: "red", + bg: "blue", bold: false } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-csr.js screen = blessed.screen({ - dump: __dirname + '/logs/csr.log', + dump: __dirname + "/logs/csr.log", smartCSR: true, warnings: true }); +const lorem = readFileSync(__dirname + "/git.diff", "utf8"); -var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); - -var cleanSides = screen.cleanSides; +const cleanSides = screen.cleanSides; function expectClean(value: any) { - screen.cleanSides = function(el: blessed.widget.Element) { - var ret = cleanSides.apply(this, arguments); + screen.cleanSides = function(el: blessed.Widgets.BlessedElement) { + const ret = cleanSides.apply(this, arguments); if (ret !== value) { - throw new Error('Failed. Expected ' - + value + ' from cleanSides. Got ' - + ret + '.'); + throw new Error(`Failed. Expected ${value} from cleanSides. Got ${ret}.`); } return ret; }; } -var btext = blessed.box({ +const btext = blessed.box({ parent: screen, - left: 'center', - top: 'center', - width: '80%', - height: '80%', + left: "center", + top: "center", + width: "80%", + height: "80%", style: { - bg: 'green' + bg: "green" }, - border: 'line', - content: 'CSR should still work.' + border: "line", + content: "CSR should still work." }); -let _oscroll = btext.scroll; -btext.scroll = function(offset, always) { +btext.scroll = (offset, always) => { expectClean(true); - return _oscroll(offset, always); }; -var text = blessed.scrollabletext({ +const text = blessed.scrollabletext({ parent: screen, content: lorem, - border: 'line', - left: 'center', - top: 'center', + border: "line", + left: "center", + top: "center", draggable: true, - width: '50%', - height: '50%', + width: "50%", + height: "50%", mouse: true, keys: true, vi: true }); -_oscroll = text.scroll; text.scroll = function(offset, always) { - var el = this; - var value = true; + const el = this; + let value = true; if (el.left < 0) value = true; if (el.top < 0) value = false; if (el.left + el.width > screen.width) value = true; if (el.top + el.height > screen.height) value = false; expectClean(value); - return _oscroll(offset, always); }; text.focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js screen = blessed.screen({ - dump: __dirname + '/logs/dock.log', + dump: __dirname + "/logs/dock.log", smartCSR: true, dockBorders: true, warnings: true @@ -154,85 +142,85 @@ blessed.box({ parent: screen, left: -1, top: -1, - width: '50%+1', - height: '50%+1', - border: 'line', - content: 'Foo' + width: "50%+1", + height: "50%+1", + border: "line", + content: "Foo" }); blessed.box({ parent: screen, - left: '50%-1', + left: "50%-1", top: -1, - width: '50%+3', - height: '50%+1', - content: 'Bar', - border: 'line' + width: "50%+3", + height: "50%+1", + content: "Bar", + border: "line" }); blessed.box({ parent: screen, left: -1, - top: '50%-1', - width: '50%+1', - height: '50%+3', - border: 'line', - content: 'Foo' + top: "50%-1", + width: "50%+1", + height: "50%+3", + border: "line", + content: "Foo" }); -blessed.listtable({ - parent: screen, - left: '50%-1', - top: '50%-1', - width: '50%+3', - height: '50%+3', - border: 'line', - align: 'center', - tags: true, - keys: true, - vi: true, - mouse: true, - style: { - header: { - fg: 'blue', - bold: true - }, - cell: { - fg: 'magenta', - selected: { - bg: 'blue' +blessed + .listtable({ + parent: screen, + left: "50%-1", + top: "50%-1", + width: "50%+3", + height: "50%+3", + border: "line", + align: "center", + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: "blue", + bold: true + }, + cell: { + fg: "magenta", + selected: { + bg: "blue" + } } - } - }, - data: [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] - ] -}).focus(); + }, + data: [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] + ] + }) + .focus(); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js -var form = blessed.form({ +const form = blessed.form({ parent: screen, keys: true, left: 0, top: 0, width: 30, height: 4, - bg: 'green', - content: 'Submit or cancel?' + bg: "green", + content: "Submit or cancel?" }); -var submit = blessed.button({ +const submit = blessed.button({ parent: form, mouse: true, keys: true, @@ -243,20 +231,20 @@ var submit = blessed.button({ left: 10, top: 2, shrink: true, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); -var cancel = blessed.button({ +const cancel = blessed.button({ parent: form, mouse: true, keys: true, @@ -267,15 +255,15 @@ var cancel = blessed.button({ left: 20, top: 2, shrink: true, - name: 'cancel', - content: 'cancel', + name: "cancel", + content: "cancel", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" }, hover: { - bg: 'red' + bg: "red" } } }); @@ -283,314 +271,306 @@ var cancel = blessed.button({ // https://github.com/chjj/blessed/blob/master/test/widget-layout.js screen = blessed.screen({ - dump: __dirname + '/logs/layout.log', + dump: __dirname + "/logs/layout.log", smartCSR: true, autoPadding: true, warnings: true }); -var layout = blessed.layout({ +const layout = blessed.layout({ parent: screen, - top: 'center', - left: 'center', - width: '50%', - height: '50%', - border: 'line', - layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + top: "center", + left: "center", + width: "50%", + height: "50%", + border: "line", + layout: process.argv[2] === "grid" ? "grid" : "inline", style: { - bg: 'red', + bg: "red", border: { - fg: 'blue' + fg: "blue" } } }); -var box1 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '1' + border: "line", + content: "1" }); -var box2 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '2' + border: "line", + content: "2" }); -var box3 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '3' + border: "line", + content: "3" }); -var box4 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '4' + border: "line", + content: "4" }); -var box5 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '5' + border: "line", + content: "5" }); -var box6 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '6' + border: "line", + content: "6" }); -var box7 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '7' + border: "line", + content: "7" }); -var box8 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '8' + border: "line", + content: "8" }); -var box9 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '9' + border: "line", + content: "9" }); -var box10 = blessed.box({ +blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '10' + border: "line", + content: "10" }); -var box11 = blessed.box({ +blessed.box({ parent: layout, top: 0, left: 0, width: 10, height: 5, - border: 'line', - content: '11' + border: "line", + content: "11" }); -var box12 = blessed.box({ +const box12 = blessed.box({ parent: layout, - top: 'center', - left: 'center', + top: "center", + left: "center", width: 20, height: 10, - border: 'line', - content: '12' + border: "line", + content: "12" }); -if (process.argv[2] !== 'grid') { - for (var i = 0; i < 10; i++) { +if (process.argv[2] !== "grid") { + for (let i = 0; i < 10; i++) { blessed.box({ parent: layout, // width: i % 2 === 0 ? 10 : 20, // height: i % 2 === 0 ? 5 : 10, width: Math.random() > 0.5 ? 10 : 20, height: Math.random() > 0.5 ? 5 : 10, - border: 'line', - content: (i + 1 + 12) + '' + border: "line", + content: String(i + 1 + 12) }); } } -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-form.js screen = blessed.screen({ - dump: __dirname + '/logs/form.log', + dump: __dirname + "/logs/form.log", warnings: true }); -type FormData = { - radio1: boolean; - radio2: boolean; - text: string; - check: boolean; -}; +interface FormData { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +} -var form2 = blessed.form({ +const form2 = blessed.form({ parent: screen, mouse: true, keys: true, vi: true, left: 0, top: 0, - width: '100%', - //height: 12, + width: "100%", style: { - bg: 'green', + bg: "green", border: { - inverse: true + inverse: true }, scrollbar: { inverse: true } }, - content: 'foobar', + content: "foobar", scrollable: true, scrollbar: { - ch: ' ' + ch: " " } - //alwaysScroll: true }); -form2.on('submit', (data) => { +form2.on("submit", data => { output.setContent(JSON.stringify(data, null, 2)); screen.render(); }); -form2.key('d', function() { +form2.key("d", () => { form2.scroll(1, true); screen.render(); }); -form2.key('u', function() { +form2.key("u", () => { form2.scroll(-1, true); screen.render(); }); -var set = blessed.radioset({ +const set = blessed.radioset({ parent: form2, left: 1, top: 1, shrink: true, - //padding: 1, - //content: 'f', style: { - bg: 'magenta' + bg: "magenta" } }); -var radio1 = blessed.radiobutton({ +const radio1 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 0, top: 0, - name: 'radio1', - content: 'radio1' + name: "radio1", + content: "radio1" }); -var radio2 = blessed.radiobutton({ +const radio2 = blessed.radiobutton({ parent: set, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 15, top: 0, - name: 'radio2', - content: 'radio2' + name: "radio2", + content: "radio2" }); -var text2 = blessed.textbox({ +const text2 = blessed.textbox({ parent: form2, mouse: true, keys: true, style: { - bg: 'blue' + bg: "blue" }, height: 1, width: 20, left: 1, top: 3, - name: 'text' + name: "text" }); -text2.on('focus', function() { - text2.readInput(); -}); +text2.on("focus", () => text2.readInput()); -var check = blessed.checkbox({ +const check = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 1, - name: 'check', - content: 'check' + name: "check", + content: "check" }); -var check2 = blessed.checkbox({ +const check2 = blessed.checkbox({ parent: form2, mouse: true, keys: true, shrink: true, style: { - bg: 'magenta' + bg: "magenta" }, height: 1, left: 28, top: 14, - name: 'foooooooo2', - content: 'foooooooo2' + name: "foooooooo2", + content: "foooooooo2" }); -var submit = blessed.button({ +const submit2 = blessed.button({ parent: form2, mouse: true, keys: true, @@ -601,69 +581,67 @@ var submit = blessed.button({ }, left: 29, top: 3, - name: 'submit', - content: 'submit', + name: "submit", + content: "submit", style: { - bg: 'blue', + bg: "blue", focus: { - bg: 'red' + bg: "red" } } }); -submit.on('press', function() { - form2.submit(); -}); +submit.on("press", () => form2.submit()); -var box1 = blessed.box({ +const box5 = blessed.box({ parent: form2, left: 1, top: 10, height: 10, width: 10, - content: 'one', + content: "one", style: { - bg: 'cyan' + bg: "cyan" } }); -var box2 = blessed.box({ - parent: box1, +const box6 = blessed.box({ + parent: box5, left: 1, top: 2, height: 8, width: 9, - content: 'two', + content: "two", style: { - bg: 'magenta' + bg: "magenta" } }); -var box3 = blessed.box({ - parent: box2, +const box7 = blessed.box({ + parent: box6, left: 1, top: 2, height: 6, width: 8, - content: 'three', + content: "three", style: { - bg: 'yellow' + bg: "yellow" } }); -var box4 = blessed.box({ - parent: box3, +blessed.box({ + parent: box7, left: 1, top: 2, height: 4, width: 7, - content: 'four', + content: "four", style: { - bg: 'blue' + bg: "blue" } }); -var output = blessed.scrollabletext({ +const output = blessed.scrollabletext({ parent: form2, mouse: true, keys: true, @@ -672,26 +650,24 @@ var output = blessed.scrollabletext({ height: 5, right: 0, style: { - bg: 'red' + bg: "red" }, - content: 'foobar' + content: "foobar" }); -var bottom = blessed.line({ +const bottom = blessed.line({ parent: form2, - type: 'line', - orientation: 'horizontal', + type: "line", + orientation: "horizontal", left: 0, right: 0, top: 50, style: { - fg: 'blue' + fg: "blue" } }); -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); form2.focus(); @@ -702,70 +678,68 @@ screen.render(); // https://github.com/chjj/blessed/blob/master/test/widget-table.js screen = blessed.screen({ - dump: __dirname + '/logs/table.log', + dump: __dirname + "/logs/table.log", autoPadding: false, fullUnicode: true, warnings: true }); -var DU = '杜'; -var JUAN = '鹃'; +const DU = "杜"; +const JUAN = "鹃"; -var table = blessed.table({ - //parent: screen, - top: 'center', - left: 'center', +const table = blessed.table({ + // parent: screen, + top: "center", + left: "center", data: null, - border: 'line', - align: 'center', + border: "line", + align: "center", tags: true, - //width: '80%', - width: 'shrink', + // width: '80%', + width: "shrink", style: { border: { - fg: 'red' + fg: "red" }, header: { - fg: 'blue', + fg: "blue", bold: true }, cell: { - fg: 'magenta' + fg: "magenta" } } }); -var data1 = [ - [ 'Animals', 'Foods', 'Times' ], - [ 'Elephant', 'Apple', '1:00am' ], - [ 'Bird', 'Orange', '2:15pm' ], - [ 'T-Rex', 'Taco', '8:45am' ], - [ 'Mouse', 'Cheese', '9:05am' ] +const data1 = [ + ["Animals", "Foods", "Times"], + ["Elephant", "Apple", "1:00am"], + ["Bird", "Orange", "2:15pm"], + ["T-Rex", "Taco", "8:45am"], + ["Mouse", "Cheese", "9:05am"] ]; -data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; -data1[2][0] += ' (' + DU + JUAN + ')'; +data1[1][0] = `{red-fg} ${data1[1][0]} {/red-fg}`; +data1[2][0] += ` (${DU}${JUAN})`; -var data2 = [ - [ 'Animals', 'Foods', 'Times', 'Numbers' ], - [ 'Elephant', 'Apple', '1:00am', 'One' ], - [ 'Bird', 'Orange', '2:15pm', 'Two' ], - [ 'T-Rex', 'Taco', '8:45am', 'Three' ], - [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +const data2 = [ + ["Animals", "Foods", "Times", "Numbers"], + ["Elephant", "Apple", "1:00am", "One"], + ["Bird", "Orange", "2:15pm", "Two"], + ["T-Rex", "Taco", "8:45am", "Three"], + ["Mouse", "Cheese", "9:05am", "Four"] ]; -data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; -data2[2][0] += ' (' + DU + JUAN + ')'; +data2[1][0] = `{red-fg} ${data2[1][0]} {/red-fg}`; +data2[2][0] += ` (${DU}${JUAN})`; -screen.key('q', function() { - return screen.destroy(); -}); +screen.key("q", () => screen.destroy()); table.setData(data2); screen.append(table); screen.render(); -setTimeout(function() { +setTimeout(() => { table.setData(data1); screen.render(); }, 3000); diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 553942af2f..9098648240 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -1,2837 +1,3033 @@ -// Type definitions for blessed 0.1.6 +// Type definitions for blessed 0.1 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: Bryn Austin Bellomy , Steve Kellock // Definitions: https://github.com/borisyankov/DefinitelyTyped +// TypeScript Version: 2.1 -/// +/// -import { EventEmitter } from 'events'; +import { EventEmitter } from "events"; import * as stream from "stream"; import * as child_process from "child_process"; -declare namespace Blessed { - export class BlessedProgram { - hideCursor: () => void; - move: any; - showCursor: any; - } +export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; +} - export module Widgets { +export namespace Widgets { + namespace Types { + type TTopLeft = string | number | "center"; - export module Types { + type TPosition = string | number; - export type TTopLeft = string | number | "center"; + type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - export type TPosition = string | number; - - export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; - - export type TStyle = { - type?: string; - bg?: string; - fg?: string; - ch?: string; - bold?: boolean; - underline?: boolean; - blink?: boolean; - inverse?: boolean; - invisible?: boolean; - transparent?: boolean; - border?: "line" | "bg" | TBorder; - hover?: boolean; - focus?: boolean; - label?: string; - track?: {bg?: string; fg?: string;}; - scrollbar?: {bg?: string; fg?: string;}; - } - - export type TBorder = { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export type TCursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: 'block'|'underline'|'line'; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - - export type TAlign = "left" | "center" | "right"; - - export type ListbarCommand = { - key: string; - callback: () => void; - }; - - export type TImage = { - /** - * Pixel width. - */ - width: number; - /** - * Pixel height. - */ - height: number; - /** - * Image bitmap. - * */ - bmp: any; - /** - * Image cellmap (bitmap scaled down to cell size). - */ - cellmap: any; - }; - - export type Cursor = { - /** - * Have blessed draw a custom cursor and hide the terminal cursor (experimental). - */ - artificial: boolean; - /** - * Shape of the cursor. Can be: block, underline, or line. - */ - shape: boolean; - /** - * Whether the cursor blinks. - */ - blink: boolean; - /** - * Color of the color. Accepts any valid color value (null is default). - */ - color: string; - } - } - - export module Events { - - export interface IMouseEventArg { - x: number; - y: number; - action: Types.TMouseAction; - } - - export interface IKeyEventArg { - full: string; - name: string; - shift: boolean; - ctrl: boolean; - meta: boolean; - sequence: string; - } - } - - export interface NodeChildProcessExecOptions { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface IOptions { - } - - export interface IHasOptions { - options: T; - } - - export interface TputsOptions extends IOptions { - terminal?: string; - extended?: boolean; - debug?: boolean; - termcap?: string; - terminfoFile?: string; - terminfoPrefix?: string; - termcapFile?: string; - } - - export class Tput implements IHasOptions { - constructor(opts: TputsOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: TputsOptions; - - debug: boolean; - padding: boolean; - extended: boolean; - printf: boolean; - termcap: string; - terminfoPrefix: string; - terminfoFile: string; - termcapFile: string; - error: Error; - terminal: string; - - setup(): void; - term(is: any): boolean; - readTerminfo(term: string): string; - parseTerminfo(data: any, file: string): { - header: { - dataSize: number; - headerSize: number; - magicNumber: boolean; - namesSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - extended: { - dataSize: number; - headerSize: number; - boolCount: number; - numCount: number; - strCount: number; - strTableSize: number; - lastStrTableOffset: number; - } - } - name: string; - names: string[]; - desc: string; - bools: Object; - numbers: Object; - strings: Object; - }; - } - - export interface IDestroyable { - destroy(): void; - } - - export interface INodeOptions extends IOptions { - name?: string; - screen?: Screen; - parent?: Node; - children?: Node[]; - focusable?: boolean; - } - - export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { - constructor(options: INodeOptions); - - // ** properties ** // - - focusable: boolean; - - /** - * Original options object. - */ - options: INodeOptions; - - /** - * An object for any miscellanous user data. - */ - data: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - _: {[index: string]: any;}; - /** - * An object for any miscellanous user data. - */ - $: {[index: string]: any;}; - /** - * Type of the node (e.g. box). - */ - type: string; - /** - * Render index (document order index) of the last render call. - */ - index: number; - /** - * Parent screen. - */ - screen: Screen; - /** - * Parent node. - */ - parent: Node; - /** - * Array of node's children. - */ - children: Node[]; - - // ** methods ** // - - /** - * Prepend a node to this node's children. - */ - prepend(node: Node): void; - /** - * Append a node to this node's children. - */ - append(node: Node): void; - /** - * Remove child node from node. - */ - remove(node: Node): void; - /** - * Insert a node to this node's children at index i. - */ - insert(node: Node, index: number): void; - /** - * Insert a node to this node's children before the reference node. - */ - insertBefore(node: Node, refNode: Node): void; - /** - * Insert a node from node after the reference node. - */ - insertAfter(node: Node, refNode: Node): void; - /** - * Remove node from its parent. - */ - detach(): void; - /** - * Remove node from its parent. - */ - free(): void; - /** - * Remove node from its parent. - */ - forDescendants(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - forAncestors(iter: Function, s: any): void; - /** - * Remove node from its parent. - */ - collectDescendants(s: any): void; - /** - * Remove node from its parent. - */ - collectAncestors(s: any): void; - /** - * Remove node from its parent. - */ - emitDescendants(): void; - /** - * Remove node from its parent. - */ - emitAncestors(): void; - /** - * Remove node from its parent. - */ - hasDescendant(target: Node): void; - /** - * Remove node from its parent. - */ - hasAncestor(target: Node): boolean; - /** - * Remove node from its parent. - */ - destroy(): void; - /** - * Emit event for element, and recursively emit same event for all descendants. - */ - emitDescendants(type: string, ...args: any[]): void; - /** - * Get user property with a potential default value. - */ - get(name: string, def: T): T; - /** - * Set user property to value. - */ - set(name: string, value: T): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when node is added to a parent. - */ - on(event: "adopt", callback: (arg: Node) => void): this; - /** - * Received when node is removed from it's current parent. - */ - on(event: "remove", callback: (arg: Node) => void): this; - /** - * Received when node gains a new parent. - */ - on(event: "reparent", callback: (arg: Node) => void): this; - /** - * Received when node is attached to the screen directly or somewhere in its ancestry. - */ - on(event: "attach", callback: (arg: Node) => void): this; - /** - * Received when node is detached from the screen directly or somewhere in its ancestry. - */ - on(event: "detach", callback: (arg: Node) => void): this; - } - - export class NodeWithEvents extends Node { - // ** methods ** // - - /** - * Bind a keypress listener for a specific key. - */ - key(name: string | string[], listener: Function): void; - /** - * Bind a keypress listener for a specific key once. - */ - onceKey(name: string, listener: Function): void; - /** - * Remove a keypress listener for a specific key. - */ - unkey(name: string, listener: Function): void; - removeKey(name: string, listener: Function): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received on screen resize. - */ - on(event: "resize", callback: () => void): this; - /** - * Received on mouse events. - */ - on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; - on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; - /** - * Received on key events. - */ - on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; - /** - * Global events received for all elements. - */ - on(event: "element click", callback: (arg: Screen) => void): this; - on(event: "element mouseover", callback: (arg: Screen) => void): this; - on(event: "element mouseout", callback: (arg: Screen) => void): this; - on(event: "element mouseup", callback: (arg: Screen) => void): this; - /** - * Received on key event for [name]. - */ - //on(event: "key", callback: (arg: BlessedScreen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "focus", callback: (arg: Screen) => void): this; - /** - * Received when the terminal window focuses/blurs. Requires a terminal supporting the - * focus protocol and focus needs to be passed to program.enableMouse(). - */ - on(event: "blur", callback: (arg: Screen) => void): this; - /** - * Received before render. - */ - on(event: "prerender", callback: () => void): this; - /** - * Received on render. - */ - on(event: "render", callback: () => void): this; - /** - * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). - */ - on(event: "warning", callback: (text: string) => void): this; - /** - * Received when the screen is destroyed (only useful when using multiple screens). - */ - on(event: "destroy", callback: () => void): this; - /** - * Received when the element is moved. - */ - on(event: "move", callback: () => void): this; - /** - * Element was clicked (slightly smarter than mouseup). - */ - on(event: "click", callback: (arg: Screen) => void): this; - /** - * Received when element is shown. - */ - on(event: "show", callback: () => void): this; - /** - * Received when element becomes hidden. - */ - on(event: "hide", callback: () => void): this; - - on(event: "set content", callback: () => void): this; - on(event: "parsed content", callback: () => void): this; - } - - export interface IScreenOptions extends INodeOptions { - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program?: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR?: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR?: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE?: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout?: number; - /** - * The width of tabs within an element's content. - */ - tabSize?: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding?: boolean; - - cursor?: Types.TCursor; - - /** - * Create a log file. See log method. - */ - log?: (...msg: any[]) => void; - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump?: string; - /** - * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when - * pressing F12. It will display all log and debug messages. - */ - debug?: (...msg: string[]) => void; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked?: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders?: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast?: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode?: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus?: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings?: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode?: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input?: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output?: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput?: Tput; - /** - * Top of the focus history stack. - */ - focused?: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width?: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height?: Types.TPosition; - /** - * Same as screen.width. - */ - cols?: number; - /** - * Same as screen.height. - */ - rows?: number; - /** - * Relative top offset, always zero. - */ - top?: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left?: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right?: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom?: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop?: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft?: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright?: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom?: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys?: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys?: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover?: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal?: string; - /** - * Set or get window title. - */ - title?: string; - } - - export class Screen extends NodeWithEvents implements IHasOptions { - constructor(opts: IScreenOptions); - - // ** properties ** // - cleanSides: any; - - /** - * Original options object. - */ - options: IScreenOptions; - - /** - * The blessed Program to be associated with. Will be automatically instantiated if none is provided. - */ - program: BlessedProgram; - /** - * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with - * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, - * however, it is more optimal for terminal rendering. - */ - smartCSR: boolean; - /** - * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, - * but may cause flickering depending on what is on each side of the element. - */ - fastCSR: boolean; - /** - * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work - * with terminals that don't support it, but only on lines with the default background color. As it - * stands with the current implementation, it's uncertain how much terminal performance this adds at - * the cost of overhead within node. - */ - useBCE: boolean; - /** - * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). - */ - resizeTimeout: number; - /** - * The width of tabs within an element's content. - */ - tabSize: number; - /** - * Automatically position child elements with border and padding in mind (NOTE: this is a recommended - * option. It may become default in the future). - */ - autoPadding: boolean; - - cursor: Types.TCursor; - - /** - * Dump all output and input to desired file. Can be used together with log option if set as a boolean. - */ - dump: string; - /** - * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful - * for creating a key that will always exit no matter whether the keys are locked. - */ - ignoreLocked: boolean; - /** - * Automatically "dock" borders with other elements instead of overlapping, depending on position - * (experimental). For example: These border-overlapped elements: - */ - dockBorders: boolean; - /** - * Normally, dockable borders will not dock if the colors or attributes are different. This option - * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. - */ - ignoreDockContrast: boolean; - /** - * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode - * combining characters. This allows you to display text above the basic multilingual plane. This - * is behind an option because it may affect performance slightly negatively. Without this option - * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', - * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply - * removes them from an element's content if iTerm2 is detected). - */ - fullUnicode: boolean; - /** - * Send focus events after mouse is enabled. - */ - sendFocus: boolean; - /** - * Display warnings (such as the output not being a TTY, similar to ncurses). - */ - warnings: boolean; - /** - * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. - * If value is true unicode is forced. If value is false non-unicode is forced (default: null). - */ - forceUnicode: boolean; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - input: stream.Writable; - /** - * Input and output streams. process.stdin/process.stdout by default, however, it could be a - * net.Socket if you want to make a program that runs over telnet or something of that nature. - * */ - output: stream.Readable; - /** - * The blessed Tput object (only available if you passed tput: true to the Program constructor.) - */ - tput: Tput; - /** - * Top of the focus history stack. - */ - focused: BlessedElement; - /** - * Width of the screen (same as program.cols). - */ - width: Types.TPosition; - /** - * Height of the screen (same as program.rows). - */ - height: Types.TPosition; - /** - * Same as screen.width. - */ - cols: number; - /** - * Same as screen.height. - */ - rows: number; - /** - * Relative top offset, always zero. - */ - top: Types.TTopLeft; - /** - * Relative left offset, always zero. - */ - left: Types.TTopLeft; - /** - * Relative right offset, always zero. - */ - right: Types.TPosition; - /** - * Relative bottom offset, always zero. - */ - bottom: Types.TPosition; - /** - * Absolute top offset, always zero. - */ - atop: Types.TTopLeft; - /** - * Absolute left offset, always zero. - */ - aleft: Types.TTopLeft; - /** - * Absolute right offset, always zero. - */ - aright: Types.TPosition; - /** - * Absolute bottom offset, always zero. - */ - abottom: Types.TPosition; - /** - * Whether the focused element grabs all keypresses. - */ - grabKeys: any; - /** - * Prevent keypresses from being received by any element. - */ - lockKeys: boolean; - /** - * The currently hovered element. Only set if mouse events are bound. - */ - hover: any; - /** - * Set or get terminal name. Set calls screen.setTerminal() internally. - */ - terminal: string; - /** - * Set or get window title. - */ - title: string; - - // ** methods ** // - - /** - * Write string to the log file if one was created. - */ - log(...msg: any[]): void; - /** - * Same as the log method, but only gets called if the debug option was set. - */ - debug(...msg: string[]): void; - /** - * Allocate a new pending screen buffer and a new output screen buffer. - */ - alloc(): void; - /** - * Reallocate the screen buffers and clear the screen. - */ - realloc(): void; - /** - * Draw the screen based on the contents of the screen buffer. - */ - draw(start: number, end: number): void; - /** - * Render all child elements, writing all data to the screen buffer and drawing the screen. - */ - render(): void; - /** - * Clear any region on the screen. - */ - clearRegion(x1: number, x2: number, y1: number, y2: number): void; - /** - * Fill any region with a character of a certain attribute. - */ - fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; - /** - * Focus element by offset of focusable elements. - */ - focusOffset(offset: number): any; - /** - * Focus previous element in the index. - */ - focusPrevious(): void; - /** - * Focus next element in the index. - */ - focusNext(): void; - /** - * Push element on the focus stack (equivalent to screen.focused = el). - */ - focusPush(element: BlessedElement): void; - /** - * Pop element off the focus stack. - */ - focusPop(): BlessedElement; - /** - * Save the focused element. - */ - saveFocus(): BlessedElement; - /** - * Restore the saved focused element. - */ - restoreFocus(): BlessedElement; - /** - * "Rewind" focus to the last visible and attached element. - */ - rewindFocus(): BlessedElement; - /** - * Spawn a process in the foreground, return to blessed app after exit. - */ - spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; - /** - * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. - */ - exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; - /** - * Read data from text editor. - */ - readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /** - * Set effects based on two events and attributes. - */ - setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; - /** - * Insert a line into the screen (using csr: this bypasses the output buffer). - */ - insertLine(n: number, y: number, top: number, bottom: number): void; - /** - * Delete a line from the screen (using csr: this bypasses the output buffer). - */ - deleteLine(n: number, y: number, top: number, bottom: number): void; - /** - * Insert a line at the bottom of the screen. - */ - insertBottom(top: number, bottom: number): void; - /** - * Insert a line at the top of the screen. - */ - insertTop(top: number, bottom: number): void; - /** - * Delete a line at the bottom of the screen. - */ - deleteBottom(top: number, bottom: number): void; - /** - * Delete a line at the top of the screen. - */ - deleteTop(top: number, bottom: number): void; - /** - * Enable mouse events for the screen and optionally an element (automatically called when a form of - * on('mouse') is bound). - */ - enableMouse(el: BlessedElement): void; - enableMouse(): void; - /** - * Enable keypress events for the screen and optionally an element (automatically called when a form of - * on('keypress') is bound). - */ - enableKeys(el: BlessedElement): void; - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(el: BlessedElement): void; - enableInput(): void; - /** - * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. - */ - copyToClipboard(text: string): void; - /** - * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution - * to this). Returns true if successful. - */ - cursorShape(shape: boolean, blink: boolean): any; - /** - * Attempt to change cursor color. Returns true if successful. - */ - cursorColor(color: string): void; - /** - * Attempt to reset cursor. Returns true if successful. - */ - cursorReset(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - /** - * Destroy the screen object and remove it from the global list. Also remove all global events relevant - * to the screen object. If all screen objects are destroyed, the node process is essentially reset - * to its initial state. - */ - destroy(): void; - /** - * Reset the terminal to term. Reloads terminfo. - */ - setTerminal(term: string): void; - } - - export interface Padding { - left?: number; - right?: number; - top?: number; - bottom?: number; - } - - export class PositionCoords { - xi: number; - xl: number; - yi: number; - yl: number; - } - - export interface Position { - left: number | string; - right: number | string; - top: number | string; - bottom: number | string; - } - - export interface Border { - /** - * Type of border (line or bg). bg by default. - */ - type?: "line" | "bg"; - /** - * Character to use if bg type, default is space. - */ - ch?: string; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg?: number; - fg?: number; - /** - * Border attributes. - */ - bold?: string; - underline?: string; - } - - export interface ElementOptions extends INodeOptions { - tags?: boolean; - - fg?: string; - bg?: string; - bold?: string; - underline?: string; - - style?: any; - /** - * Border object, see below. - */ - border?: Border | "line" | "bg"; - /** - * Element's text content. - */ - content?: string; - /** - * Element is clickable. - */ - clickable?: boolean; - /** - * Element is focusable and can receive key input. - */ - input?: boolean; - keyable?: boolean; - /** - * Element is focused. - */ - focused?: BlessedElement; - /** - * Whether the element is hidden. - */ - hidden?: boolean; - /** - * A simple text label for the element. - */ - label?: string; - /** - * A floating text label for the element which appears on mouseover. - */ - hoverText?: string; - /** - * Text alignment: left, center, or right. - */ - align?: "left" | "center" | "right"; - /** - * Vertical text alignment: top, middle, or bottom. - */ - valign?: "top" | "middle" | "bottom"; - /** - * Shrink/flex/grow to content and child elements. Width/height during render. - */ - shrink?: boolean; - /** - * Amount of padding on the inside of the element. Can be a number or an object containing - * the properties: left, right, top, and bottom. - */ - padding?: number | Padding; - - top?: Types.TTopLeft; - left?: Types.TTopLeft; - right?: Types.TPosition; - bottom?: Types.TPosition; - - /** - * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). - * Percentages can also have offsets (50%+1, 50%-1). - */ - width?: number | string; - /** - * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or - * keyword (center). right and bottom do not accept keywords. Percentages can also have - * offsets (50%+1, 50%-1). - */ - height?: number | string; - /** - * Can contain the above options. - */ - position?: Position; - /** - * Whether the element is scrollable or not. - */ - scrollable?: boolean; - /** - * Background character (default is whitespace ). - */ - ch?: string; - /** - * Allow the element to be dragged with the mouse. - */ - draggable?: boolean; - /** - * Draw a translucent offset shadow behind the element. - */ - shadow?: boolean; - } - - export interface Coords { - xl: number; - xi: number; - yl: number; - yi: number; - base: number; - _contentEnd: {x: number; y: number;}; - notop: Types.TTopLeft; - noleft: Types.TTopLeft; - noright: Types.TPosition; - nobot: Types.TPosition; - } - - export interface LabelOptions { - text: string; - side: Types.TAlign; - } - - // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. - export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { - constructor(opts: ElementOptions); - - // ** properties ** // - - /** - * Original options object. - */ - options: ElementOptions; - /** - * Name of the element. Useful for form submission. - */ - name: string; - /** - * Border object. - */ - border: Border; - - style: any; - position: Position; - content: string; - hidden: boolean; - visible: boolean; - detached: boolean; - /** - * Border foreground and background, must be numbers (-1 for default). - */ - bg: number; - fg: number; - /** - * Border attributes. - */ - bold: string; - underline: string; - /** - * Calculated width. - */ - width: number | string; - /** - * Calculated height. - */ - height: number | string; - /** - * Calculated relative top offset.*/ - top: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - left: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - right: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - bottom: Types.TPosition; - /** - * Calculated absolute top offset. - */ - atop: Types.TTopLeft; - /** - * Calculated absolute left offset. - */ - aleft: Types.TTopLeft; - /** - * Calculated absolute right offset. - */ - aright: Types.TPosition; - /** - * Calculated absolute bottom offset. - */ - abottom: Types.TPosition; - - /** - * Whether the element is draggable. Set to true to allow dragging. - */ - draggable: boolean; - - itop: Types.TTopLeft; - ileft: Types.TTopLeft; - iheight: Types.TPosition; - iwidth: Types.TPosition; - - /** - * Calculated relative top offset. - */ - rtop: Types.TTopLeft; - /** - * Calculated relative left offset. - */ - rleft: Types.TTopLeft; - /** - * Calculated relative right offset. - */ - rright: Types.TPosition; - /** - * Calculated relative bottom offset. - */ - rbottom: Types.TPosition; - - lpos: PositionCoords; - - // ** methods ** // - - /** - * Write content and children to the screen buffer. - */ - render(): Coords; - /** - * Hide element.*/ - hide(): void; - /** - * Show element. - */ - show(): void; - /** - * Toggle hidden/shown. - */ - toggle(): void; - /** - * Focus element. - */ - focus(): void; - /** - * Same asel.on('screen', ...) except this will automatically keep track of which listeners - * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). - */ - onScreenEvent(type: string, handler: Function): void; - /** - * Same asel.removeListener('screen', ...) except this will automatically keep track of which - * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). - */ - removeScreenEvent(type: string, handler: Function): void; - /** - * Free up the element. Automatically unbind all events that may have been bound to the screen - * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), - * and destroy(). - */ - free(): void; - /** - * Same as the detach() method, except this will automatically call free() and unbind any screen - * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). - */ - destroy(): void; - /** - * Set the z-index of the element (changes rendering order). - */ - setIndex(z: number): void; - /** - * Put the element in front of its siblings.*/ - setFront(): void; - /** - * Put the element in back of its siblings. - */ - setBack(): void; - /** - * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} - */ - setLabel(arg: string | LabelOptions): void; - /** - * Remove the label completely. - */ - removeLabel(): any; - /** - * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute - * in the browser. Example options: {text:'foo'} - */ - setHover(arg: string | LabelOptions): void; - /** - * Remove the hover label completely. - */ - removeHover(): void; - /** - * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). - */ - enableMouse(): void; - /** - * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). - */ - enableKeys(): void; - /** - * Enable key and mouse events. Calls bot enableMouse and enableKeys. - */ - enableInput(): void; - /** - * Enable dragging of the element. - */ - enableDrag(): void; - /** - * Disable dragging of the element. - */ - disableDrag(): void; - /** - * Take an SGR screenshot of the screen within the region. Returns a string containing only - * characters and SGR codes. Can be displayed by simply echoing it in a terminal. - */ - screenshot(xi: number, xl: number, yi: number, yl: number): string; - screenshot(): void; - - /* - Content Methods - - Methods for dealing with text content, line by line. Useful for writing a text editor, - irc client, etc. - - Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() - on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending - on how long the original line was. - - The lines parameter can be a string or an array of strings. The line parameter must - be a string. - */ - - /** - * Set the content. Note: When text is input, it will be stripped of all non-SGR - * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced - * with SGR codes (if enabled). - */ - setContent(text: string): void; - /** - * Return content, slightly different from el.content. Assume the above formatting. - */ - getContent(): string; - /** - * Similar to setContent, but ignore tags and remove escape codes. - */ - setText(text: string): void; - /** - * Similar to getContent, but return content with tags and escape codes removed. - */ - getText(): string; - /** - * Insert a line into the box's content. - */ - insertLine(i: number, lines: string | string[]): void; - /** - * Delete a line from the box's content. - */ - deleteLine(i: number): void; - /** - * Get a line from the box's content. - */ - getLine(i: number): string; - /** - * Get a line from the box's content from the visible top. - */ - getBaseLine(i: number): string; - /** - * Set a line in the box's content. - */ - setLine(i: number, line: string | string[]): void; - /** - * Set a line in the box's content from the visible top. - */ - setBaseLine(i: number, line: string | string[]): void; - /** - * Clear a line from the box's content. - */ - clearLine(i: number): void; - /** - * Clear a line from the box's content from the visible top. - */ - clearBaseLine(i: number): void; - /** - * Insert a line at the top of the box. - */ - insertTop(lines: string | string[]): void; - /** - * Insert a line at the bottom of the box. - */ - insertBottom(lines: string | string[]): void; - /** - * Delete a line at the top of the box. - */ - deleteTop(): void; - /** - * Delete a line at the bottom of the box. - */ - deleteBottom(): void; - /** - * Unshift a line onto the top of the content. - */ - unshiftLine(lines: string | string[]): void; - /** - * Shift a line off the top of the content. - */ - shiftLine(i: number): void; - /** - * Push a line onto the bottom of the content. - */ - pushLine(lines: string | string[]): void; - /** - * Pop a line off the bottom of the content. - */ - popLine(i: number): string; - /** - * An array containing the content lines. - */ - getLines(): string[]; - /** - * An array containing the lines as they are displayed on the screen. - */ - getScreenLines(): string[]; - /** - * Get a string's displayed width, taking into account double-width, surrogate pairs, - * combining characters, tags, and SGR escape codes. - */ - strWidth(text: string): string; - - // ** events ** // - } - - export interface ScrollableBoxOptions extends ElementOptions { - /** - * A limit to the childBase. Default is Infinity. - */ - baseLimit?: number; - /** - * A option which causes the ignoring of childOffset. This in turn causes the - * childBase to change every time the element is scrolled. - */ - alwaysScroll?: boolean; - /** - * Object enabling a scrollbar. - * Style of the scrollbar track if present (takes regular style options). - */ - scrollbar?: { style?: any; track?: any; ch?: string; } - } - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** - * Whether to enable automatic mouse support for this element. - * Use pre-defined mouse events (right-click for editor). - */ - mouse?: boolean | (() => void); - /** - * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). - */ - keys?: string | string[] | boolean; - /** - * Use vi keys with the keys option. - */ - vi?: boolean; - } - - export interface BoxOptions extends ScrollableTextOptions { - bindings?: any; - } - - /** - * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. - */ - export class ScrollableBoxElement extends BlessedElement { - /** - * The offset of the top of the scroll content. - */ - childBase: number; - /** - * The offset of the chosen item/line. - */ - childOffset: number; - - /** - * Scroll the content by a relative offset. - */ - scroll(offset: number, always?: boolean): void; - /** - * Scroll the content to an absolute index. - */ - scrollTo(index: number): void; - /** - * Same as scrollTo. - */ - setScroll(index: number): void; - /** - * Set the current scroll index in percentage (0-100). - */ - setScrollPerc(perc: number): void; - /** - * Get the current scroll index in lines. - */ - getScroll(): number; - /** - * Get the actual height of the scrolling area. - */ - getScrollHeight(): number; - /** - * Get the current scroll index in percentage. - */ - getScrollPerc(): number; - /** - * Reset the scroll index to its initial state. - */ - resetScroll(): void; - - on(event: string, listener: Function): this; - /** - * Received when the element is scrolled. - */ - on(event: "scroll", callback: () => void): this; - } - - /** - * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. - * A scrollable text box which can display and scroll text, as well as handle - * pre-existing newlines and escape codes. - */ - export class ScrollableTextElement extends ScrollableBoxElement { - } - - /** - * A box element which draws a simple box containing content or other elements. - */ - export class BoxElement extends ScrollableTextElement implements IHasOptions { - constructor(opts: BoxOptions); - - /** - * Original options object. - */ - options: BoxOptions; - } - - export interface TextOptions extends ElementOptions { - /** - * Fill the entire line with chosen bg until parent bg ends, even if there - * is not enough text to fill the entire width. - */ - fill?: boolean; - /** - * Text alignment: left, center, or right. - */ - align?: Types.TAlign; - } - - /** - * An element similar to Box, but geared towards rendering simple text elements. - */ - export class TextElement extends BlessedElement implements IHasOptions { - constructor(opts: TextOptions); - - /** - * Original options object. - */ - options: TextOptions; - } - - /** - * A simple line which can be line or bg styled. - */ - export interface LineOptions extends BoxOptions { - /** - * Can be vertical or horizontal. - */ - orientation?: "vertical" | "horizontal"; - /** - * Treated the same as a border object. (attributes can be contained in style). - */ + interface TStyle { type?: string; bg?: string; fg?: string; ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: { bg?: string; fg?: string }; + scrollbar?: { bg?: string; fg?: string }; } - /** - * A simple line which can be line or bg styled. - */ - export class LineElement extends BoxElement implements IHasOptions { - constructor(opts: LineOptions); + interface TBorder { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; /** - * Original options object. - */ - options: LineOptions; + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; } - export interface BigTextOptions extends BoxOptions { + interface TCursor { /** - * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - font?: string; + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** - * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). - */ - fontBold?: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: "block" | "underline" | "line"; + /** - * foreground character. (default: ' ') - */ - fch?: string; + * Whether the cursor blinks. + */ + blink: boolean; + + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } - /** - * A box which can render content drawn as 8x14 cell characters using the terminus font. - */ - export class BigTextElement extends BoxElement implements IHasOptions { - constructor(opts: BigTextOptions); + type TAlign = "left" | "center" | "right"; - /** - * Original options object. - */ - options: BigTextOptions; + interface ListbarCommand { + key: string; + callback(): void; } - export interface ListElementStyle { - selected?: any; - item?: any; + interface TImage { + /** + * Pixel width. + */ + width: number; + + /** + * Pixel height. + */ + height: number; + + /** + * Image bitmap. + */ + bmp: any; + + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; } - export interface ListOptions extends BoxOptions { + interface Cursor { /** - * Style for a selected item. Style for an unselected item. - */ - style?: TStyle; - /** - * An array of strings which become the list's items. - */ - items?: string[]; - /** - * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a - * callback function which should be called with the search string. The search string is then used to - * jump to an item that is found in items. - */ - search?: () => void; - /** - * Whether the list is interactive and can have items selected (Default: true). - */ - interactive?: boolean; - /** - * Whether to automatically override tags and invert fg of item when selected (Default: true). - */ - invertSelected?: boolean; - } - - export class ListElement extends BoxElement implements IHasOptions> { - constructor(opts: ListOptions); - - /** - * Original options object. - */ - options: ListOptions; - - /** - * Add an item based on a string. - */ - add(text: string): void; - /** - * Add an item based on a string. - */ - addItem(text: string): void; - /** - * Removes an item from the list. Child can be an element, index, or string. - */ - removeItem(child: BlessedElement): BlessedElement; - /** - * Push an item onto the list. - * */ - pushItem(child: BlessedElement): number; - /** - * Pop an item off the list. - * */ - popItem(): BlessedElement; - /** - * Unshift an item onto the list. - */ - unshiftItem(child: BlessedElement): number; - /** - * Shift an item off the list. - * */ - shiftItem(): BlessedElement; - /** - * Inserts an item to the list. Child can be an element, index, or string. - */ - insertItem(i: number, child: BlessedElement): void; - /** - * Returns the item element. Child can be an element, index, or string. - */ - getItem(child: BlessedElement): BlessedElement; - /** - * Set item to content. - */ - setItem(child: BlessedElement, content: BlessedElement | string): void; - /** - * Remove and insert items to the list. - * */ - spliceItem(i: number, n: number, ...items: BlessedElement[]): void; - /** - * Clears all items from the list. - * */ - clearItems(): void; - /** - * Sets the list items to multiple strings. - */ - setItems(items: BlessedElement[]): void; - /** - * Returns the item index from the list. Child can be an element, index, or string. - */ - getItemIndex(child: BlessedElement): number; - /** - * Select an index of an item. - * */ - select(index: number): void; - /** - * Select item based on current offset. - * */ - move(offset: number): void; - /** - * Select item above selected. - * */ - up(amount: number): void; - /** - * Select item below selected. - */ - down(amount: number): void; - /** - * Show/focus list and pick an item. The callback is executed with the result. - */ - pick(callback: () => void): void; - /** - * Find an item based on its text content. - */ - fuzzyFind(arg: string | RegExp | (() => void)): void; - - // ** events ** // + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "select", callback: (item: BoxElement, index: number) => void): this; - /** - * List was canceled (when esc is pressed with the keys option). - */ - on(event: "cancel", callback: () => void): this; - /** - * Either a select or a cancel event was received. - */ - on(event: "action", callback: () => void): this; - - on(event: "create item", callback: () => void): this; - on(event: "add item", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "insert item", callback: () => void): this; - on(event: "set items", callback: () => void): this; - on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; - } - - export interface FileManagerOptions extends ListOptions { - /** - * Current working directory. - */ - cwd?: string; - } - - export class FileManagerElement extends ListElement implements IHasOptions { - constructor(opts: FileManagerOptions); - - /** - * Original options object. - */ - options: FileManagerOptions; /** - * Current working directory. - */ - cwd: string; + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; /** - * Refresh the file list (perform a readdir on cwd and update the list items). - */ - refresh(cwd:string, callback: () => void): void; - refresh(callback: () => void): void; - refresh(): void; - /** - * Pick a single file and return the path in the callback. - */ - pick(cwd:string, callback: () => void): void; - pick(callback: () => void): void; - /** - * Reset back to original cwd. - */ - reset(cwd:string, callback: () => void): void; - reset(callback: () => void): void; - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Received when an item is selected. - */ - on(event: "cd", callback: (file: string, cwd: string) => void): this; - /** - * Received when an item is selected. - */ - on(event: "file", callback: (file: string) => void): this; - - on(event: "error", callback: (err: any, file: string) => void): this; - on(event: "refresh", callback: () => void): this; - } - - export interface StyleListTable extends ListElementStyle { - /** - * Header style. - */ - header?: any; - /** - * Cell style. - */ - cell?: any; - } - - export interface ListTableOptions extends ListOptions { - /** - * Array of array of strings representing rows. - */ - rows?: string[]; - data?: string[][]; - /** - * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side - * (only useful if the width is shrunken). - */ - pad?: number; - /** - * Do not draw inner cells. - */ - noCellBorders?: boolean; - - style?: StyleListTable; - } - - export class ListTableElement extends ListElement implements IHasOptions { - constructor(opts: ListTableOptions); - - /** - * Original options object. - */ - options: ListTableOptions; - - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setRows(rows: string[][]): void; - /** - * Set rows in table. Array of arrays of strings. - * @example: - * - * table.setData([ - [ 'Animals', 'Foods' ], - [ 'Elephant', 'Apple' ], - [ 'Bird', 'Orange' ] - ]); - */ - setData(rows: string[][]): void; - } - - export interface ListbarOptions extends BoxOptions { - style?: ListElementStyle; - /** - * Set buttons using an object with keys as titles of buttons, containing of objects - * containing keys of keys and callback. - */ - commands: Types.ListbarCommand[]; - items: Types.ListbarCommand[]; - /** - * Automatically bind list buttons to keys 0-9. - */ - autoCommandKeys: boolean; - } - - export class ListbarElement extends BoxElement implements IHasOptions { - constructor(opts: ListbarOptions); - - /** - * Original options object. - */ - options: ListbarOptions; - - /** - * Set commands (see commands option above). - */ - setItems(commands: Types.ListbarCommand[]): void; - /** - * Append an item to the bar. - */ - add(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - addItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Append an item to the bar. - */ - appendItem(item: Types.ListbarCommand, callback: () => void): void; - /** - * Select an item on the bar. - */ - select(offset: number): void; - /** - * Remove item from the bar. - */ - removeItem(child: BlessedElement): void; - /** - * Move relatively across the bar. - */ - move(offset: number): void; - /** - * Move left relatively across the bar. - */ - moveLeft(offset: number): void; - /** - * Move right relatively across the bar. - */ - moveRight(offset: number): void; - /** - * Select button and execute its callback. - */ - selectTab(index: number): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "set items", callback: () => void): this; - on(event: "remove item", callback: () => void): this; - on(event: "select tab", callback: () => void): this; - } - - export interface FormOptions extends BoxOptions { - /** - * Allow default keys (tab, vi keys, enter). - */ - keys?: any; - /** - * Allow vi keys. - */ - vi?: boolean; - } - - export class FormElement extends BoxElement implements IHasOptions { - constructor(opts: FormOptions); - - /** - * Original options object. - */ - options: FormOptions; - /** - * Last submitted data. - */ - submission: TFormData; - - /** - * Focus next form element. - */ - focusNext(): void; - /** - * Focus previous form element. - */ - focusPrevious(): void; - /** - * Submit the form. - */ - submit(): void; - /** - * Discard the form. - */ - cancel(): void; - /** - * Clear the form. - */ - reset(): void; - - // ** events ** // - - on(event: string, listener: Function): this; - /** - * Form is submitted. Receives a data object. - */ - on(event: "submit", callback: (out: TFormData) => void): this; - /** - * Form is discarded. - */ - on(event: "cancel", callback: () => void): this; - /** - * Form is cleared. - */ - on(event: "reset", callback: () => void): this; - } - - export interface InputOptions extends BoxOptions { } - - export abstract class InputElement extends BoxElement { - constructor(opts: InputOptions); - } - - /** - * A box which allows multiline text input. - */ - export interface TextareaOptions extends InputOptions { - /** - * Call readInput() when the element is focused. Automatically unfocus. - */ - inputOnFocus?: boolean; - } - - export class TextareaElement extends InputElement implements IHasOptions { - constructor(opts: TextareaOptions); - - /** - * Original options object. - */ - options: TextareaOptions; - - /** - * The input text. read-only. - */ - value: string; - - /** - * Submit the textarea (emits submit). - */ - submit(): void; - /** - * Cancel the textarea (emits cancel). - */ - cancel(): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - readInput(callback?: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - input(callback: (err: any, value?: string) => void): void; - /** - * Grab key events and start reading text from the keyboard. Takes a callback which receives - * the final value. - */ - setInput(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - readEditor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - editor(callback: (err: any, value?: string) => void): void; - /** - * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which - * receives the final value. - */ - setEditor(callback: (err: any, value?: string) => void): void; - /** - * The same as this.value, for now. - */ - getValue(): string; - /** - * Clear input. - */ - clearValue(): void; - /** - * Set value. - */ - setValue(text: string): void; - - // ** events ** // - - on(event: string, listener: Function): this; - - on(event: "error", callback: (err: any) => void): this; - - /** - * Value is submitted (enter). - */ - on(event: "submit", callback: (value: any) => void): this; - /** - * Value is discared (escape). - */ - on(event: "cancel", callback: (value: any) => void): this; - /** - * Either submit or cancel. - */ - on(event: "action", callback: (value: any) => void): this; - } - - export interface TextboxOptions extends TextareaOptions { - /** - * Completely hide text. - */ - secret?: boolean; - /** - * Replace text with asterisks (*). - */ - censor?: boolean; - } - - export class TextboxElement extends TextareaElement implements IHasOptions { - constructor(opts: TextboxOptions); - - /** - * Original options object. - */ - options: TextboxOptions; - - /** - * Completely hide text. - */ - secret: boolean; - /** - * Replace text with asterisks (*). - */ - censor: boolean; - } - - export interface ButtonOptions extends BoxOptions { } - - export class ButtonElement extends InputElement implements IHasOptions { - constructor(opts: ButtonOptions); - - /** - * Original options object. - */ - options: ButtonOptions; - - /** - * Press button. Emits press. - */ - press(): void; - - on(event: string, listener: Function): this; - - on(event: "press", callback: () => void): this; - } - - export interface CheckboxOptions extends BoxOptions { - /** - * whether the element is checked or not. - * */ - checked?: boolean; - /** - * enable mouse support. - * */ - mouse?: boolean; - } - - /** - * A checkbox which can be used in a form element. - * */ - export class CheckboxElement extends InputElement implements IHasOptions { - constructor(options?: CheckboxOptions); - - /** - * Original options object. - */ - options: CheckboxOptions; - - /** - * the text next to the checkbox (do not use setcontent, use `check.text = ''`). - * */ - text: string; - /** - * whether the element is checked or not. - * */ - checked: boolean; - /** - * same as `checked`. - * */ - value: boolean; - - /** - * check the element. - * */ - check(): void; - /** - * uncheck the element. - * */ - uncheck(): void; - /** - * toggle checked state. - * */ - toggle(): void; - } - - export interface RadioSetOptions extends BoxOptions { } - - /** - * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive - * with each other. - * */ - export abstract class RadioSetElement extends BoxElement { - constructor(opts: RadioSetOptions); - } - - export interface RadioButtonOptions extends BoxOptions { } - - /** - * A radio button which can be used in a form element. - */ - export abstract class RadioButtonElement extends CheckboxElement { - constructor(opts: RadioButtonOptions); - } - - export interface PromptOptions extends BoxOptions { } - - /** - * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). - */ - export class PromptElement extends BoxElement implements IHasOptions { - constructor(opts: PromptOptions); - - options: PromptOptions; - - /** - * Show the prompt and wait for the result of the textbox. Set text and initial value. - */ - input(text: string, value: string, callback: (err: any, value: string) => void): void; - setInput(text: string, value: string, callback: (err: any, value: string) => void): void; - readInput(text: string, value: string, callback: (err: any, value: string) => void): void; - } - - export interface QuestionOptions extends BoxOptions { } - - /** - * A question box containing okay and cancel buttons (automatically hidden). - */ - export class QuestionElement extends BoxElement implements IHasOptions { - constructor(opts: QuestionOptions); - - options: QuestionOptions; - - /** - * Ask a question. callback will yield the result. - */ - ask(question: string, callback: (err: any, value: string) => void): void; - } - - export interface MessageOptions extends BoxOptions { } - - /** - * A box containing a message to be displayed (automatically hidden). - */ - export class MessageElement extends BoxElement implements IHasOptions { - constructor(opts: MessageOptions); - - options: MessageOptions; - - /** - * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. - */ - log(text: string, time: number, callback: (err: any) => void): void; - log(text: string, callback: (err: any) => void): void; - display(text: string, time: number, callback: (err: any) => void): void; - display(text: string, callback: (err: any) => void): void; - - /** - * Display an error in the same way. - */ - error(text: string, time: number, callback: () => void): void; - error(text: string, callback: () => void): void; - } - - export interface LoadingOptions extends BoxOptions { } - - /** - * A box with a spinning line to denote loading (automatically hidden). - */ - export class LoadingElement extends BoxElement implements IHasOptions { - constructor(opts: LoadingOptions); - - options: LoadingOptions; - - /** - * Display the loading box with a message. Will lock keys until stop is called. - */ - load(text: string): void; - /** - * Hide loading box. Unlock keys. - */ - stop(): void; - } - - export interface ProgressBarOptions extends BoxOptions { - /** - * can be `horizontal` or `vertical`. - * */ - orientation: string; - /** - * the character to fill the bar with (default is space). - * */ - pch: string; - /** - * the amount filled (0 - 100). - * */ - filled: number; - /** - * same as `filled`. - * */ - value: number; - /** - * enable key support. - * */ - keys: boolean; - /** - * enable mouse support. - * */ - mouse: boolean; - } - - /** - * A progress bar allowing various styles. This can also be used as a form input. - */ - export class ProgressBarElement extends InputElement implements IHasOptions { - constructor(options?: ProgressBarOptions); - - options: ProgressBarOptions; - - /** - * progress the bar by a fill amount. - * */ - progress(amount:number): void; - /** - * set progress to specific amount. - * */ - setProgress(amount:number): void; - /** - * reset the bar. - * */ - reset(): void; - - on(event: string, listener: Function): this; - /** - * Bar was reset. - */ - on(event: "reset", callback: () => void): this; - /** - * Bar has completely filled. - */ - on(event: "complete", callback: () => void): this; - } - - export interface LogOptions extends ScrollableTextOptions { - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback?: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput?: boolean; - } - - /** - * A log permanently scrolled to the bottom. - * */ - export class Log extends ScrollableTextElement implements IHasOptions { - constructor(options?: LogOptions); - - options: LogOptions; - - /** - * amount of scrollback allowed. default: Infinity. - * */ - scrollback: number; - /** - * scroll to bottom on input even if the user has scrolled up. default: false. - * */ - scrollOnInput: boolean; - - /** - * add a log line. - * */ - log(text:string): void; - /** - * add a log line. - * */ - add(text:string): void; - } - - export interface TableOptions extends BoxOptions { - /** - * array of array of strings representing rows (same as `data`). - * */ - rows?: string[][]; - /** - * array of array of strings representing rows (same as `rows`). - * */ - data?: string[][]; - /** - * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). - * */ - pad?: number; - /** - * do not draw inner cells. - * */ - noCellBorders?: boolean; - /** - * fill cell borders with the adjacent background color. - * */ - fillCellBorders?: boolean; - } - - /** - * A stylized table of text elements. - * */ - export class TableElement extends BoxElement implements IHasOptions { - constructor(opts: TableOptions); - - options: TableOptions; - - /** - * set rows in table. array of arrays of strings. - * */ - setData(rows: string[][]): void; - /** - * set rows in table. array of arrays of strings. - * */ - setRows(rows: string[][]): void; - } - - export interface TerminalOptions extends BoxOptions { - /** - * handler for input data. - * */ - handler?: (userInput:Buffer) => void; - /** - * name of shell. $SHELL by default. - * */ - shell?:string; - /** - * args for shell. - * */ - args?:any; - /** - * can be line, underline, and block. - * */ - cursor?: 'line'|'underline'|'block'; - - terminal?: string; - - /** - * Object for process env. - */ - env?: any; - } - - export class TerminalElement extends BoxElement implements IHasOptions { - constructor(opts: TerminalOptions); - - options: TerminalOptions; - - /** - * reference to the headless term.js terminal. - * */ - term: any; - /** - * reference to the pty.js pseudo terminal. - * */ - pty: any; - - /** - * write data to the terminal. - * */ - write(data:string): void; - - /** - * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. - * */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - export interface ImageOptions extends BoxOptions { - /** - * path to image. - * */ - file: string; - /** - * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - * */ - type: "ansi" | "overlay" | "w3m"; - } - - /** - * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. - * */ - export class ImageElement extends BoxElement implements IHasOptions { - constructor(options?: ImageOptions); - - options: ImageOptions; - } - - export interface ANSIImageOptions extends BoxOptions { - /** - * URL or path to PNG/GIF file. Can also be a buffer. - * */ - file: string; - /** - * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). - * */ - scale: number; - - /** - * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. - * */ - width: number | string; - height: number | string; - - /** - * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). - */ - ascii: string; - - /** - * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). - */ - animate: boolean; - - /** - * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) - */ - speed: number; - - /** - * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). - */ - optimization: "mem" | "cpu"; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class ANSIImageElement extends BoxElement implements IHasOptions { - constructor(options?:ANSIImageOptions); - - options: ANSIImageOptions; - - /** - * Image object from the png reader. - */ - img: Types.TImage; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * Play animation if it has been paused or stopped. - */ - play(): void; - /** - * Pause animation. - */ - pause(): void; - /** - * Stop animation. - */ - stop(): void; - } - - export interface OverlayImageOptions extends BoxOptions { - /** - * Path to image. - */ - file: string; - /** - * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). - */ - ansi: boolean; - /** - * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. - */ - w3m: string; - /** - * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). - */ - search: string; - } - - /** - * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. - * */ - export class OverlayImageElement extends BoxElement implements IHasOptions { - constructor(options?: OverlayImageOptions); - - options: OverlayImageOptions; - - /** - * set the image in the box to a new path. - * */ - setImage(img: string, callback: () => void): void; - /** - * clear the current image. - * */ - clearImage(callback: () => void): void; - /** - * get the size of an image file in pixels. - * */ - imageSize(img:string, callback: () => void): void; - /** - * get the size of the terminal in pixels. - * */ - termSize(callback: () => void): void; - /** - * get the pixel to cell ratio for the terminal. - * */ - getPixelRatio(callback: () => void): void; - } - - export interface VideoOptions extends BoxOptions { - /** - * Video to play. - */ - file: string; - /** - * Start time in seconds. - */ - start: number; - } - - export class VideoElement extends BoxElement implements IHasOptions { - constructor(options?: VideoOptions); - - options: VideoOptions; - - /** - * The terminal element running mplayer or mpv. - */ - tty: any; - } - - export interface LayoutOptions extends ElementOptions { - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer?: () => void; - - /** - * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render - * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' - * width and height are always determined by the largest children in the layout. - */ - layout: "inline" | "inline-block" | "grid"; - } - - export class LayoutElement extends BlessedElement implements IHasOptions { - constructor(options?: LayoutOptions); - - options: LayoutOptions; - - /** - * A callback which is called right before the children are iterated over to be rendered. Should return an - * iterator callback which is called on each child element: iterator(el, i). - */ - renderer(coords: PositionCoords): void; - /** - * Check to see if a previous child element has been rendered and is visible on screen. This is only useful - * for checking child elements that have already been attempted to be rendered! see the example below. - */ - isRendered(el: BlessedElement): boolean; - /** - * Get the last rendered and visible child element based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. - */ - getLast(i: number): Element; - /** - * Get the last rendered and visible child element coords based on an index. This is useful for basing the position - * of the current child element on the position of the last child element. See the example below. - */ - getLastCoords(i: number): PositionCoords; - } + * Whether the cursor blinks. + */ + blink: boolean; - export class Program { /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; } } - export module widget { - export class Element extends Widgets.BlessedElement { } - export class Node extends Widgets.Node { } - export class Screen extends Widgets.Screen { } + namespace Events { + interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } - export class Box extends Widgets.BoxElement { } - export class ScrollableBox extends Widgets.ScrollableBoxElement { } - export class ScrollableText extends Widgets.ScrollableTextElement { } - export class Text extends Widgets.BoxElement { } - export class Line extends Widgets.LineElement { } - export class BigText extends Widgets.BigTextElement { } - export class List extends Widgets.ListElement { } - export class FileManager extends Widgets.FileManagerElement { } - export class ListTable extends Widgets.ListTableElement { } - export class ListBar extends Widgets.ListbarElement { } - export class Form extends Widgets.FormElement { } - export class Textarea extends Widgets.TextareaElement { } - export class Button extends Widgets.ButtonElement { } - export class Checkbox extends Widgets.CheckboxElement { } - export class RadioSet extends Widgets.RadioSetElement { } - export class RadioButton extends Widgets.RadioButtonElement { } - - export class Prompt extends Widgets.PromptElement { } - export class question extends Widgets.QuestionElement { } - export class Message extends Widgets.MessageElement { } - export class Loading extends Widgets.LoadingElement { } - - export class ProgressBar extends Widgets.ProgressBarElement { } - export class Terminal extends Widgets.TerminalElement { } + interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + interface NodeChildProcessExecOptions { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + } - export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function text(options?: Widgets.TextOptions): Widgets.TextElement; - export function line(options?: Widgets.LineOptions): Widgets.LineElement; - export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; - export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; - export function list(options?: Widgets.ListOptions): Widgets.ListElement; - export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; - export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; - export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; - export function form(options?: Widgets.FormOptions): Widgets.FormElement; - export function input(options?: Widgets.InputOptions): Widgets.InputElement; - export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; - export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; - export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; - export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; - export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; - export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + interface IDestroyable { + destroy(): void; + } - export function table(options?: Widgets.TableOptions): Widgets.TableElement; + interface IOptions {} - export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; - export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; - export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; - export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; - export function log(options?: Widgets.LogOptions): Widgets.Log; + interface IHasOptions { + options: T; + } - export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; - export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } - export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + class Tput implements IHasOptions { + constructor(opts: TputsOptions); - export function escape(item: any): any; - export const colors: { - match: (hexColor: string) => string + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo( + data: any, + file: string + ): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + }; + }; + name: string; + names: string[]; + desc: string; + bools: any; + numbers: any; + strings: any; + }; + } + + interface IDestroyable { + destroy(): void; + } + + interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + type NodeEventType = + /** Received when node is added to a parent. */ + | "adopt" + /** Received when node is removed from it's current parent. */ + | "remove" + /** Received when node gains a new parent. */ + | "reparent" + /** Received when node is attached to the screen directly or somewhere in its ancestry. */ + | "attach" + /** Received when node is detached from the screen directly or somewhere in its ancestry. */ + | "detach"; + + abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + _: { [index: string]: any }; + + /** + * An object for any miscellanous user data. + */ + $: { [index: string]: any }; + + /** + * Type of the node (e.g. box). + */ + type: string; + + /** + * Render index (document order index) of the last render call. + */ + index: number; + + /** + * Parent screen. + */ + screen: Screen; + + /** + * Parent node. + */ + parent: Node; + + /** + * Array of node's children. + */ + children: Node[]; + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + + /** + * Append a node to this node's children. + */ + append(node: Node): void; + + /** + * Remove child node from node. + */ + remove(node: Node): void; + + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + + /** + * Remove node from its parent. + */ + detach(): void; + free(): void; + forDescendants(iter: (node: Node) => void, s: any): void; + forAncestors(iter: (node: Node) => void, s: any): void; + collectDescendants(s: any): void; + collectAncestors(s: any): void; + + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type?: string, ...args: any[]): void; + emitAncestors(): void; + hasDescendant(target: Node): void; + hasAncestor(target: Node): boolean; + destroy(): void; + + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + + /** + * Set user property to value. + */ + set(name: string, value: any): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: NodeEventType, callback: (arg: Node) => void): this; + } + + type NodeScreenEventType = + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "focus" + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + | "blur" + /** + * Element was clicked (slightly smarter than mouseup). + */ + | "click" + | "element click" + | "element mouseover" + | "element mouseout" + | "element mouseup"; + + type NodeMouseEventType = + | "mouse" + | "mouseout" + | "mouseover" + | "mousedown" + | "mouseup" + | "mousewheel" + | "wheeldown" + | "wheelup" + | "mousemove"; + + type NodeGenericEventType = + /** Received on screen resize. */ + | "resize" + /** Received before render. */ + | "prerender" + /** Received on render. */ + | "render" + /** Received when the screen is destroyed (only useful when using multiple screens). */ + | "destroy" + /** Received when the element is moved. */ + | "move" + /** Received when element is shown. */ + | "show" + /** Received when element becomes hidden. */ + | "hide" + | "set content" + | "parsed content"; + + class NodeWithEvents extends Node { + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + removeKey(name: string, listener: (ch: any, key: Events.IKeyEventArg) => void): void; + + on(event: string, listener: (ch: any, key: Events.IKeyEventArg) => void): this; + /** Received on mouse events. */ + on(event: NodeMouseEventType, callback: (arg: Events.IMouseEventArg) => void): this; + /** Received on key events. */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + on(event: NodeScreenEventType, callback: (arg: Screen) => void): this; + /** Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). */ + on(event: "warning", callback: (text: string) => void): this; + on(event: NodeGenericEventType, callback: () => void): this; + } + + interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?(...msg: any[]): void; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?(...msg: string[]): void; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input?: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output?: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + + /** + * Same as screen.width. + */ + cols?: number; + + /** + * Same as screen.height. + */ + rows?: number; + + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + + /** + * Set or get window title. + */ + title?: string; + } + + class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + + /** + * The width of tabs within an element's content. + */ + tabSize: number; + + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + input: stream.Writable; + + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + */ + output: stream.Readable; + + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + + /** + * Same as screen.width. + */ + cols: number; + + /** + * Same as screen.height. + */ + rows: number; + + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + + /** + * Set or get window title. + */ + title: string; + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + + /** + * Focus next element in the index. + */ + focusNext(): void; + + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec( + file: string, + args: string[], + options: NodeChildProcessExecOptions, + callback: (...args: any[]) => void + ): child_process.ChildProcess; + + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el?: BlessedElement): void; + + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el?: BlessedElement): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el?: BlessedElement): void; + + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + + /** + * Character to use if bg type, default is space. + */ + ch?: string; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + + /** + * Element's text content. + */ + content?: string; + + /** + * Element is clickable. + */ + clickable?: boolean; + + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + + /** + * Element is focused. + */ + focused?: BlessedElement; + + /** + * Whether the element is hidden. + */ + hidden?: boolean; + + /** + * A simple text label for the element. + */ + label?: string; + + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + + /** + * Can contain the above options. + */ + position?: Position; + + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + + /** + * Background character (default is whitespace ). + */ + ch?: string; + + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: { x: number; y: number }; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + /** + * Original options object. + */ + options: ElementOptions; + + /** + * Name of the element. Useful for form submission. + */ + name: string; + + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + + /** + * Border attributes. + */ + bold: string; + underline: string; + + /** + * Calculated width. + */ + width: number | string; + + /** + * Calculated height. + */ + height: number | string; + + /** + * Calculated relative top offset. + */ + top: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + + /** + * Hide element. + */ + hide(): void; + + /** + * Show element. + */ + show(): void; + + /** + * Toggle hidden/shown. + */ + toggle(): void; + + /** + * Focus element. + */ + focus(): void; + + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: (...args: any[]) => void): void; + + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + + /** + * Put the element in front of its siblings. + */ + setFront(): void; + + /** + * Put the element in back of its siblings. + */ + setBack(): void; + + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + + /** + * Remove the label completely. + */ + removeLabel(): any; + + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + + /** + * Remove the hover label completely. + */ + removeHover(): void; + + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + + /** + * Enable dragging of the element. + */ + enableDrag(): void; + + /** + * Disable dragging of the element. + */ + disableDrag(): void; + + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + + /** + * An array containing the content lines. + */ + getLines(): string[]; + + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + } + + interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string }; + } + + interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + + /** + * Get the current scroll index in lines. + */ + getScroll(): number; + + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): number; + + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): number; + + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + class ScrollableTextElement extends ScrollableBoxElement {} + + /** + * A box element which draws a simple box containing content or other elements. + */ + class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + interface ListElementStyle { + selected?: any; + item?: any; + } + + interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + + /** + * An array of strings which become the list's items. + */ + items?: string[]; + + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?(err: any, value?: string): void; + + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + type ListElementEventType = + /** List was canceled (when esc is pressed with the keys option). */ + | "cancel" + /** Either a select or a cancel event was received. */ + | "action" + | "create item" + | "add item" + | "remove item" + | "insert item" + | "set items"; + + class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + + /** + * Add an item based on a string. + */ + addItem(text: string): void; + + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + + /** + * Push an item onto the list. + */ + pushItem(child: BlessedElement): number; + + /** + * Pop an item off the list. + */ + popItem(): BlessedElement; + + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + + /** + * Shift an item off the list. + */ + shiftItem(): BlessedElement; + + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + + /** + * Remove and insert items to the list. + */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + + /** + * Clears all items from the list. + */ + clearItems(): void; + + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + + /** + * Select an index of an item. + */ + select(index: number): void; + + /** + * Select item based on current offset. + */ + move(offset: number): void; + + /** + * Select item above selected. + */ + up(amount: number): void; + + /** + * Select item below selected. + */ + down(amount: number): void; + + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + on(event: ListElementEventType, callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd: string, callback: () => void): void; + refresh(callback?: () => void): void; + + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd: string, callback: () => void): void; + pick(callback: () => void): void; + + /** + * Reset back to original cwd. + */ + reset(cwd: string, callback: () => void): void; + reset(callback?: () => void): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Received when an item is selected. */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** Received when an item is selected. */ + on(event: "file", callback: (file: string) => void): this; + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + + /** + * Cell style. + */ + cell?: any; + } + + interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setRows(rows: string[][]): void; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + * [ 'Animals', 'Foods' ], + * [ 'Elephant', 'Apple' ], + * [ 'Bird', 'Orange' ] + * ]); + */ + setData(rows: string[][]): void; + } + + interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + + /** + * Select an item on the bar. + */ + select(offset: number): void; + + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + + /** + * Move relatively across the bar. + */ + move(offset: number): void; + + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "set items" | "remove item" | "select tab", callback: () => void): this; + } + + interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + + /** + * Allow vi keys. + */ + vi?: boolean; + } + + class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + + /** + * Focus previous form element. + */ + focusPrevious(): void; + + /** + * Submit the form. + */ + submit(): void; + + /** + * Discard the form. + */ + cancel(): void; + + /** + * Clear the form. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + /** Form is submitted. Receives a data object. */ + on(event: "submit", callback: (out: TFormData) => void): this; + on(event: "cancel" | "reset", callback: () => void): this; + } + + interface InputOptions extends BoxOptions {} + + abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + type TextareaElementEventType = + /** Value is an error. */ + | "error" + /** Value is submitted (enter). */ + | "submit" + /** Value is discared (escape). */ + | "cancel" + /** Either submit or cancel. */ + | "action"; + + class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + + /** + * The same as this.value, for now. + */ + getValue(): string; + + /** + * Clear input. + */ + clearValue(): void; + + /** + * Set value. + */ + setValue(text: string): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: TextareaElementEventType, callback: (err: any) => void): this; + } + + interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + interface ButtonOptions extends BoxOptions {} + + class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "press", callback: () => void): this; + } + + interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + */ + checked?: boolean; + + /** + * enable mouse support. + */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + */ + class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + */ + text: string; + + /** + * whether the element is checked or not. + */ + checked: boolean; + + /** + * same as `checked`. + */ + value: boolean; + + /** + * check the element. + */ + check(): void; + + /** + * uncheck the element. + */ + uncheck(): void; + + /** + * toggle checked state. + */ + toggle(): void; + } + + interface RadioSetOptions extends BoxOptions {} + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + */ + abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + interface RadioButtonOptions extends BoxOptions {} + + /** + * A radio button which can be used in a form element. + */ + abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + interface PromptOptions extends BoxOptions {} + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + interface QuestionOptions extends BoxOptions {} + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + interface MessageOptions extends BoxOptions {} + + /** + * A box containing a message to be displayed (automatically hidden). + */ + class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a + * perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + interface LoadingOptions extends BoxOptions {} + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + */ + orientation: string; + + /** + * the character to fill the bar with (default is space). + */ + pch: string; + + /** + * the amount filled (0 - 100). + */ + filled: number; + + /** + * same as `filled`. + */ + value: number; + + /** + * enable key support. + */ + keys: boolean; + + /** + * enable mouse support. + */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + */ + progress(amount: number): void; + + /** + * set progress to specific amount. + */ + setProgress(amount: number): void; + + /** + * reset the bar. + */ + reset(): void; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "reset" | "complete", callback: () => void): this; + } + + interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback?: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + */ + class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + */ + scrollback: number; + + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + */ + scrollOnInput: boolean; + + /** + * add a log line. + */ + log(text: string): void; + + /** + * add a log line. + */ + add(text: string): void; + } + + interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + */ + rows?: string[][]; + + /** + * array of array of strings representing rows (same as `rows`). + */ + data?: string[][]; + + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + */ + pad?: number; + + /** + * do not draw inner cells. + */ + noCellBorders?: boolean; + + /** + * fill cell borders with the adjacent background color. + */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + */ + class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + */ + setData(rows: string[][]): void; + + /** + * set rows in table. array of arrays of strings. + */ + setRows(rows: string[][]): void; + } + + interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + */ + handler?(userInput: Buffer): void; + + /** + * name of shell. $SHELL by default. + */ + shell?: string; + + /** + * args for shell. + */ + args?: any; + + /** + * can be line, underline, and block. + */ + cursor?: "line" | "underline" | "block"; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + */ + term: any; + + /** + * reference to the pty.js pseudo terminal. + */ + pty: any; + + /** + * write data to the terminal. + */ + write(data: string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's + * _entire_ scrollback, rather than just what is visible on the screen. + */ + screenshot(xi?: number, xl?: number, yi?: number, yl?: number): string; + } + + interface ImageOptions extends BoxOptions { + /** + * path to image. + */ + file: string; + + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the + * entire disk for the binary. + */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. + * X11 required: works in xterm, urxvt, and possibly other terminals. + */ + class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + */ + file: string; + + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + */ + scale: number; + + /** + * This differs from other element's width or height in that only one + * of them is needed: blessed will maintain the aspect ratio of the image + * as it scales down to the proper number of cells. NOTE: PNG/GIF's are + * always automatically shrunken to size (based on scale) if a width or + * height is not given. + */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the + * image more detail, similar to libcaca/libcucul (the library mplayer uses + * to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only + * display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go + * faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to + * bitmaps as the animation plays, using less memory. Optimizing for cpu will + * precompile all bitmaps beforehand, which may be faster, but might also OOM + * the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?: ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + + /** + * Pause animation. + */ + pause(): void; + + /** + * Stop animation. + */ + stop(): void; + } + + interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the + * ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will + * search the entire disk for the binary. + */ + w3m: string; + + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + */ + class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + */ + setImage(img: string, callback: () => void): void; + + /** + * clear the current image. + */ + clearImage(callback: () => void): void; + + /** + * get the size of an image file in pixels. + */ + imageSize(img: string, callback: () => void): void; + + /** + * get the size of the terminal in pixels. + */ + termSize(callback: () => void): void; + + /** + * get the pixel to cell ratio for the terminal. + */ + getPixelRatio(callback: () => void): void; + } + + interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + + /** + * Start time in seconds. + */ + start: number; + } + + class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?(): void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): BlessedElement; + + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + class Program { + /** + * Wrap the given text in terminal formatting codes corresponding to the given attribute + * name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + * integer color number. + */ + text(text: string, attr: string): string; } } -export = Blessed; +export namespace widget { + class Terminal extends Widgets.TerminalElement {} +} + +export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; +export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function text(options?: Widgets.TextOptions): Widgets.TextElement; +export function line(options?: Widgets.LineOptions): Widgets.LineElement; +export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; +export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; +export function list(options?: Widgets.ListOptions): Widgets.ListElement; +export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; +export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; +export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; +export function form(options?: Widgets.FormOptions): Widgets.FormElement; +export function input(options?: Widgets.InputOptions): Widgets.InputElement; +export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; +export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; +export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; +export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; +export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; +export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; +export function table(options?: Widgets.TableOptions): Widgets.TableElement; +export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; +export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; +export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; +export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; +export function log(options?: Widgets.LogOptions): Widgets.Log; +export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; +export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; +export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; +export function escape(item: any): any; + +export const colors: { + match(hexColor: string): string; +}; diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index eb3260a007..e9beaf5562 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -1,13 +1,13 @@ import Promise = require('bluebird'); import retry = require('bluebird-retry'); -function promiseSuccess(text:string) { +function promiseSuccess(text: string) { return Promise.resolve(text); -}; +} -var count = 0; +let count = 0; function myfunc() { - console.log('myfunc called ' + (++count) + ' times'); + console.log(`myfunc called ${++count} times`); if (count < 3) { throw new Error('i fail the first two times'); } else { @@ -16,18 +16,17 @@ function myfunc() { } retry(myfunc) - .done(function(result) { console.log(result); } ); + .done(result => { console.log(result); }); - -//Options example +// Options example function logFail() { console.log(new Date().toISOString()); throw new Error('bail'); } -var options:retry.Options = { +const options: retry.Options = { max_tries: 4, interval: 500 }; -retry(logFail, options); \ No newline at end of file +retry(logFail, options); diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 97d756524b..358c75936d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for bluebird-retry +// Type definitions for bluebird-retry 0.11 // Project: https://github.com/jut-io/bluebird-retry // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - import Promise = require('bluebird'); declare function retry(func: (param: T) => void, options?: retry.Options): Promise; declare namespace retry { - export interface Options { + interface Options { interval?: number; backoff?: number; max_interval?: number; @@ -22,7 +20,6 @@ declare namespace retry { context?: any; args?: any; } - } export = retry; diff --git a/types/bluebird-retry/tslint.json b/types/bluebird-retry/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/bluebird-retry/tslint.json +++ b/types/bluebird-retry/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 49bd5e3808..ba7a8bd172 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -43,24 +43,37 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { constructor(callback: (resolve: (thenableOrResult?: R | PromiseLike) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); /** - * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + * Promises/A+ `.then()`. Returns a new promise chained from this promise. + * + * The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. */ // Based on PromiseLike.then, but returns a Bluebird instance. then(onFulfill?: (value: R) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike): Bluebird; // For simpler signature help. - then(onfulfilled?: ((value: R) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): Bluebird; + then( + onfulfilled?: ((value: R) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | null + ): Bluebird; /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. + * + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ catch(onReject: (error: any) => R | PromiseLike): Bluebird; - catch(onReject?: ((error: any) => U | PromiseLike) | undefined | null): Bluebird; + catch(onReject: ((error: any) => U | PromiseLike) | undefined | null): Bluebird; /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * Instead of manually checking `instanceof` or `.name === "SomeError"`, + * you may specify a number of error constructors which are eligible for this catch handler. + * The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. + * If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. + * The return result of the predicate will be used determine whether the error handler should be called. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ @@ -190,17 +203,23 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { ): Bluebird; /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. + * + * Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ caught(onReject: (error: any) => R | PromiseLike): Bluebird; - caught(onReject?: ((error: any) => U | PromiseLike) | undefined | null): Bluebird; + caught(onReject: ((error: any) => U | PromiseLike) | undefined | null): Bluebird; /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. + * The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. + * The return result of the predicate will be used determine whether the error handler should be called. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ @@ -335,7 +354,9 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { error(onReject: (reason: any) => U | PromiseLike): Bluebird; /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. + * + * There are special semantics for `.finally()` in that the final value cannot be modified from the handler. * * Alias `.lastly();` for compatibility with earlier ECMAScript version. */ @@ -344,7 +365,9 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { lastly(handler: () => U | PromiseLike): Bluebird; /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. + * + * Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. */ bind(thisArg: any): Bluebird; @@ -409,7 +432,11 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { timeout(ms: number, message?: string | Error): Bluebird; /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Register a node-style callback on this promise. + * + * When this promise is is either fulfilled or rejected, + * the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. + * The error argument will be `null` in case of success. * If the `callback` argument is not a function, this method does not do anything. */ nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; @@ -694,7 +721,8 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { /** * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. + * Otherwise it is passed as is as the first argument for the function call. * * Alias for `attempt();` for compatibility with earlier ECMAScript version. */ @@ -702,7 +730,8 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static attempt(fn: () => R | PromiseLike): Bluebird; /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * Returns a new function that wraps the given function `fn`. + * The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. * This method is convenient when a function can sometimes return synchronously or throw synchronously. */ static method(fn: (arg1: A1) => R | PromiseLike): (arg1: A1) => Bluebird; @@ -729,7 +758,10 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static defer(): Bluebird.Resolver; /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + * Cast the given `value` to a trusted promise. + * + * If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. + * If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. */ static cast(value: R | PromiseLike): Bluebird; @@ -744,7 +776,10 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static is(value: any): boolean; /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + * Call this right after the library is loaded to enabled long stack traces. + * + * Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. + * Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. */ static longStackTraces(): void; @@ -757,24 +792,49 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static delay(ms: number): Bluebird; /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * Returns a function that will wrap the given `nodeFunction`. + * + * Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. + * The node function should conform to node.js convention of accepting a callback as last argument and + * calling that callback with error as the first argument and success value on the second argument. * * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. * * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. */ - static promisify(func: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird; - static promisify(func: (arg1: A1, callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; + static promisify( + func: (callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): () => Bluebird; + static promisify( + func: (arg1: A1, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1) => Bluebird; + static promisify( + func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2) => Bluebird; + static promisify( + func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; + static promisify( + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; + static promisify( + func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void, + options?: Bluebird.PromisifyOptions + ): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; static promisify(nodeFunction: (...args: any[]) => void, options?: Bluebird.PromisifyOptions): (...args: any[]) => Bluebird; /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + * The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, + * if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. */ // TODO how to model promisifyAll? static promisifyAll(target: T, options?: Bluebird.PromisifyAllOptions): T; @@ -788,19 +848,49 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static fromCallback(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + * Returns a function that can use `yield` to run asynchronous code synchronously. + * + * This feature requires the support of generators which are drafted in the next version of the language. + * Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. */ // TODO: After https://github.com/Microsoft/TypeScript/issues/2983 is implemented, we can use // the return type propagation of generators to automatically infer the return type T. - static coroutine(generatorFunction: () => IterableIterator, options?: Bluebird.CoroutineOptions): () => Bluebird; - static coroutine(generatorFunction: (a1: A1) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird; - static coroutine(generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator, options?: Bluebird.CoroutineOptions): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird; + static coroutine( + generatorFunction: () => IterableIterator, + options?: Bluebird.CoroutineOptions + ): () => Bluebird; + static coroutine( + generatorFunction: (a1: A1) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird; + static coroutine( + generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator, + options?: Bluebird.CoroutineOptions + ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird; /** * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. @@ -820,7 +910,9 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird) => void): void; /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. + * The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. + * If any promise in the array rejects, the returned promise is rejected with the rejection reason. */ // TODO enable more overloads // array with promises of different types @@ -833,9 +925,13 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static all(values: PromiseLike | R>> | Iterable | R>): Bluebird; /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. + * If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. + * All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. * * *The original object is not modified.* */ @@ -859,7 +955,8 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { static race(values: PromiseLike | R>> | Iterable | R>): Bluebird; /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). + * When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. * * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. * @@ -874,60 +971,112 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * ) -> Promise * For coordinating multiple concurrent discrete promises. * - * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply + * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. + * This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply */ - static join(arg1: A1 | PromiseLike, handler: (arg1: A1) => R | PromiseLike): Bluebird; - static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, handler: (arg1: A1, arg2: A2) => R | PromiseLike): Bluebird; - static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3) => R | PromiseLike): Bluebird; - static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, arg4: A4 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => R | PromiseLike): Bluebird; - static join(arg1: A1 | PromiseLike, arg2: A2 | PromiseLike, arg3: A3 | PromiseLike, arg4: A4 | PromiseLike, arg5: A5 | PromiseLike, handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => R | PromiseLike): Bluebird; + static join( + arg1: A1 | PromiseLike, + handler: (arg1: A1) => R | PromiseLike + ): Bluebird; + static join( + arg1: A1 | PromiseLike, + arg2: A2 | PromiseLike, + handler: (arg1: A1, arg2: A2) => R | PromiseLike + ): Bluebird; + static join( + arg1: A1 | PromiseLike, + arg2: A2 | PromiseLike, + arg3: A3 | PromiseLike, + handler: (arg1: A1, arg2: A2, arg3: A3) => R | PromiseLike + ): Bluebird; + static join( + arg1: A1 | PromiseLike, + arg2: A2 | PromiseLike, + arg3: A3 | PromiseLike, + arg4: A4 | PromiseLike, + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => R | PromiseLike + ): Bluebird; + static join( + arg1: A1 | PromiseLike, + arg2: A2 | PromiseLike, + arg3: A3 | PromiseLike, + arg4: A4 | PromiseLike, + arg5: A5 | PromiseLike, + handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => R | PromiseLike + ): Bluebird; // variadic array /** @deprecated use .all instead */ static join(...values: Array>): Bluebird; /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. * * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. * * *The original array is not modified.* */ - static map(values: PromiseLike | R>> | Iterable | R>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, options?: Bluebird.ConcurrencyOption): Bluebird; + static map( + values: PromiseLike | R>> | Iterable | R>, + mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike, + options?: Bluebird.ConcurrencyOption + ): Bluebird; /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. * * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. + * If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* */ - static reduce(values: PromiseLike | R>> | Iterable | R>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Bluebird; + static reduce( + values: PromiseLike | R>> | Iterable | R>, + reducer: (total: U, current: R, index: number, arrayLength: number) => U | PromiseLike, + initialValue?: U + ): Bluebird; /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. + * If any promise in the input array is rejected the returned promise is rejected as well. * * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. * * *The original array is not modified. */ - static filter(values: PromiseLike | R>> | Iterable | R>, filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, option?: Bluebird.ConcurrencyOption): Bluebird; + static filter( + values: PromiseLike | R>> | Iterable | R>, + filterer: (item: R, index: number, arrayLength: number) => boolean | PromiseLike, + option?: Bluebird.ConcurrencyOption + ): Bluebird; /** - * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. + * Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. * - * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * Resolves to the original array unmodified, this method is meant to be used for side effects. + * If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. */ - static each(values: PromiseLike | R>> | Iterable | R>, iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; + static each( + values: PromiseLike | R>> | Iterable | R>, + iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike + ): Bluebird; /** * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. * - * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. + * The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. + * This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. * * If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well. */ - static mapSeries(values: PromiseLike | R>> | Iterable | R>, iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike): Bluebird; + static mapSeries( + values: PromiseLike | R>> | Iterable | R>, + iterator: (item: R, index: number, arrayLength: number) => U | PromiseLike + ): Bluebird; /** * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. @@ -946,9 +1095,21 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * will be called when the promise returned by the callback passed to using has settled. The disposer is * necessary because there is no standard interface in node for disposing resources. */ - static using(disposer: Bluebird.Disposer, executor: (transaction: R) => PromiseLike): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => PromiseLike): Bluebird; - static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike): Bluebird; + static using( + disposer: Bluebird.Disposer, + executor: (transaction: R) => PromiseLike + ): Bluebird; + static using( + disposer: Bluebird.Disposer, + disposer2: Bluebird.Disposer, + executor: (transaction1: R1, transaction2: R2 + ) => PromiseLike): Bluebird; + static using( + disposer: Bluebird.Disposer, + disposer2: Bluebird.Disposer, + disposer3: Bluebird.Disposer, + executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike + ): Bluebird; /** * Configure long stack traces, warnings, monitoring and cancellation. @@ -1083,7 +1244,8 @@ declare namespace Bluebird { reject(reason: any): void; /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. + * The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. * * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. */ diff --git a/types/bluebird/tslint.json b/types/bluebird/tslint.json index 85497e648a..6abaaba4e3 100644 --- a/types/bluebird/tslint.json +++ b/types/bluebird/tslint.json @@ -1,8 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "max-line-length": [true, 490], - "no-redundant-undefined": false, + "max-line-length": [true, 280], "no-unnecessary-generics": false, "prefer-const": false } diff --git a/types/body-parser/index.d.ts b/types/body-parser/index.d.ts index 497f3c8dc7..b1485770a1 100644 --- a/types/body-parser/index.d.ts +++ b/types/body-parser/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/expressjs/body-parser // Definitions by: Santi Albo , Vilic Vane , Jonathan Häberle , Gevik Babakhani , Tomasz Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 /// diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index bb817d3074..dca8d5fad2 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bookshelfjs v0.9.3 +// Type definitions for bookshelfjs v0.9.4 // Project: http://bookshelfjs.org/ // Definitions by: Andrew Schurman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,7 +17,7 @@ interface Bookshelf extends Bookshelf.Events { Collection: typeof Bookshelf.Collection; plugin(name: string | string[] | Function, options?: any): Bookshelf; - transaction(callback: (transaction: knex.Transaction) => BlueBird): BlueBird; + transaction(callback: (transaction: knex.Transaction) => PromiseLike): BlueBird; } declare function Bookshelf(knex: knex): Bookshelf; diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index 8025a7ddab..76cd2d6b46 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -4,7 +4,7 @@ // AJP // Jinesh Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 export = Boom; @@ -55,7 +55,7 @@ declare namespace Boom { // Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload // [anyContent: string]: any; } - + /** * Decorates an error with the boom properties * @param error the error object to wrap. If error is already a boom object, it defaults to overriding the object with the new status code and message. diff --git a/types/bootstrap-fileinput/index.d.ts b/types/bootstrap-fileinput/index.d.ts index 8a7df2dbbc..61a53b12bb 100644 --- a/types/bootstrap-fileinput/index.d.ts +++ b/types/bootstrap-fileinput/index.d.ts @@ -6,10 +6,14 @@ /// -interface JQuery { - fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; -} +export = BootstrapFileInput; +export as namespace BootstrapFileInput; +declare global { + interface JQuery { + fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; + } +} declare module BootstrapFileInput { interface FileInputOptions { @@ -19,6 +23,11 @@ declare module BootstrapFileInput { The locale JS file for the language code must be defined as mentioned in the translations section: http://plugins.krajee.com/file-input#translations */ language?: string; + + /** + * Theming + */ + theme?: string; /** Whether to display the file caption. Defaults to true. diff --git a/types/botvs/index.d.ts b/types/botvs/index.d.ts index 2eabcb98da..04d8f76c97 100644 --- a/types/botvs/index.d.ts +++ b/types/botvs/index.d.ts @@ -282,21 +282,18 @@ declare global { /** * 返回交易所名称(string) * - * @return {string} */ GetName(): string; /** * 返回交易所自定义的标签(string) * - * @return {string} */ GetLabel(): string; /** * 返回交易所使用的美元的汇率, OKCoin期货返回官方提供的汇率, 该值不受SetRate影响 * - * @return {number} */ GetUSDCNY(): number; @@ -306,7 +303,6 @@ declare global { * 汇率接口调用雅虎提供的接口, 5分钟更新一次 * 所有函数自动经过汇率转换,如果为1指禁用汇率转换 * - * @return {number} */ GetRate(): number; @@ -317,7 +313,6 @@ declare global { * SetRate(), 如果不加参数,则恢复系统内置汇率 * SetRate(1), 就是禁用汇率转换 * - * @param {number} rate */ SetRate(rate?: number): void; @@ -326,43 +321,36 @@ declare global { * * exchange.SetPrecision(2, 3); // 设置价格小数位精度为2位, 品种下单量小数位精度为3位 * - * @param {number} PricePrecision - * @param {number} AmountPrecision */ SetPrecision(PricePrecision: number, AmountPrecision: number): void; /** * 返回交易所操作的货币名称(string), 传统期货CTP返回的固定为STOCK * - * @return {string} */ GetCurrency(): string; /** * 返回交易所操作的基础货币名称(string), BTC_CNY就返回CNY, ETH_BTC就返回BTC * - * @return {string} */ GetBaseCurrency(): string; /** * 返回一个Ticker结构 * - * @return {botvs.Ticker} */ GetTicker(): Ticker; /** * 返回一个Depth结构 * - * @return {botvs.Depth} */ GetDepth(): Depth; /** * 返回一个Trade数组, 按时间从低到高的顺序, 只支持数字货币(BTC/LTC) * - * @return {botvs.Trade[]} */ GetTrades(): Trade[]; @@ -373,15 +361,12 @@ declare global { * 支持: PERIOD_M1 指1分钟, PERIOD_M5 指5分钟, PERIOD_M15 指15分钟, * PERIOD_M30 指30分钟, PERIOD_H1 指1小时, PERIOD_D1 指一天 * - * @param {number} Period - * @return {botvs.Record[]} */ GetRecords(Period?: VPeriod): Record[]; /** * 返回一个Account结构, 如exchange.GetAccount(), 将返回主交易所账户信息 * - * @return {botvs.Account} */ GetAccount(): Account; @@ -392,59 +377,43 @@ declare global { * 支持现货(火币/BitVC/OKCoin/OKCoin国际/OKCoin期货/BTCChina/BitYes)市价单, 市价单价格指定为-1 * exchange.Buy(1000), 指买市价1000元的币, BTCChina例外exchange.Buy(0.3)指市价买0.3个币 * - * @param {number} Price - * @param {number} Amount - * @param {*[]} args - * @return {string} - 订单ID + * @return - 订单ID */ Buy(Price: number, Amount: number, ...args: any[]): string; /** * 跟Buy函数一样的调用方法和场景 {@see Exchange#Buy} * - * @param {number} Price - * @param {number} Amount - * @return {string} */ Sell(Price: number, Amount: number): string; /** * 获取所有未完成的订单, 返回一个Order数组结构 * - * @return {botvs.Order[]} */ GetOrders(): Order[]; /** * 根据订单号获取订单详情, 返回一个Order结构 * - * @param {string} orderId - * @return {botvs.Order} */ GetOrder(orderId: string): Order; /** * 根据订单号取消一个订单, 返回true或者false * - * @param {string} orderId - * @return {boolean} */ CancelOrder(orderId: string): boolean; /** * 不下单, 只记录交易信息, logType可为LOG_TYPE_BUY/LOG_TYPE_SELL/LOG_TYPE_CANCEL * - * @param {VLogType} logType - * @param {string} orderId - * @param {number} price - * @param {number} amount */ Log(logType: VLogType, orderId: string, price: number, amount: number): void; /** * 返回币最小交易数量 * - * @return {number} */ GetMinStock(): number; @@ -453,14 +422,12 @@ declare global { * * Bitstamp要求5美元(程序会根据汇率自动转换为人民币), 其它没有限制 * - * @return {number} */ GetMinPrice(): number; /** * 返回一个Fee结构 * - * @return {botvs.Fee} */ GetFee(): Fee; @@ -476,7 +443,6 @@ declare global { * Log(exchange.GetRawJSON());//在GetAccount成功后调用, 获取更详细的账户信息, 可以用JSON.parse解析 * 也支持GetTicker, GetDepth后的exchange.GetRawJSON(), 以及GetPosition与GetOrders,GetOrder这三个调用后的详细反馈数据 * - * @return {string} */ GetRawJSON(): string; @@ -501,9 +467,6 @@ declare global { * ret, ok = d.wait() // ok是一定返回True的, 除非策略被停止 * ret, ok = d.wait(100) // ok返回False, 如果等待超时, 或者wait了一个已经结束的实例 * - * @param {keyof botvs.Exchange} Method - * @param Args - * @return {botvs.AsyncJob} */ Go(Method: keyof Exchange, ...Args: any[]): AsyncJob; @@ -553,10 +516,6 @@ declare global { * exchange.IO("wait_instrument"); // 有任何品种更新行情信息时才返回, 可带第二个参数(毫秒数) * 指定超时, 超时返回空字符串, 正常返回触发事件的品种名称, 只支持实盘 * - * @param {"api" | "usd" | "cny" | "currency" | string} Api - * @param {string} ApiName - * @param {string} Args - * @return {T} */ IO(Api: 'api' | 'usd' | 'cny' | 'currency' | string, ApiName?: string, Args?: string): T; @@ -565,7 +524,6 @@ declare global { * * 返回一个Position数组, (BitVC和OKCoin)可以传入一个参数, 指定要获取的合约类型 * - * @return {botvs.Position[]} */ GetPosition(): Position[]; @@ -576,7 +534,6 @@ declare global { * 796支持5,10,20,50三个选项, BitVC的LTC不支持20倍杠杆, OKCoin支持10倍和20倍 * 如: exchange.SetMarginLevel(5) * - * @param {number} MarginLevel */ SetMarginLevel(MarginLevel: number): void; @@ -617,8 +574,6 @@ declare global { * exchange.SetDirection("sell"); * exchange.Sell(1000, 1); * - * @param {"buy" | "closebuy" | "sell" | "closesell" | "closebuy_today" | "closesell_today"} Direction - * @constructor */ SetDirection(Direction: 'buy' | 'closebuy' | 'sell' | 'closesell' | 'closebuy_today' | 'closesell_today'): void; @@ -634,7 +589,6 @@ declare global { * 在合约后加"@A"或"@B", 如: "day@A" 为日合约A子账户 BitVC有week和quarter和next_week三个可选参数, OKCoin期货有this_week, * next_week, quarter三个参数 exchange.SetContractType("week"); * - * @param {string} ContractType */ SetContractType(ContractType: string): void; } @@ -646,11 +600,6 @@ declare global { * * MACD(数据, 快周期, 慢周期, 信号周期), 默认参数为(12, 26, 9), 返回二维数组, 分别是[DIF, DEA, MACD] * - * @param {botvs.Record[]} Records - * @param {number} LongPeriod - * @param {number} ShortPeriod - * @param {number} SignalPeriod - * @return {[number[] , number[] , number[]]} */ function MACD( Records: botvs.Record[], @@ -664,11 +613,6 @@ declare global { * * KDJ(数据, 周期1, 周期2, 周期3), 默认参数为(9, 3, 3), 返回二维数组, 分别是[K, D, J] * - * @param {botvs.Record[]} Records - * @param {number} FirstPeriod - * @param {number} SecondPeriod - * @param {number} ThirdPeriod - * @return {[number[] , number[] , number[]]} */ function KDJ( Records: botvs.Record[], @@ -682,9 +626,6 @@ declare global { * * RSI(数据, 周期), 默认参数为14, 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function RSI(Records: botvs.Record[], Period?: number): number[]; @@ -693,9 +634,6 @@ declare global { * * ATR(数据, 周期), 默认参数为14, 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function ATR(Records: botvs.Record[], Period?: number): number[]; @@ -704,8 +642,6 @@ declare global { * * OBV(数据), 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @return {[number[] , number[]]} */ function OBV(Records: botvs.Record[]): [number[], number[]]; @@ -714,9 +650,6 @@ declare global { * * MA(数据, 周期), 默认参数为9, 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function MA(Records: botvs.Record[], Period?: number): number[]; @@ -724,9 +657,6 @@ declare global { * 指数平均数指标 * EMA(数据, 周期), 默认参数为9, 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function EMA(Records: botvs.Record[], Period?: number): number[]; @@ -735,11 +665,6 @@ declare global { * * Alligator(数据, 下颚周期,牙齿周期,上唇周期), 鳄鱼线指标, 默认参数为(13,8,5) 返回一个二维数组[下颚,牙齿,上唇] * - * @param {botvs.Record[]} Records - * @param {number} JawPeriod - * @param {number} TeethPeriod - * @param {number} LibsPeriod - * @return {[number[] , number[] , number[]]} */ function Alligator( Records: botvs.Record[], @@ -753,9 +678,6 @@ declare global { * * CMF(数据, 周期), 默认周期参数为20, 返回一个一维数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @return {number[]} */ function CMF(Records: botvs.Record[], Period?: number): number[]; @@ -765,11 +687,6 @@ declare global { * Highest(数据, 周期, 属性), 返回最近周期内的最大值(不包含当前Bar), * 如TA.Highest(records, 30, 'High'), 如果周期为0指所有, 如属性不指定则视数据为普通数组 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @param {keyof botvs.Record} Property - * @return {number} - * @constructor */ function Highest(Records: botvs.Record[], Period?: number, Property?: keyof botvs.Record): number; @@ -778,10 +695,6 @@ declare global { * * Lowest(数据, 周期, 属性), 同上, 求最小值 * - * @param {botvs.Record[]} Records - * @param {number} Period - * @param {keyof botvs.Record} Property - * @return {number} */ function Lowest(Records: botvs.Record[], Period?: number, Property?: keyof botvs.Record): number; } @@ -792,8 +705,6 @@ declare global { * * Log(talib.help('MACD')); // 在回测环境下调用 * - * @param {string} Func - * @return {string} */ function help(Func: string): string; @@ -802,8 +713,6 @@ declare global { * * ACOS(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ACOS(Records: botvs.Record[] | number[]): number[]; @@ -812,8 +721,6 @@ declare global { * * AD(Records[High,Low,Close,Volume]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function AD(Records: botvs.Record[]): number[]; /** @@ -821,11 +728,6 @@ declare global { * * AD(Records[High,Low,Close,Volume]) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @return {number[]} */ function AD(High: number[], Low: number[], Close: number[], Volume: number[]): number[]; @@ -834,10 +736,6 @@ declare global { * * ADOSC(Records[High,Low,Close,Volume],Fast Period = 3,Slow Period = 10) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=3} FastPeriod - * @param {number=10} SlowPeriod - * @return {number[]} */ function ADOSC(Records: botvs.Record[], FastPeriod: number, SlowPeriod: number): number[]; /** @@ -845,13 +743,6 @@ declare global { * * ADOSC(Records[High,Low,Close,Volume],Fast Period = 3,Slow Period = 10) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @param {number=3} FastPeriod - * @param {number=10} SlowPeriod - * @return {number[]} */ function ADOSC( High: number[], @@ -867,9 +758,6 @@ declare global { * * ADX(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ADX(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -877,11 +765,6 @@ declare global { * * ADX(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ADX(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -890,9 +773,6 @@ declare global { * * ADXR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ADXR(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -900,11 +780,6 @@ declare global { * * ADXR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ADXR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -913,11 +788,6 @@ declare global { * * APO(Records[Close],Fast Period = 12,Slow Period = 26,MA Type = 0) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=0} MAType - * @return {number[]} */ function APO( Records: botvs.Record[] | number[], @@ -931,9 +801,6 @@ declare global { * * AROON(Records[High,Low],Time Period = 14) = [Array(outAroonDown),Array(outAroonUp)] * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {[number[], number[]]} */ function AROON(Records: botvs.Record[], TimePeriod: number): [number[], number[]]; /** @@ -941,10 +808,6 @@ declare global { * * AROON(Records[High,Low],Time Period = 14) = [Array(outAroonDown),Array(outAroonUp)] * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {[number[], number[]]} */ function AROON(High: number[], Low: number[], TimePeriod: number): [number[], number[]]; @@ -953,9 +816,6 @@ declare global { * * AROONOSC(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function AROONOSC(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -963,10 +823,6 @@ declare global { * * AROONOSC(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function AROONOSC(High: number[], Low: number[], TimePeriod: number): number[]; @@ -975,8 +831,6 @@ declare global { * * ASIN(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ASIN(Records: botvs.Record[] | number[]): number[]; @@ -985,8 +839,6 @@ declare global { * * ATAN(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function ATAN(Records: botvs.Record[] | number[]): number[]; @@ -995,9 +847,6 @@ declare global { * * ATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function ATR(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -1005,11 +854,6 @@ declare global { * * ATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function ATR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -1018,8 +862,6 @@ declare global { * * AVGPRICE(Records[Open,High,Low,Close]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function AVGPRICE(Records: botvs.Record[]): number[]; /** @@ -1027,11 +869,6 @@ declare global { * * AVGPRICE(Records[Open,High,Low,Close]) = Array(outReal) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function AVGPRICE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1041,12 +878,6 @@ declare global { * BBANDS(Records[Close],Time Period = 5,Deviations up = 2,Deviations down = 2,MA Type = 0) = * [Array(outRealUpperBand),Array(outRealMiddleBand),Array(outRealLowerBand)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=2} Deviationsup - * @param {number=2} Deviationsdown - * @param {number=0} MAType - * @return {[number[], number[], number[]]} */ function BBANDS( Records: botvs.Record[] | number[], @@ -1061,8 +892,6 @@ declare global { * * BOP(Records[Open,High,Low,Close]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function BOP(Records: botvs.Record[]): number[]; /** @@ -1070,11 +899,6 @@ declare global { * * BOP(Records[Open,High,Low,Close]) = Array(outReal) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function BOP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1083,9 +907,6 @@ declare global { * * CCI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function CCI(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -1093,11 +914,6 @@ declare global { * * CCI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function CCI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -1106,8 +922,6 @@ declare global { * * CDL2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL2CROWS(Records: botvs.Record[]): number[]; /** @@ -1115,11 +929,6 @@ declare global { * * CDL2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL2CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1128,8 +937,6 @@ declare global { * * CDL3BLACKCROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3BLACKCROWS(Records: botvs.Record[]): number[]; /** @@ -1137,11 +944,6 @@ declare global { * * CDL3BLACKCROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3BLACKCROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1150,8 +952,6 @@ declare global { * * CDL3INSIDE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3INSIDE(Records: botvs.Record[]): number[]; /** @@ -1159,11 +959,6 @@ declare global { * * CDL3INSIDE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3INSIDE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1172,8 +967,6 @@ declare global { * * CDL3LINESTRIKE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3LINESTRIKE(Records: botvs.Record[]): number[]; /** @@ -1181,11 +974,6 @@ declare global { * * CDL3LINESTRIKE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3LINESTRIKE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1194,8 +982,6 @@ declare global { * * CDL3OUTSIDE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3OUTSIDE(Records: botvs.Record[]): number[]; /** @@ -1203,11 +989,6 @@ declare global { * * CDL3OUTSIDE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3OUTSIDE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1216,8 +997,6 @@ declare global { * * CDL3STARSINSOUTH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3STARSINSOUTH(Records: botvs.Record[]): number[]; /** @@ -1225,11 +1004,6 @@ declare global { * * CDL3STARSINSOUTH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3STARSINSOUTH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1238,8 +1012,6 @@ declare global { * * CDL3WHITESOLDIERS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDL3WHITESOLDIERS(Records: botvs.Record[]): number[]; /** @@ -1247,11 +1019,6 @@ declare global { * * CDL3WHITESOLDIERS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDL3WHITESOLDIERS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1260,9 +1027,6 @@ declare global { * * CDLABANDONEDBABY(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLABANDONEDBABY(Records: botvs.Record[], Penetration: number): number[]; /** @@ -1270,12 +1034,6 @@ declare global { * * CDLABANDONEDBABY(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLABANDONEDBABY( Open: number[], @@ -1290,8 +1048,6 @@ declare global { * * CDLADVANCEBLOCK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLADVANCEBLOCK(Records: botvs.Record[]): number[]; /** @@ -1299,11 +1055,6 @@ declare global { * * CDLADVANCEBLOCK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLADVANCEBLOCK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1312,8 +1063,6 @@ declare global { * * CDLBELTHOLD(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLBELTHOLD(Records: botvs.Record[]): number[]; /** @@ -1321,11 +1070,6 @@ declare global { * * CDLBELTHOLD(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLBELTHOLD(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1334,8 +1078,6 @@ declare global { * * CDLBREAKAWAY(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLBREAKAWAY(Records: botvs.Record[]): number[]; /** @@ -1343,11 +1085,6 @@ declare global { * * CDLBREAKAWAY(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLBREAKAWAY(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1356,8 +1093,6 @@ declare global { * * CDLCLOSINGMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCLOSINGMARUBOZU(Records: botvs.Record[]): number[]; /** @@ -1365,11 +1100,6 @@ declare global { * * CDLCLOSINGMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCLOSINGMARUBOZU(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1378,8 +1108,6 @@ declare global { * * CDLCONCEALBABYSWALL(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCONCEALBABYSWALL(Records: botvs.Record[]): number[]; /** @@ -1387,11 +1115,6 @@ declare global { * * CDLCONCEALBABYSWALL(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCONCEALBABYSWALL(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1400,8 +1123,6 @@ declare global { * * CDLCOUNTERATTACK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLCOUNTERATTACK(Records: botvs.Record[]): number[]; /** @@ -1409,11 +1130,6 @@ declare global { * * CDLCOUNTERATTACK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLCOUNTERATTACK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1422,9 +1138,6 @@ declare global { * * CDLDARKCLOUDCOVER(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLDARKCLOUDCOVER(Records: botvs.Record[], Penetration: number): number[]; /** @@ -1432,12 +1145,6 @@ declare global { * * CDLDARKCLOUDCOVER(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLDARKCLOUDCOVER( Open: number[], @@ -1452,8 +1159,6 @@ declare global { * * CDLDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDOJI(Records: botvs.Record[]): number[]; /** @@ -1461,11 +1166,6 @@ declare global { * * CDLDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1474,8 +1174,6 @@ declare global { * * CDLDOJISTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDOJISTAR(Records: botvs.Record[]): number[]; /** @@ -1483,11 +1181,6 @@ declare global { * * CDLDOJISTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDOJISTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1496,8 +1189,6 @@ declare global { * * CDLDRAGONFLYDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLDRAGONFLYDOJI(Records: botvs.Record[]): number[]; /** @@ -1505,11 +1196,6 @@ declare global { * * CDLDRAGONFLYDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLDRAGONFLYDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1518,8 +1204,6 @@ declare global { * * CDLENGULFING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLENGULFING(Records: botvs.Record[]): number[]; /** @@ -1527,11 +1211,6 @@ declare global { * * CDLENGULFING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLENGULFING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1540,9 +1219,6 @@ declare global { * * CDLEVENINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGDOJISTAR(Records: botvs.Record[], Penetration: number): number[]; /** @@ -1550,12 +1226,6 @@ declare global { * * CDLEVENINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGDOJISTAR( Open: number[], @@ -1570,9 +1240,6 @@ declare global { * * CDLEVENINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGSTAR(Records: botvs.Record[], Penetration: number): number[]; /** @@ -1580,12 +1247,6 @@ declare global { * * CDLEVENINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLEVENINGSTAR( Open: number[], @@ -1600,8 +1261,6 @@ declare global { * * CDLGAPSIDESIDEWHITE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLGAPSIDESIDEWHITE(Records: botvs.Record[]): number[]; /** @@ -1609,11 +1268,6 @@ declare global { * * CDLGAPSIDESIDEWHITE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLGAPSIDESIDEWHITE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1622,8 +1276,6 @@ declare global { * * CDLGRAVESTONEDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLGRAVESTONEDOJI(Records: botvs.Record[]): number[]; /** @@ -1631,11 +1283,6 @@ declare global { * * CDLGRAVESTONEDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLGRAVESTONEDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1644,8 +1291,6 @@ declare global { * * CDLHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHAMMER(Records: botvs.Record[]): number[]; /** @@ -1653,11 +1298,6 @@ declare global { * * CDLHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHAMMER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1666,8 +1306,6 @@ declare global { * * CDLHANGINGMAN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHANGINGMAN(Records: botvs.Record[]): number[]; /** @@ -1675,11 +1313,6 @@ declare global { * * CDLHANGINGMAN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHANGINGMAN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1688,8 +1321,6 @@ declare global { * * CDLHARAMI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHARAMI(Records: botvs.Record[]): number[]; /** @@ -1697,11 +1328,6 @@ declare global { * * CDLHARAMI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHARAMI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1710,8 +1336,6 @@ declare global { * * CDLHARAMICROSS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHARAMICROSS(Records: botvs.Record[]): number[]; /** @@ -1719,11 +1343,6 @@ declare global { * * CDLHARAMICROSS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHARAMICROSS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1732,8 +1351,6 @@ declare global { * * CDLHIGHWAVE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIGHWAVE(Records: botvs.Record[]): number[]; /** @@ -1741,11 +1358,6 @@ declare global { * * CDLHIGHWAVE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIGHWAVE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1754,8 +1366,6 @@ declare global { * * CDLHIKKAKE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIKKAKE(Records: botvs.Record[]): number[]; /** @@ -1763,11 +1373,6 @@ declare global { * * CDLHIKKAKE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIKKAKE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1776,8 +1381,6 @@ declare global { * * CDLHIKKAKEMOD(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHIKKAKEMOD(Records: botvs.Record[]): number[]; /** @@ -1785,11 +1388,6 @@ declare global { * * CDLHIKKAKEMOD(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHIKKAKEMOD(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1798,8 +1396,6 @@ declare global { * * CDLHOMINGPIGEON(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLHOMINGPIGEON(Records: botvs.Record[]): number[]; /** @@ -1807,11 +1403,6 @@ declare global { * * CDLHOMINGPIGEON(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLHOMINGPIGEON(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1820,8 +1411,6 @@ declare global { * * CDLIDENTICAL3CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLIDENTICAL3CROWS(Records: botvs.Record[]): number[]; /** @@ -1829,11 +1418,6 @@ declare global { * * CDLIDENTICAL3CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLIDENTICAL3CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1842,8 +1426,6 @@ declare global { * * CDLINNECK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLINNECK(Records: botvs.Record[]): number[]; /** @@ -1851,11 +1433,6 @@ declare global { * * CDLINNECK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLINNECK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1864,8 +1441,6 @@ declare global { * * CDLINVERTEDHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLINVERTEDHAMMER(Records: botvs.Record[]): number[]; /** @@ -1873,11 +1448,6 @@ declare global { * * CDLINVERTEDHAMMER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLINVERTEDHAMMER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1886,8 +1456,6 @@ declare global { * * CDLKICKING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLKICKING(Records: botvs.Record[]): number[]; /** @@ -1895,11 +1463,6 @@ declare global { * * CDLKICKING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLKICKING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1908,8 +1471,6 @@ declare global { * * CDLKICKINGBYLENGTH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLKICKINGBYLENGTH(Records: botvs.Record[]): number[]; /** @@ -1917,11 +1478,6 @@ declare global { * * CDLKICKINGBYLENGTH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLKICKINGBYLENGTH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1930,8 +1486,6 @@ declare global { * * CDLLADDERBOTTOM(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLADDERBOTTOM(Records: botvs.Record[]): number[]; /** @@ -1939,11 +1493,6 @@ declare global { * * CDLLADDERBOTTOM(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLADDERBOTTOM(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1952,8 +1501,6 @@ declare global { * * CDLLONGLEGGEDDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLONGLEGGEDDOJI(Records: botvs.Record[]): number[]; /** @@ -1961,11 +1508,6 @@ declare global { * * CDLLONGLEGGEDDOJI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLONGLEGGEDDOJI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1974,8 +1516,6 @@ declare global { * * CDLLONGLINE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLLONGLINE(Records: botvs.Record[]): number[]; /** @@ -1983,11 +1523,6 @@ declare global { * * CDLLONGLINE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLLONGLINE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -1996,8 +1531,6 @@ declare global { * * CDLMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLMARUBOZU(Records: botvs.Record[]): number[]; /** @@ -2005,11 +1538,6 @@ declare global { * * CDLMARUBOZU(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLMARUBOZU(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2018,8 +1546,6 @@ declare global { * * CDLMATCHINGLOW(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLMATCHINGLOW(Records: botvs.Record[]): number[]; /** @@ -2027,11 +1553,6 @@ declare global { * * CDLMATCHINGLOW(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLMATCHINGLOW(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2040,9 +1561,6 @@ declare global { * * CDLMATHOLD(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLMATHOLD(Records: botvs.Record[], Penetration: number): number[]; /** @@ -2050,12 +1568,6 @@ declare global { * * CDLMATHOLD(Records[Open,High,Low,Close],Penetration = 0.5) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.5} Penetration - * @return {number[]} */ function CDLMATHOLD( Open: number[], @@ -2070,9 +1582,6 @@ declare global { * * CDLMORNINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGDOJISTAR(Records: botvs.Record[], Penetration: number): number[]; /** @@ -2080,12 +1589,6 @@ declare global { * * CDLMORNINGDOJISTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGDOJISTAR( Open: number[], @@ -2100,9 +1603,6 @@ declare global { * * CDLMORNINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGSTAR(Records: botvs.Record[], Penetration: number): number[]; /** @@ -2110,12 +1610,6 @@ declare global { * * CDLMORNINGSTAR(Records[Open,High,Low,Close],Penetration = 0.3) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=0.3} Penetration - * @return {number[]} */ function CDLMORNINGSTAR( Open: number[], @@ -2130,8 +1624,6 @@ declare global { * * CDLONNECK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLONNECK(Records: botvs.Record[]): number[]; /** @@ -2139,11 +1631,6 @@ declare global { * * CDLONNECK(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLONNECK(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2152,8 +1639,6 @@ declare global { * * CDLPIERCING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLPIERCING(Records: botvs.Record[]): number[]; /** @@ -2161,11 +1646,6 @@ declare global { * * CDLPIERCING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLPIERCING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2174,8 +1654,6 @@ declare global { * * CDLRICKSHAWMAN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLRICKSHAWMAN(Records: botvs.Record[]): number[]; /** @@ -2183,11 +1661,6 @@ declare global { * * CDLRICKSHAWMAN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLRICKSHAWMAN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2196,8 +1669,6 @@ declare global { * * CDLRISEFALL3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLRISEFALL3METHODS(Records: botvs.Record[]): number[]; /** @@ -2205,11 +1676,6 @@ declare global { * * CDLRISEFALL3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLRISEFALL3METHODS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2218,8 +1684,6 @@ declare global { * * CDLSEPARATINGLINES(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSEPARATINGLINES(Records: botvs.Record[]): number[]; /** @@ -2227,11 +1691,6 @@ declare global { * * CDLSEPARATINGLINES(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSEPARATINGLINES(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2240,8 +1699,6 @@ declare global { * * CDLSHOOTINGSTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSHOOTINGSTAR(Records: botvs.Record[]): number[]; /** @@ -2249,11 +1706,6 @@ declare global { * * CDLSHOOTINGSTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSHOOTINGSTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2262,8 +1714,6 @@ declare global { * * CDLSHORTLINE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSHORTLINE(Records: botvs.Record[]): number[]; /** @@ -2271,11 +1721,6 @@ declare global { * * CDLSHORTLINE(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSHORTLINE(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2284,8 +1729,6 @@ declare global { * * CDLSPINNINGTOP(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSPINNINGTOP(Records: botvs.Record[]): number[]; /** @@ -2293,11 +1736,6 @@ declare global { * * CDLSPINNINGTOP(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSPINNINGTOP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2306,8 +1744,6 @@ declare global { * * CDLSTALLEDPATTERN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSTALLEDPATTERN(Records: botvs.Record[]): number[]; /** @@ -2315,11 +1751,6 @@ declare global { * * CDLSTALLEDPATTERN(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSTALLEDPATTERN(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2328,8 +1759,6 @@ declare global { * * CDLSTICKSANDWICH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLSTICKSANDWICH(Records: botvs.Record[]): number[]; /** @@ -2337,11 +1766,6 @@ declare global { * * CDLSTICKSANDWICH(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLSTICKSANDWICH(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2350,8 +1774,6 @@ declare global { * * CDLTAKURI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTAKURI(Records: botvs.Record[]): number[]; /** @@ -2359,11 +1781,6 @@ declare global { * * CDLTAKURI(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTAKURI(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2372,8 +1789,6 @@ declare global { * * CDLTASUKIGAP(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTASUKIGAP(Records: botvs.Record[]): number[]; /** @@ -2381,11 +1796,6 @@ declare global { * * CDLTASUKIGAP(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTASUKIGAP(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2394,8 +1804,6 @@ declare global { * * CDLTHRUSTING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTHRUSTING(Records: botvs.Record[]): number[]; /** @@ -2403,11 +1811,6 @@ declare global { * * CDLTHRUSTING(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTHRUSTING(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2416,8 +1819,6 @@ declare global { * * CDLTRISTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLTRISTAR(Records: botvs.Record[]): number[]; /** @@ -2425,11 +1826,6 @@ declare global { * * CDLTRISTAR(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLTRISTAR(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2438,8 +1834,6 @@ declare global { * * CDLUNIQUE3RIVER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLUNIQUE3RIVER(Records: botvs.Record[]): number[]; /** @@ -2447,11 +1841,6 @@ declare global { * * CDLUNIQUE3RIVER(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLUNIQUE3RIVER(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2460,8 +1849,6 @@ declare global { * * CDLUPSIDEGAP2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLUPSIDEGAP2CROWS(Records: botvs.Record[]): number[]; /** @@ -2469,11 +1856,6 @@ declare global { * * CDLUPSIDEGAP2CROWS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLUPSIDEGAP2CROWS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2482,8 +1864,6 @@ declare global { * * CDLXSIDEGAP3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function CDLXSIDEGAP3METHODS(Records: botvs.Record[]): number[]; /** @@ -2491,11 +1871,6 @@ declare global { * * CDLXSIDEGAP3METHODS(Records[Open,High,Low,Close]) = Array(outInteger) * - * @param {number[]} Open - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function CDLXSIDEGAP3METHODS(Open: number[], High: number[], Low: number[], Close: number[]): number[]; @@ -2504,8 +1879,6 @@ declare global { * * CEIL(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function CEIL(Records: botvs.Record[] | number[]): number[]; @@ -2514,9 +1887,6 @@ declare global { * * CMO(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function CMO(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2525,8 +1895,6 @@ declare global { * * COS(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function COS(Records: botvs.Record[] | number[]): number[]; @@ -2535,8 +1903,6 @@ declare global { * * COSH(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function COSH(Records: botvs.Record[] | number[]): number[]; @@ -2545,9 +1911,6 @@ declare global { * * DEMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function DEMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2556,9 +1919,6 @@ declare global { * * DX(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function DX(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -2566,11 +1926,6 @@ declare global { * * DX(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function DX(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -2579,9 +1934,6 @@ declare global { * * EMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function EMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2590,8 +1942,6 @@ declare global { * * EXP(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function EXP(Records: botvs.Record[] | number[]): number[]; @@ -2600,8 +1950,6 @@ declare global { * * FLOOR(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function FLOOR(Records: botvs.Record[] | number[]): number[]; @@ -2610,8 +1958,6 @@ declare global { * * HT_DCPERIOD(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_DCPERIOD(Records: botvs.Record[] | number[]): number[]; @@ -2620,8 +1966,6 @@ declare global { * * HT_DCPHASE(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_DCPHASE(Records: botvs.Record[] | number[]): number[]; @@ -2630,8 +1974,6 @@ declare global { * * HT_PHASOR(Records[Close]) = [Array(outInPhase),Array(outQuadrature)] * - * @param {botvs.Record[]|number[]} Records - * @return {[number[], number[]]} */ function HT_PHASOR(Records: botvs.Record[] | number[]): [number[], number[]]; @@ -2640,8 +1982,6 @@ declare global { * * HT_SINE(Records[Close]) = [Array(outSine),Array(outLeadSine)] * - * @param {botvs.Record[]|number[]} Records - * @return {[number[], number[]]} */ function HT_SINE(Records: botvs.Record[] | number[]): [number[], number[]]; @@ -2650,8 +1990,6 @@ declare global { * * HT_TRENDLINE(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_TRENDLINE(Records: botvs.Record[] | number[]): number[]; @@ -2660,8 +1998,6 @@ declare global { * * HT_TRENDMODE(Records[Close]) = Array(outInteger) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function HT_TRENDMODE(Records: botvs.Record[] | number[]): number[]; @@ -2670,9 +2006,6 @@ declare global { * * KAMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function KAMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2681,9 +2014,6 @@ declare global { * * LINEARREG(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2692,9 +2022,6 @@ declare global { * * LINEARREG_ANGLE(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_ANGLE(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2703,9 +2030,6 @@ declare global { * * LINEARREG_INTERCEPT(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_INTERCEPT(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2714,9 +2038,6 @@ declare global { * * LINEARREG_SLOPE(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function LINEARREG_SLOPE(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2725,8 +2046,6 @@ declare global { * * LN(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function LN(Records: botvs.Record[] | number[]): number[]; @@ -2735,8 +2054,6 @@ declare global { * * LOG10(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function LOG10(Records: botvs.Record[] | number[]): number[]; @@ -2745,10 +2062,6 @@ declare global { * * MA(Records[Close],Time Period = 30,MA Type = 0) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @param {number=0} MAType - * @return {number[]} */ function MA(Records: botvs.Record[] | number[], TimePeriod: number, MAType: number): number[]; @@ -2758,11 +2071,6 @@ declare global { * MACD(Records[Close],Fast Period = 12,Slow Period = 26,Signal Period = 9) = * [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=9} SignalPeriod - * @return {[number[], number[], number[]]} */ function MACD( Records: botvs.Record[] | number[], @@ -2778,14 +2086,6 @@ declare global { * = * 0) = [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=0} FastMA - * @param {number=26} SlowPeriod - * @param {number=0} SlowMA - * @param {number=9} SignalPeriod - * @param {number=0} SignalMA - * @return {[number[], number[], number[]]} */ function MACDEXT( Records: botvs.Record[] | number[], @@ -2802,9 +2102,6 @@ declare global { * * MACDFIX(Records[Close],Signal Period = 9) = [Array(outMACD),Array(outMACDSignal),Array(outMACDHist)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=9} SignalPeriod - * @return {[number[], number[], number[]]} */ function MACDFIX(Records: botvs.Record[] | number[], SignalPeriod: number): [number[], number[], number[]]; @@ -2813,10 +2110,6 @@ declare global { * * MAMA(Records[Close],Fast Limit = 0.5,Slow Limit = 0.05) = [Array(outMAMA),Array(outFAMA)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=0.5} FastLimit - * @param {number=0.05} SlowLimit - * @return {[number[], number[]]} */ function MAMA(Records: botvs.Record[] | number[], FastLimit: number, SlowLimit: number): [number[], number[]]; @@ -2825,9 +2118,6 @@ declare global { * * MAX(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MAX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2836,9 +2126,6 @@ declare global { * * MAXINDEX(Records[Close],Time Period = 30) = Array(outInteger) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MAXINDEX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2847,8 +2134,6 @@ declare global { * * MEDPRICE(Records[High,Low]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function MEDPRICE(Records: botvs.Record[]): number[]; /** @@ -2856,9 +2141,6 @@ declare global { * * MEDPRICE(Records[High,Low]) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @return {number[]} */ function MEDPRICE(High: number[], Low: number[]): number[]; @@ -2867,9 +2149,6 @@ declare global { * * MFI(Records[High,Low,Close,Volume],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MFI(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -2877,12 +2156,6 @@ declare global { * * MFI(Records[High,Low,Close,Volume],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number[]} Volume - * @param {number=14} TimePeriod - * @return {number[]} */ function MFI(High: number[], Low: number[], Close: number[], Volume: number[], TimePeriod: number): number[]; @@ -2891,9 +2164,6 @@ declare global { * * MIDPOINT(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPOINT(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2902,9 +2172,6 @@ declare global { * * MIDPRICE(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPRICE(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -2912,10 +2179,6 @@ declare global { * * MIDPRICE(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function MIDPRICE(High: number[], Low: number[], TimePeriod: number): number[]; @@ -2924,9 +2187,6 @@ declare global { * * MIN(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MIN(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2935,9 +2195,6 @@ declare global { * * MININDEX(Records[Close],Time Period = 30) = Array(outInteger) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function MININDEX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -2946,9 +2203,6 @@ declare global { * * MINMAX(Records[Close],Time Period = 30) = [Array(outMin),Array(outMax)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {[number[], number[]]} */ function MINMAX(Records: botvs.Record[] | number[], TimePeriod: number): [number[], number[]]; @@ -2957,9 +2211,6 @@ declare global { * * MINMAXINDEX(Records[Close],Time Period = 30) = [Array(outMinIdx),Array(outMaxIdx)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {[number[], number[]]} */ function MINMAXINDEX(Records: botvs.Record[] | number[], TimePeriod: number): [number[], number[]]; @@ -2968,9 +2219,6 @@ declare global { * * MINUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DI(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -2978,11 +2226,6 @@ declare global { * * MINUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -2991,9 +2234,6 @@ declare global { * * MINUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DM(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -3001,10 +2241,6 @@ declare global { * * MINUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function MINUS_DM(High: number[], Low: number[], TimePeriod: number): number[]; @@ -3013,9 +2249,6 @@ declare global { * * MOM(Records[Close],Time Period = 10) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function MOM(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3024,9 +2257,6 @@ declare global { * * NATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function NATR(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -3034,11 +2264,6 @@ declare global { * * NATR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function NATR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3047,8 +2272,6 @@ declare global { * * OBV(Records[Close],Records[Volume]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function OBV(Records: botvs.Record[]): number[]; @@ -3057,9 +2280,6 @@ declare global { * * OBV(Records[Close],Records[Volume]) = Array(outReal) * - * @param {number[]} Close - * @param {number[]} Volume - * @return {number[]} */ function OBV(Close: number[], Volume: number[]): number[]; @@ -3068,9 +2288,6 @@ declare global { * * PLUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DI(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -3078,11 +2295,6 @@ declare global { * * PLUS_DI(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DI(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3091,9 +2303,6 @@ declare global { * * PLUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DM(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -3101,10 +2310,6 @@ declare global { * * PLUS_DM(Records[High,Low],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=14} TimePeriod - * @return {number[]} */ function PLUS_DM(High: number[], Low: number[], TimePeriod: number): number[]; @@ -3113,11 +2318,6 @@ declare global { * * PPO(Records[Close],Fast Period = 12,Slow Period = 26,MA Type = 0) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=12} FastPeriod - * @param {number=26} SlowPeriod - * @param {number=0} MAType - * @return {number[]} */ function PPO( Records: botvs.Record[] | number[], @@ -3131,9 +2331,6 @@ declare global { * * ROC(Records[Close],Time Period = 10) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROC(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3142,9 +2339,6 @@ declare global { * * ROCP(Records[Close],Time Period = 10) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCP(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3153,9 +2347,6 @@ declare global { * * ROCR(Records[Close],Time Period = 10) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCR(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3164,9 +2355,6 @@ declare global { * * ROCR100(Records[Close],Time Period = 10) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=10} TimePeriod - * @return {number[]} */ function ROCR100(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3175,9 +2363,6 @@ declare global { * * RSI(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function RSI(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3186,10 +2371,6 @@ declare global { * * SAR(Records[High,Low],Acceleration Factor = 0.02,AF Maximum = 0.2) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=0.02} AccelerationFactor - * @param {number=0.2} AFMaximum - * @return {number[]} */ function SAR(Records: botvs.Record[], AccelerationFactor: number, AFMaximum: number): number[]; /** @@ -3197,11 +2378,6 @@ declare global { * * SAR(Records[High,Low],Acceleration Factor = 0.02,AF Maximum = 0.2) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=0.02} AccelerationFactor - * @param {number=0.2} AFMaximum - * @return {number[]} */ function SAR(High: number[], Low: number[], AccelerationFactor: number, AFMaximum: number): number[]; @@ -3212,16 +2388,6 @@ declare global { * Long = * 0.2,AF Init Short = 0.02,AF Short = 0.02,AF Max Short = 0.2) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=0} StartValue - * @param {number=0} OffsetonReverse - * @param {number=0.02} AFInitLong - * @param {number=0.02} AFLong - * @param {number=0.2} AFMaxLong - * @param {number=0.02} AFInitShort - * @param {number=0.02} AFShort - * @param {number=0.2} AFMaxShort - * @return {number[]} */ function SAREXT( Records: botvs.Record[], @@ -3241,17 +2407,6 @@ declare global { * Long = * 0.2,AF Init Short = 0.02,AF Short = 0.02,AF Max Short = 0.2) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number=0} StartValue - * @param {number=0} OffsetonReverse - * @param {number=0.02} AFInitLong - * @param {number=0.02} AFLong - * @param {number=0.2} AFMaxLong - * @param {number=0.02} AFInitShort - * @param {number=0.02} AFShort - * @param {number=0.2} AFMaxShort - * @return {number[]} */ function SAREXT( High: number[], @@ -3271,8 +2426,6 @@ declare global { * * SIN(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SIN(Records: botvs.Record[] | number[]): number[]; @@ -3281,8 +2434,6 @@ declare global { * * SINH(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SINH(Records: botvs.Record[] | number[]): number[]; @@ -3291,9 +2442,6 @@ declare global { * * SMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function SMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3302,8 +2450,6 @@ declare global { * * SQRT(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function SQRT(Records: botvs.Record[] | number[]): number[]; @@ -3312,10 +2458,6 @@ declare global { * * STDDEV(Records[Close],Time Period = 5,Deviations = 1) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=1} Deviations - * @return {number[]} */ function STDDEV(Records: botvs.Record[] | number[], TimePeriod: number, Deviations: number): number[]; @@ -3326,13 +2468,6 @@ declare global { * = 0) * = [Array(outSlowK),Array(outSlowD)] * - * @param {botvs.Record[]} Records - * @param {number=5} Fast_KPeriod - * @param {number=3} Slow_KPeriod - * @param {number=0} Slow_KMA - * @param {number=3} Slow_DPeriod - * @param {number=0} Slow_DMA - * @return {[number[], number[]]} */ function STOCH( Records: botvs.Record[], @@ -3349,15 +2484,6 @@ declare global { * = 0) * = [Array(outSlowK),Array(outSlowD)] * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=5} Fast_KPeriod - * @param {number=3} Slow_KPeriod - * @param {number=0} Slow_KMA - * @param {number=3} Slow_DPeriod - * @param {number=0} Slow_DMA - * @return {[number[], number[]]} */ function STOCH( High: number[], @@ -3376,11 +2502,6 @@ declare global { * STOCHF(Records[High,Low,Close],Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] * - * @param {botvs.Record[]} Records - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHF( Records: botvs.Record[], @@ -3394,13 +2515,6 @@ declare global { * STOCHF(Records[High,Low,Close],Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHF( High: number[], @@ -3417,12 +2531,6 @@ declare global { * STOCHRSI(Records[Close],Time Period = 14,Fast-K Period = 5,Fast-D Period = 3,Fast-D MA = 0) = * [Array(outFastK),Array(outFastD)] * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @param {number=5} Fast_KPeriod - * @param {number=3} Fast_DPeriod - * @param {number=0} Fast_DMA - * @return {[number[], number[]]} */ function STOCHRSI( Records: botvs.Record[] | number[], @@ -3437,9 +2545,6 @@ declare global { * * SUM(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function SUM(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3448,10 +2553,6 @@ declare global { * * T3(Records[Close],Time Period = 5,Volume Factor = 0.7) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=0.7} VolumeFactor - * @return {number[]} */ function T3(Records: botvs.Record[] | number[], TimePeriod: number, VolumeFactor: number): number[]; @@ -3460,8 +2561,6 @@ declare global { * * TAN(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function TAN(Records: botvs.Record[] | number[]): number[]; @@ -3470,8 +2569,6 @@ declare global { * * TANH(Records[Close]) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @return {number[]} */ function TANH(Records: botvs.Record[] | number[]): number[]; @@ -3480,9 +2577,6 @@ declare global { * * TEMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TEMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3491,8 +2585,6 @@ declare global { * * TRANGE(Records[High,Low,Close]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function TRANGE(Records: botvs.Record[]): number[]; /** @@ -3500,10 +2592,6 @@ declare global { * * TRANGE(Records[High,Low,Close]) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function TRANGE(High: number[], Low: number[], Close: number[]): number[]; @@ -3512,9 +2600,6 @@ declare global { * * TRIMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TRIMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3523,9 +2608,6 @@ declare global { * * TRIX(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function TRIX(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3534,9 +2616,6 @@ declare global { * * TSF(Records[Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function TSF(Records: botvs.Record[] | number[], TimePeriod: number): number[]; @@ -3545,8 +2624,6 @@ declare global { * * TYPPRICE(Records[High,Low,Close]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function TYPPRICE(Records: botvs.Record[]): number[]; /** @@ -3554,10 +2631,6 @@ declare global { * * TYPPRICE(Records[High,Low,Close]) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function TYPPRICE(High: number[], Low: number[], Close: number[]): number[]; @@ -3566,11 +2639,6 @@ declare global { * * ULTOSC(Records[High,Low,Close],First Period = 7,Second Period = 14,Third Period = 28) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=7} FirstPeriod - * @param {number=14} SecondPeriod - * @param {number=28} ThirdPeriod - * @return {number[]} */ function ULTOSC( Records: botvs.Record[], @@ -3583,13 +2651,6 @@ declare global { * * ULTOSC(Records[High,Low,Close],First Period = 7,Second Period = 14,Third Period = 28) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=7} FirstPeriod - * @param {number=14} SecondPeriod - * @param {number=28} ThirdPeriod - * @return {number[]} */ function ULTOSC( High: number[], @@ -3605,10 +2666,6 @@ declare global { * * VAR(Records[Close],Time Period = 5,Deviations = 1) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=5} TimePeriod - * @param {number=1} Deviations - * @return {number[]} */ function VAR(Records: botvs.Record[] | number[], TimePeriod: number, Deviations: number): number[]; @@ -3617,8 +2674,6 @@ declare global { * * WCLPRICE(Records[High,Low,Close]) = Array(outReal) * - * @param {botvs.Record[]} Records - * @return {number[]} */ function WCLPRICE(Records: botvs.Record[]): number[]; /** @@ -3626,10 +2681,6 @@ declare global { * * WCLPRICE(Records[High,Low,Close]) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @return {number[]} */ function WCLPRICE(High: number[], Low: number[], Close: number[]): number[]; @@ -3638,9 +2689,6 @@ declare global { * * WILLR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {botvs.Record[]} Records - * @param {number=14} TimePeriod - * @return {number[]} */ function WILLR(Records: botvs.Record[], TimePeriod: number): number[]; /** @@ -3648,11 +2696,6 @@ declare global { * * WILLR(Records[High,Low,Close],Time Period = 14) = Array(outReal) * - * @param {number[]} High - * @param {number[]} Low - * @param {number[]} Close - * @param {number=14} TimePeriod - * @return {number[]} */ function WILLR(High: number[], Low: number[], Close: number[], TimePeriod: number): number[]; @@ -3661,9 +2704,6 @@ declare global { * * WMA(Records[Close],Time Period = 30) = Array(outReal) * - * @param {botvs.Record[]|number[]} Records - * @param {number=30} TimePeriod - * @return {number[]} */ function WMA(Records: botvs.Record[] | number[], TimePeriod: number): number[]; } @@ -3780,7 +2820,6 @@ declare global { * plt.plot([3,6,2,4,7,1]) * Log(plt) * - * @param {string} arg */ function Log(arg: string): void; @@ -3789,7 +2828,6 @@ declare global { * * 参数为毫秒数,如Sleep(1000)为休眠一秒 * - * @param {number} Millisecond */ function Sleep(Millisecond: number): void; @@ -3798,28 +2836,24 @@ declare global { * * 模拟回测状态返回true,实盘返回false * - * @return {boolean} */ function IsVirtual(): boolean; /** * 记录盈利值,这个为总盈利的值,参数类型为浮点数 * - * @param {number} Profit */ function LogProfit(Profit: number): void; /** * 清空所有收益日志, 可以带一个数字参数, 指定保留的条数 * - * @param {number} reserve */ function LogProfitReset(reserve?: number): void; /** * 清空所有日志, 可以带一个数字参数, 指定保留的条数 * - * @param {number} reserve */ function LogReset(reserve?: number): void; @@ -3856,14 +2890,12 @@ declare global { * LogStatus('`' + JSON.stringify({'type':'button', 'class': 'btn btn-xs btn-danger', 'cmd': 'coverAll', 'name': * '平仓'}) + '`') * - * @param {string} Msg */ function LogStatus(Msg: string): void; /** * 打开或者关闭定单和出错信息的日志记录 * - * @param {boolean} IsEnable */ function EnableLog(IsEnable: boolean): void; @@ -3883,8 +2915,6 @@ declare global { * series的数据, 指定序列3指的是图表3的第一个series的数据 HighStocks: * http://api.highcharts.com/highstock * - * @param {botvs.ChartOptions} options - * @return {botvs.RChart} */ function Chart(...options: botvs.ChartOptions[]): botvs.RChart; @@ -3894,13 +2924,6 @@ declare global { * Mail(smtpServer, smtpUsername, smtpPassword, mailTo, title, body); ret true or false * Mail("smtp.163.com", "asdf@163.com", "password", "111@163.com", "title", "body") * - * @param {string} smtpServer - * @param {string} smtpUsername - * @param {string} smtpPassword - * @param {string} mailTo - * @param {string} title - * @param {string} body - * @return {boolean} */ function Mail( smtpServer: string, @@ -3918,21 +2941,18 @@ declare global { * SetErrorFilter("502:|503:|tcp|character|unexpected|network|timeout|WSARecv|Connect|GetAddr|no * such|reset|http|received|EOF|reused"); * - * @param {string} RegEx */ function SetErrorFilter(RegEx: string): void; /** * 返回机器人进程ID * - * @return {number} */ function GetPid(): number; /** * 获取最近一次出错信息,一般无需使用,因为程序会把出错信息自动上传到日志系统 * - * @return {string} */ function GetLastError(): string; @@ -3948,8 +2968,6 @@ declare global { * _G(); // 返回当前机器人的ID * _G(null); // 删除所有全局变量 * - * @param {string} K - * @param {T} V */ function _G(K: string, V: T): void; @@ -3965,7 +2983,6 @@ declare global { * Sleep(1000); * } * - * @return {string} */ function GetCommand(): string | null; @@ -3989,9 +3006,6 @@ declare global { * } * ``` * - * @param {string} Address - * @param {number} Timeout - * @return {botvs.Socket} */ function Dial(Address: string, Timeout?: number): botvs.Socket | void; @@ -4009,11 +3023,6 @@ declare global { * HttpQuery("http://www.baidu.com/", null, "a=10; b=20", "User-Agent: Mobile\nContent-Type: text/html", true); * // will return {Header: HTTP Header, Body: HTML} * - * @param {string} Url - * @param {string | null | {method: string; data?: string}} PostData - * @param {string} Cookies - * @param {string} Headers - * @return {string} */ function HttpQuery( Url: string, @@ -4036,10 +3045,6 @@ declare global { * Log(Hash('md5', 'hex', 'hello')); * Log(Hash('sha512', 'base64', 'hello')); * - * @param {"md5" | "sha256" | "sha512" | "sha1"} Algo - * @param {"hex" | "base64"} OutputAlgo - * @param {string} Data - * @return {string} */ function Hash( Algo: 'md5' | 'sha256' | 'sha512' | 'sha1', @@ -4054,11 +3059,6 @@ declare global { * Log(HMAC('md5', 'hex', 'hello', 'pass')); * Log(HMAC('sha512', 'base64', 'hello', 'pass')); * - * @param {"md5" | "sha256" | "sha512" | "sha1"} Algo - * @param {"hex" | "base64" | "raw"} OutputAlgo - * @param {string} Data - * @param {string} password - * @return {string} */ function HMAC( Algo: 'md5' | 'sha256' | 'sha512' | 'sha1', @@ -4071,18 +3071,13 @@ declare global { * 返回指定时间戳(ms)字符串, 不传任何参数就返回当前时间, * 如_D(),或者_D(1478570053241), 默认格式为yyyy-MM-dd hh:mm:ss * - * @param {string} timestamp - * @param {string} format - * @return {string} */ function _D(timestamp: string, format: string): string; /** * 格式化一个浮点函数 * - * @param {number} num - * @param {number=4} precision - * @return {string} + * @param precision Default 4 */ function _N(num: number, precision?: number): string; @@ -4091,16 +3086,12 @@ declare global { * 比如_C(exchange.GetTicker), 默认重试间隔为3秒, 可以调用_CDelay函数来控制重试间隔 * 比如_CDelay(1000), 指改变_C函数重试间隔为1秒 * - * @param {(...args: any[]) => T} func - * @param args - * @return {T} */ function _C(func: (...args: any[]) => T, ...args: any[]): T; /** * 比如_CDelay(1000), 指改变_C函数重试间隔为1秒, 默认为3秒 * - * @param {number} delay */ function _CDelay(delay: number): void; } diff --git a/types/bowser/bowser-tests.ts b/types/bowser/bowser-tests.ts index 490d02a254..6b69a12ca2 100644 --- a/types/bowser/bowser-tests.ts +++ b/types/bowser/bowser-tests.ts @@ -1,10 +1,11 @@ -bowser.msedge === true; -bowser.test(['msie']) === true; +bowser.msedge; // $ExpectType boolean +bowser.test(['msie']); // $ExpectType boolean bowser.a === bowser.c; bowser.osversion > 10; bowser.osversion === '10.1A'; bowser.compareVersions(['9.0', '10']); -bowser() === {android: true, x: true}; +bowser().android; // $ExpectType boolean +bowser().x; // $ExpectType boolean bowser.check({msie: "11"}, window.navigator.userAgent); -bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file +bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); diff --git a/types/bowser/index.d.ts b/types/bowser/index.d.ts index 163342a631..7339783c77 100644 --- a/types/bowser/index.d.ts +++ b/types/bowser/index.d.ts @@ -8,13 +8,12 @@ export = bowser; export as namespace bowser; declare namespace bowser { - - export interface IBowserOS { + interface IBowserOS { mac: boolean; - /**other than Windows Phone */ + /** other than Windows Phone */ windows: boolean; windowsphone: boolean; - /**other than android, chromeos, webos, tizen, and sailfish */ + /** other than android, chromeos, webos, tizen, and sailfish */ linux: boolean; chromeos: boolean; android: boolean; @@ -29,7 +28,7 @@ declare namespace bowser { sailfish: boolean; } - export interface IBowserVersions { + interface IBowserVersions { chrome: boolean; firefox: boolean; msie: boolean; @@ -53,14 +52,14 @@ declare namespace bowser { kMeleon: boolean; } - export interface IBowserEngines { + interface IBowserEngines { /** IE <= 11 */ msie: boolean; - /**Chrome 0-27, Android <4.4, iOs, BB, etc. */ + /** Chrome 0-27, Android <4.4, iOs, BB, etc. */ webkit: boolean; - /**Chrome >=28, Android >=4.4, Opera, etc. */ + /** Chrome >=28, Android >=4.4, Opera, etc. */ blink: boolean; - /**Firefox, etc. */ + /** Firefox, etc. */ gecko: boolean; /** IE > 11 */ msedge: boolean; @@ -68,37 +67,35 @@ declare namespace bowser { tablet: boolean; /** All detected mobile OSes are additionally flagged mobile, unless it's a tablet */ mobile: boolean; - } - export interface IBowserGrade { + interface IBowserGrade { /** Grade A browser */ a: boolean; /** Grade C browser */ c: boolean; /** Grade X browser */ x: boolean; - /**A human readable name for this browser. E.g. 'Chrome', '' */ + /** A human readable name for this browser. E.g. 'Chrome', '' */ name: string; - /**Version number for the browser. E.g. '32.0' */ - version: string|number; - osversion: string|number; + /** Version number for the browser. E.g. '32.0' */ + version: string | number; + osversion: string | number; } - export interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { } + interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { } - export interface IBowserMinVersions { + interface IBowserMinVersions { // { msie: "11", "firefox": "4" } [index: string]: string; } - export interface IBowser extends IBowserDetection { + interface IBowser extends IBowserDetection { (): IBowserDetection; test(browserList: string[]): boolean; _detect(ua: string): IBowser; compareVersions(versions: string[]): number; - check(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): Boolean; - isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): boolean; + check(minVersions: IBowserMinVersions, strictMode?: boolean | string, ua?: string): boolean; + isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean | string, ua?: string): boolean; } - } diff --git a/types/bowser/tslint.json b/types/bowser/tslint.json index a41bf5d19a..45f91d386b 100644 --- a/types/bowser/tslint.json +++ b/types/bowser/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + // TODO + "interface-name": false } } diff --git a/types/box2d/index.d.ts b/types/box2d/index.d.ts index 77a132592e..d17eb2c8f6 100644 --- a/types/box2d/index.d.ts +++ b/types/box2d/index.d.ts @@ -5147,7 +5147,7 @@ declare namespace Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. **/ - export class b2PullyJoint extends b2Joint { + export class b2PulleyJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. @@ -5207,7 +5207,7 @@ declare namespace Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. **/ - export class b2PullyJointDef extends b2JointDef { + export class b2PulleyJointDef extends b2JointDef { /** * The first ground anchor in world coordinates. This point never moves. diff --git a/types/braintree-web/index.d.ts b/types/braintree-web/index.d.ts index 46f16e072b..bc5ca0b01f 100644 --- a/types/braintree-web/index.d.ts +++ b/types/braintree-web/index.d.ts @@ -611,12 +611,14 @@ declare namespace braintree { * @property {object} details Additional account details. * @property {string} details.cardType Type of card, ex: Visa, MasterCard. * @property {string} details.lastTwo Last two digits of card number. + * @property {string} details.lastFour Last four digits of card number. * @property {string} description A human-readable description. * @property {string} type The payment method type, always `CreditCard`. */ interface HostedFieldsAccountDetails { cardType: string; lastTwo: string; + lastFour: string; } interface HostedFieldsTokenizePayload { diff --git a/types/browser-bunyan/index.d.ts b/types/browser-bunyan/index.d.ts index 7edabdca26..4fedbcd780 100644 --- a/types/browser-bunyan/index.d.ts +++ b/types/browser-bunyan/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Paul Lockwood // Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 2b6a636e89..6aeeabe3d9 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -39,6 +39,9 @@ export class Binary { constructor(buffer: Buffer, subType?: number); + /** The underlying Buffer which stores the binary data. */ + readonly buffer: Buffer; + /** The length of the binary. */ length(): number; /** Updates this binary with byte_value */ diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index abfd4ddd98..1e9e3b55bc 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for bull 3.0 +// Type definitions for bull 3.3 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers // Marshall Cottrell +// Weeco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Redis from "ioredis"; +import * as Promise from "bluebird"; /** * This is the Queue constructor. @@ -13,407 +16,591 @@ import * as Redis from "ioredis"; * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. */ declare const Bull: { - // tslint:disable:unified-signatures - (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - (queueName: string, url?: string): Bull.Queue; - new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - new (queueName: string, url?: string): Bull.Queue; - // tslint:enable:unified-signatures + // tslint:disable:unified-signatures + (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + (queueName: string, url?: string): Bull.Queue; + new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + new (queueName: string, url?: string): Bull.Queue; + // tslint:enable:unified-signatures }; declare namespace Bull { - interface QueueOptions { - /** - * Options passed directly to the `ioredis` constructor - */ - redis?: Redis.RedisOptions; - - /** - * When specified, the `Queue` will use this function to create new `ioredis` client connections. - * This is useful if you want to re-use connections. - */ - createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; - - /** - * Prefix to use for all redis keys - */ - prefix?: string; - - settings?: AdvancedSettings; - } - - interface AdvancedSettings { - /** - * Key expiration time for job locks - */ - lockDuration?: number; - - /** - * How often check for stalled jobs (use 0 for never checking) - */ - stalledInterval?: number; - - /** - * Max amount of times a stalled job will be re-processed - */ - maxStalledCount?: number; - - /** - * Poll interval for delayed jobs and added jobs - */ - guardInterval?: number; - - /** - * Delay before processing next job in case of internal error - */ - retryProcessDelay?: number; - } - - type DoneCallback = (error?: Error | null, value?: any) => void; - - type JobId = number | string; - - interface Job { - id: JobId; - - /** - * The custom data passed when the job was created - */ - data: any; - - /** - * Report progress on a job - */ - progress(value: any): Promise; - - /** - * Removes a job from the queue and from any lists it may be included in. - * @returns A promise that resolves when the job is removed. - */ - remove(): Promise; - - /** - * Re-run a job that has failed. - * @returns A promise that resolves when the job is scheduled for retry. - */ - retry(): Promise; - - /** - * Returns a promise the resolves when the job has been finished. - * TODO: Add a watchdog to check if the job has finished periodically. - * since pubsub does not give any guarantees. - */ - finished(): Promise; - - /** - * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. - */ - promote(): Promise; - } - - type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; - - interface BackoffOptions { - /** - * Backoff type, which can be either `fixed` or `exponential` - */ - type: 'fixed' | 'exponential'; - - /** - * Backoff delay, in milliseconds - */ - delay: number; - } - - interface RepeatOptions { - /** - * Cron pattern specifying when the job should execute - */ - cron: string; - - /** - * Timezone - */ - tz?: string; - - /** - * End date when the repeat job should stop repeating - */ - endDate?: Date | string | number; - } - - interface JobOptions { - /** - * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). - * Note that using priorities has a slight impact on performance, so do not use it if not required - */ - priority?: number; - - /** - * An amount of miliseconds to wait until this job can be processed. - * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] - */ - delay?: number; - - /** - * The total number of attempts to try the job until it completes - */ - attempts?: number; - - /** - * Repeat job according to a cron specification - */ - repeat?: RepeatOptions; - - /** - * Backoff setting for automatic retries if the job fails - */ - backoff?: number | BackoffOptions; - - /** - * A boolean which, if true, adds the job to the right - * of the queue instead of the left (default false) - */ - lifo?: boolean; - - /** - * The number of milliseconds after which the job should be fail with a timeout error - */ - timeout?: number; - - /** - * Override the job ID - by default, the job ID is a unique - * integer, but you can use this setting to override it. - * If you use this option, it is up to you to ensure the - * jobId is unique. If you attempt to add a job with an id that - * already exists, it will not be added. - */ - jobId?: JobId; - - /** - * A boolean which, if true, removes the job when it successfully completes. - * Default behavior is to keep the job in the completed set. - */ - removeOnComplete?: boolean; - - /** - * A boolean which, if true, removes the job when it fails after all attempts - * Default behavior is to keep the job in the completed set. - */ - removeOnFail?: boolean; - } - - interface JobCounts { - wait: number; - active: number; - completed: number; - failed: number; - delayed: number; - } - - interface Queue { - /** - * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. - * This replaces the `ready` event emitted on Queue in previous verisons. - */ - isReady(): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job) => void): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - */ - process(callback: (job: Job) => void): Promise; - - /** - * Creates a new job and adds it to the queue. - * If the queue is empty the job will be executed directly, - * otherwise it will be placed in the queue and executed as soon as possible. - */ - add(data: any, opts?: JobOptions): Promise; - - /** - * Returns a promise that resolves when the queue is paused. - * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. - * A paused queue will not process new jobs until resumed, - * but current jobs being processed will continue until they are finalized. - * - * Pausing a queue that is already paused does nothing. - */ - pause(): Promise; - - /** - * Returns a promise that resolves when the queue is resumed after being paused. - * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. - * - * Resuming a queue that is not paused does nothing. - */ - resume(): Promise; - - /** - * Returns a promise that returns the number of jobs in the queue, waiting or paused. - * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. - */ - count(): Promise; - - /** - * Empties a queue deleting all the input lists and associated jobs. - */ - empty(): Promise; - - /** - * Closes the underlying redis client. Use this to perform a graceful shutdown. - * - * `close` can be called from anywhere, with one caveat: - * if called from within a job handler the queue won't close until after the job has been processed - */ - close(): Promise; - - /** - * Returns a promise that will return the job instance associated with the jobId parameter. - * If the specified job cannot be located, the promise callback parameter will be set to null. - */ - getJob(jobId: JobId): Promise; - - /** - * Returns a promise that resolves with the job counts for the given queue - */ - getJobCounts(): Promise; - - /** - * Tells the queue remove all jobs created outside of a grace period in milliseconds. - * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. - */ - clean(grace: number, status?: JobStatus, limit?: number): Promise; - - // tslint:disable:unified-signatures - - /** - * Listens to queue events - */ - on(event: string, callback: (...args: any[]) => void): this; - - /** - * An error occured - */ - on(event: 'error', callback: ErrorEventCallback): this; - - /** - * A job has started. You can use `jobPromise.cancel()` to abort it - */ - on(event: 'active', callback: ActiveEventCallback): this; - - /** - * A job has been marked as stalled. - * This is useful for debugging job workers that crash or pause the event loop. - */ - on(event: 'stalled', callback: StalledEventCallback): this; - - /** - * A job's progress was updated - */ - on(event: 'progress', callback: ProgressEventCallback): this; - - /** - * A job successfully completed with a `result` - */ - on(event: 'completed', callback: CompletedEventCallback): this; - - /** - * A job failed with `err` as the reason - */ - on(event: 'failed', callback: FailedEventCallback): this; - - /** - * The queue has been paused - */ - on(event: 'paused', callback: EventCallback): this; - - /** - * The queue has been resumed - */ - on(event: 'resumed', callback: EventCallback): this; - - /** - * Old jobs have been cleaned from the queue. - * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. - * - * @see Queue#clean() for details - */ - on(event: 'cleaned', callback: CleanedEventCallback): this; - - // tslint:enable:unified-signatures - } - - type EventCallback = () => void; - - type ErrorEventCallback = (error: Error) => void; - - interface JobPromise { - /** - * Abort this job - */ - cancel(): void; - } - - type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; - - type StalledEventCallback = (job: Job) => void; - - type ProgressEventCallback = (job: Job, progress: any) => void; - - type CompletedEventCallback = (job: Job, result: any) => void; - - type FailedEventCallback = (job: Job, error: Error) => void; - - type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; + interface RateLimiter { + /** Max numbers of jobs processed */ + max: number; + /** Per duration in milliseconds */ + duration: number; + } + + interface QueueOptions { + /** + * Options passed directly to the `ioredis` constructor + */ + redis?: Redis.RedisOptions; + + /** + * When specified, the `Queue` will use this function to create new `ioredis` client connections. + * This is useful if you want to re-use connections. + */ + createClient?(type: 'client' | 'subscriber', redisOpts?: Redis.RedisOptions): Redis.Redis; + + /** + * Prefix to use for all redis keys + */ + prefix?: string; + + settings?: AdvancedSettings; + + limiter?: RateLimiter; + } + + interface AdvancedSettings { + /** + * Key expiration time for job locks + */ + lockDuration?: number; + + /** + * How often check for stalled jobs (use 0 for never checking) + */ + stalledInterval?: number; + + /** + * Max amount of times a stalled job will be re-processed + */ + maxStalledCount?: number; + + /** + * Poll interval for delayed jobs and added jobs + */ + guardInterval?: number; + + /** + * Delay before processing next job in case of internal error + */ + retryProcessDelay?: number; + } + + type DoneCallback = (error?: Error | null, value?: any) => void; + + type JobId = number | string; + + interface Job { + id: JobId; + + /** + * The custom data passed when the job was created + */ + data: any; + + /** + * Report progress on a job + */ + progress(value: any): Promise; + + /** + * Returns a promise resolving to the current job's status. + * Please take note that the implementation of this method is not very efficient, nor is + * it atomic. If your queue does have a very large quantity of jobs, you may want to + * avoid using this method. + */ + getState(): Promise; + + /** + * Update a specific job's data. Promise resolves when the job has been updated. + */ + update(data: any): Promise; + + /** + * Removes a job from the queue and from any lists it may be included in. + * The returned promise resolves when the job has been removed. + */ + remove(): Promise; + + /** + * Re-run a job that has failed. The returned promise resolves when the job + * has been scheduled for retry. + */ + retry(): Promise; + + /** + * Returns a promise that resolves to the returned data when the job has been finished. + * TODO: Add a watchdog to check if the job has finished periodically. + * since pubsub does not give any guarantees. + */ + finished(): Promise; + + /** + * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. + */ + promote(): Promise; + } + + type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; + + interface BackoffOptions { + /** + * Backoff type, which can be either `fixed` or `exponential` + */ + type: 'fixed' | 'exponential'; + + /** + * Backoff delay, in milliseconds + */ + delay: number; + } + + interface RepeatOptions { + /** + * Cron pattern specifying when the job should execute + */ + cron: string; + + /** + * Timezone + */ + tz?: string; + + /** + * End date when the repeat job should stop repeating + */ + endDate?: Date | string | number; + } + + interface JobOptions { + /** + * Optional priority value. ranges from 1 (highest priority) to MAX_INT (lowest priority). + * Note that using priorities has a slight impact on performance, so do not use it if not required + */ + priority?: number; + + /** + * An amount of miliseconds to wait until this job can be processed. + * Note that for accurate delays, both server and clients should have their clocks synchronized. [optional] + */ + delay?: number; + + /** + * The total number of attempts to try the job until it completes + */ + attempts?: number; + + /** + * Repeat job according to a cron specification + */ + repeat?: RepeatOptions; + + /** + * Backoff setting for automatic retries if the job fails + */ + backoff?: number | BackoffOptions; + + /** + * A boolean which, if true, adds the job to the right + * of the queue instead of the left (default false) + */ + lifo?: boolean; + + /** + * The number of milliseconds after which the job should be fail with a timeout error + */ + timeout?: number; + + /** + * Override the job ID - by default, the job ID is a unique + * integer, but you can use this setting to override it. + * If you use this option, it is up to you to ensure the + * jobId is unique. If you attempt to add a job with an id that + * already exists, it will not be added. + */ + jobId?: JobId; + + /** + * A boolean which, if true, removes the job when it successfully completes. + * Default behavior is to keep the job in the completed set. + */ + removeOnComplete?: boolean; + + /** + * A boolean which, if true, removes the job when it fails after all attempts + * Default behavior is to keep the job in the completed set. + */ + removeOnFail?: boolean; + } + + interface JobCounts { + wait: number; + active: number; + completed: number; + failed: number; + delayed: number; + } + + interface JobInformation { + key: string; + name: string; + id?: string; + endDate?: number; + tz?: string; + cron: string; + next: number; + } + + interface Queue { + /** + * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. + * This replaces the `ready` event emitted on Queue in previous verisons. + */ + isReady(): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + */ + process(callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + */ + process(callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + */ + // tslint:disable-next-line:unified-signatures + process(name: string, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a named processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * @param name Bull will only call the handler if the job name matches + * @param concurrency Bull will then call you handler in parallel respecting this max number. + */ + process(name: string, concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: any, opts?: JobOptions): Promise; + + /** + * Creates a new named job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(name: string, data: any, opts?: JobOptions): Promise; + + /** + * Returns a promise that resolves when the queue is paused. + * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. + * A paused queue will not process new jobs until resumed, + * but current jobs being processed will continue until they are finalized. + * + * Pausing a queue that is already paused does nothing. + */ + pause(): Promise; + + /** + * Returns a promise that resolves when the queue is resumed after being paused. + * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * Resuming a queue that is not paused does nothing. + */ + resume(): Promise; + + /** + * Returns a promise that returns the number of jobs in the queue, waiting or paused. + * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. + */ + count(): Promise; + + /** + * Empties a queue deleting all the input lists and associated jobs. + */ + empty(): Promise; + + /** + * Closes the underlying redis client. Use this to perform a graceful shutdown. + * + * `close` can be called from anywhere, with one caveat: + * if called from within a job handler the queue won't close until after the job has been processed + */ + close(): Promise; + + /** + * Returns a promise that will return the job instance associated with the jobId parameter. + * If the specified job cannot be located, the promise callback parameter will be set to null. + */ + getJob(jobId: JobId): Promise; + + /** + * Returns a promise that will return an array with the active jobs between start and end. + */ + getActive(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the delayed jobs between start and end. + */ + getDelayed(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the completed jobs between start and end. + */ + getCompleted(start?: number, end?: number): Promise; + + /** + * Returns a promise that will return an array with the failed jobs between start and end. + */ + getFailed(start?: number, end?: number): Promise; + + /** + * Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end + * index to limit the number of results. Start defaults to 0, end to -1 and asc to false. + */ + getRepeatableJobs(start?: number, end?: number, asc?: boolean): Promise; + + /** + * ??? + */ + nextRepeatableJob(name: string, data: any, opts: JobOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + */ + removeRepeatable(repeat: RepeatOptions): Promise; + + /** + * Removes a given repeatable job. The RepeatOpts needs to be the same as the ones used for + * the job when it was added. + * + * name: The name of the to be removed job + */ + removeRepeatable(name: string, repeat: RepeatOptions): Promise; + + /** + * Returns a promise that resolves with the job counts for the given queue. + */ + getJobCounts(): Promise; + + /** + * Returns a promise that resolves with the quantity of completed jobs. + */ + getCompletedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of failed jobs. + */ + getFailedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of delayed jobs. + */ + getDelayedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of waiting jobs. + */ + getWaitingCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of paused jobs. + */ + getPausedCount(): Promise; + + /** + * Returns a promise that resolves with the quantity of active jobs. + */ + getActiveCount(): Promise; + + /** + * Returns a promise that resolves to the quantity of repeatable jobs. + */ + getRepeatableCount(): Promise; + + /** + * Tells the queue remove all jobs created outside of a grace period in milliseconds. + * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + * @param grace Grace period in milliseconds. + * @param status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. + * @param limit Maximum amount of jobs to clean per call. If not provided will clean all matching jobs. + */ + clean(grace: number, status?: JobStatus, limit?: number): Promise; + + // tslint:disable:unified-signatures + + /** + * Listens to queue events + */ + on(event: string, callback: (...args: any[]) => void): this; + + /** + * An error occured + */ + on(event: 'error', callback: ErrorEventCallback): this; + + /** + * A job has started. You can use `jobPromise.cancel()` to abort it + */ + on(event: 'active', callback: ActiveEventCallback): this; + + /** + * A job has been marked as stalled. + * This is useful for debugging job workers that crash or pause the event loop. + */ + on(event: 'stalled', callback: StalledEventCallback): this; + + /** + * A job's progress was updated + */ + on(event: 'progress', callback: ProgressEventCallback): this; + + /** + * A job successfully completed with a `result` + */ + on(event: 'completed', callback: CompletedEventCallback): this; + + /** + * A job failed with `err` as the reason + */ + on(event: 'failed', callback: FailedEventCallback): this; + + /** + * The queue has been paused + */ + on(event: 'paused', callback: EventCallback): this; + + /** + * The queue has been resumed + */ + on(event: 'resumed', callback: EventCallback): this; + + /** + * Old jobs have been cleaned from the queue. + * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. + * + * @see Queue#clean() for details + */ + on(event: 'cleaned', callback: CleanedEventCallback): this; + + // tslint:enable:unified-signatures + } + + type EventCallback = () => void; + + type ErrorEventCallback = (error: Error) => void; + + interface JobPromise { + /** + * Abort this job + */ + cancel(): void; + } + + type ActiveEventCallback = (job: Job, jobPromise?: JobPromise) => void; + + type StalledEventCallback = (job: Job) => void; + + type ProgressEventCallback = (job: Job, progress: any) => void; + + type CompletedEventCallback = (job: Job, result: any) => void; + + type FailedEventCallback = (job: Job, error: Error) => void; + + type CleanedEventCallback = (jobs: Job[], status: JobStatus) => void; } export = Bull; diff --git a/types/bunyan-blackhole/index.d.ts b/types/bunyan-blackhole/index.d.ts index 2ece8b2f40..80b4a33fcf 100644 --- a/types/bunyan-blackhole/index.d.ts +++ b/types/bunyan-blackhole/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Floby/node-bunyan-blackhole // Definitions by: Olivier Chevet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as Logger from "bunyan"; diff --git a/types/bunyan-bugsnag/index.d.ts b/types/bunyan-bugsnag/index.d.ts index 9716238aab..06e13714b7 100644 --- a/types/bunyan-bugsnag/index.d.ts +++ b/types/bunyan-bugsnag/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/marnusw/bunyan-bugsnag // Definitions by: Pasi Eronen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as Logger from 'bunyan'; diff --git a/types/bunyan-format/bunyan-format-tests.ts b/types/bunyan-format/bunyan-format-tests.ts new file mode 100644 index 0000000000..3f4c2a658d --- /dev/null +++ b/types/bunyan-format/bunyan-format-tests.ts @@ -0,0 +1,5 @@ +import BunyanFormatWritable = require('bunyan-format'); + +const formatOut = new BunyanFormatWritable({ outputMode: 'short' }); + +const formatOut2 = new BunyanFormatWritable({ outputMode: 'bunyan', levelInString: true }); diff --git a/types/bunyan-format/index.d.ts b/types/bunyan-format/index.d.ts new file mode 100644 index 0000000000..06a37ba2e5 --- /dev/null +++ b/types/bunyan-format/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for bunyan-format 0.2 +// Project: https://github.com/thlorenz/bunyan-format +// Definitions by: Piotr Roszatycki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Writable } from 'stream'; + +declare namespace BunyanFormatWritable { + interface ColorFromLevel { + [level: number]: string; + } + + interface Options { + outputMode?: 'short' | 'long' | 'simple' | 'json' | 'bunyan'; + color?: boolean; + colorFromLevel?: ColorFromLevel; + levelInString?: boolean; + jsonIndent?: string | number; + } +} + +declare class BunyanFormatWritable extends Writable { + /** Creates a writable stream that formats bunyan records written to it. */ + constructor(options: BunyanFormatWritable.Options, output?: Writable); +} + +export = BunyanFormatWritable; diff --git a/types/bunyan-format/tsconfig.json b/types/bunyan-format/tsconfig.json new file mode 100644 index 0000000000..c26359cdb6 --- /dev/null +++ b/types/bunyan-format/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bunyan-format-tests.ts" + ] +} diff --git a/types/bunyan-format/tslint.json b/types/bunyan-format/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bunyan-format/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bunyan-winston-adapter/index.d.ts b/types/bunyan-winston-adapter/index.d.ts index e0c4f835d9..6798b8f1c9 100644 --- a/types/bunyan-winston-adapter/index.d.ts +++ b/types/bunyan-winston-adapter/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gluwer/bunyan-winston-adapter // Definitions by: Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as bunyan from "bunyan"; import { LoggerInstance } from "winston"; diff --git a/types/business-rules-engine/index.d.ts b/types/business-rules-engine/index.d.ts index a74bcf180d..d85cd49c81 100644 --- a/types/business-rules-engine/index.d.ts +++ b/types/business-rules-engine/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rsamec/form // Definitions by: Roman Samec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Source: typings/business-rules-engine/Validation.d.ts diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index eb727233a0..afae3cff31 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -459,11 +459,11 @@ declare namespace c3 { /** * Set max value of x axis range. */ - max?: number; + max?: string | number | Date; /** * Set min value of x axis range. */ - min?: number; + min?: string | number | Date; /** * Set padding for x axis. * If this option is set, the range of x axis will increase/decrease according to the values. If no padding is needed in the ragen of x axis, 0 should be set. On category axis, this option @@ -636,7 +636,7 @@ declare namespace c3 { } interface LineOptions { - value: number; + value: string | number | Date; text?: string; axis?: string; position?: string; diff --git a/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts b/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts new file mode 100644 index 0000000000..a4370cff73 --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/case-sensitive-paths-webpack-plugin-tests.ts @@ -0,0 +1,15 @@ +import { Configuration } from 'webpack'; +import CaseSensitivePathsWebpackPlugin = require('case-sensitive-paths-webpack-plugin'); + +const options: CaseSensitivePathsWebpackPlugin.Options = { + debug: true, +}; + +const c: Configuration = { + plugins: [ + new CaseSensitivePathsWebpackPlugin(), + new CaseSensitivePathsWebpackPlugin({ + debug: true + }), + ], +}; diff --git a/types/case-sensitive-paths-webpack-plugin/index.d.ts b/types/case-sensitive-paths-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..360d3d6d08 --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for case-sensitive-paths-webpack-plugin 2.1 +// Project: https://github.com/Urthen/case-sensitive-paths-webpack-plugin#readme +// Definitions by: Andrew Makarov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = CaseSensitivePathsWebpackPlugin; + +declare class CaseSensitivePathsWebpackPlugin extends Plugin { + constructor(options?: CaseSensitivePathsWebpackPlugin.Options); +} + +declare namespace CaseSensitivePathsWebpackPlugin { + interface Options { + /** + * Show more information + */ + debug?: boolean; + } +} diff --git a/types/case-sensitive-paths-webpack-plugin/tsconfig.json b/types/case-sensitive-paths-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..b8cb05390a --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "case-sensitive-paths-webpack-plugin-tests.ts" + ] +} diff --git a/types/case-sensitive-paths-webpack-plugin/tslint.json b/types/case-sensitive-paths-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/case-sensitive-paths-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 40971c7183..891c5a0167 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -1,9 +1,16 @@ import * as cassandra from 'cassandra-driver'; import * as util from 'util'; +import * as fs from 'fs'; -var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'}); +const client = new cassandra.Client({ + contactPoints: ['h1', 'h2'], + keyspace: 'ks1', + sslOptions: { + cert: fs.readFileSync('certFilePath') + } +}); -var query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; +const query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; client.execute(query, ['guy'], function(err, result) { console.log('got user profile with email ' + result.rows[0].email); }); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index a581071dfb..bdaed6559c 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -12,11 +12,12 @@ export type ResultCallback = (err: Error, result: types.ResultSet) => void; import * as events from "events"; import * as stream from "stream"; +import * as tls from "tls"; import _Long = require("long"); export namespace policies { namespace addressResolution { - var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + let EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; interface AddressTranslator { translate(address: string, port: number, callback: Callback): void; @@ -32,10 +33,10 @@ export namespace policies { } namespace loadBalancing { - var DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - var RoundRobinPolicy: RoundRobinPolicyStatic; - var TokenAwarePolicy: TokenAwarePolicyStatic; - var WhiteListPolicy: WhiteListPolicyStatic; + let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; + let RoundRobinPolicy: RoundRobinPolicyStatic; + let TokenAwarePolicy: TokenAwarePolicyStatic; + let WhiteListPolicy: WhiteListPolicyStatic; interface LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; @@ -72,8 +73,8 @@ export namespace policies { } namespace reconnection { - var ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; - var ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; + let ConstantReconnectionPolicy: ConstantReconnectionPolicyStatic; + let ExponentialReconnectionPolicy: ExponentialReconnectionPolicyStatic; interface ReconnectionPolicy { newSchedule(): { next: Function }; @@ -93,7 +94,7 @@ export namespace policies { } namespace retry { - var RetryPolicy: RetryPolicyStatic; + let RetryPolicy: RetryPolicyStatic; interface DecisionInfo { decision: number; @@ -128,18 +129,18 @@ export namespace policies { } export namespace types { - var BigDecimal: BigDecimalStatic; - var InetAddress: InetAddressStatic; - var Integer: IntegerStatic; - var LocalDate: LocalDateStatic; - var LocalTime: LocalTimeStatic; - var Long: _Long; - var ResultSet: ResultSetStatic; - // var ResultStream: ResultStreamStatic; - var Row: RowStatic; - var TimeUuid: TimeUuidStatic; - var Tuple: TupleStatic; - var Uuid: UuidStatic; + let BigDecimal: BigDecimalStatic; + let InetAddress: InetAddressStatic; + let Integer: IntegerStatic; + let LocalDate: LocalDateStatic; + let LocalTime: LocalTimeStatic; + let Long: _Long; + let ResultSet: ResultSetStatic; + // let ResultStream: ResultStreamStatic; + let Row: RowStatic; + let TimeUuid: TimeUuidStatic; + let Tuple: TupleStatic; + let Uuid: UuidStatic; enum consistencies { any = 0, @@ -433,10 +434,10 @@ export namespace types { } } -export var Client: ClientStatic; -export var Host: HostStatic; -export var HostMap: HostMapStatic; -export var Encoder: EncoderStatic; +export let Client: ClientStatic; +export let Host: HostStatic; +export let HostMap: HostMapStatic; +export let Encoder: EncoderStatic; export interface ClientOptions { contactPoints: Array, @@ -468,7 +469,7 @@ export interface ClientOptions { coalescingThreshold: number }, authProvider?: auth.AuthProvider, - sslOptions?: any, + sslOptions?: tls.ConnectionOptions, encoding?: { map: Function, set: Function, @@ -564,8 +565,8 @@ export interface Encoder { } export namespace auth { - var Authenticator: AuthenticatorStatic; - var PlainTextAuthProvider: PlainTextAuthProviderStatic; + let Authenticator: AuthenticatorStatic; + let PlainTextAuthProvider: PlainTextAuthProviderStatic; interface AuthenticatorStatic { new (): Authenticator; @@ -623,12 +624,12 @@ export namespace errors { } export namespace metadata { - var Aggregate: AggregateStatic; - var Index: IndexStatic; - var MaterializedView: MaterializedViewStatic; - var Metadata: MetadataStatic; - var SchemaFunction: SchemaFunctionStatic; - var TableMetadata: TableMetadataStatic; + let Aggregate: AggregateStatic; + let Index: IndexStatic; + let MaterializedView: MaterializedViewStatic; + let Metadata: MetadataStatic; + let SchemaFunction: SchemaFunctionStatic; + let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 7bc691abdc..826f1f7369 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/catbox // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as Boom from 'boom'; diff --git a/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts b/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts index 05cf190765..c93c4a1d04 100644 --- a/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts +++ b/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts @@ -16,7 +16,7 @@ const mockContext: Mocha.IBeforeAndAfterContext = { } }; -chaiJestSnapshot.setFileName("filename"); +chaiJestSnapshot.setFilename("filename"); chaiJestSnapshot.setTestName("testname"); chaiJestSnapshot.configureUsingMochaContext(mockContext); chaiJestSnapshot.resetSnapshotRegistry(); diff --git a/types/chai-jest-snapshot/index.d.ts b/types/chai-jest-snapshot/index.d.ts index 40ce5afc1b..862da8cd16 100644 --- a/types/chai-jest-snapshot/index.d.ts +++ b/types/chai-jest-snapshot/index.d.ts @@ -21,7 +21,7 @@ interface ChaiJestSnapshot { (chai: any, utils: any): void; /** Set snapshot file name */ - setFileName(filename: string): void; + setFilename(filename: string): void; /** * Set snapshot test name diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index 31802ca303..401e5f468a 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -1357,6 +1357,56 @@ suite('assert', () => { assert.notInclude(undefined, 'bar'); }); + test('deepInclude', () => { + assert.deepInclude('foobar', 'bar'); + assert.deepInclude([1, 2, 3], 3); + assert.deepInclude('foobar', 'baz'); + assert.deepInclude(undefined, 'bar'); + }); + + test('notDeepInclude', () => { + assert.notDeepInclude('foobar', 'baz'); + assert.notDeepInclude([1, 2, 3], 4); + assert.notDeepInclude('foobar', 'bar'); + assert.notDeepInclude(undefined, 'bar'); + }); + + test('nestedInclude', () => { + assert.nestedInclude({'.a': {'b': 'x'}}, {'\\.a.[b]': 'x'}); + assert.nestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'x'}); + }); + + test('notNestedInclude', () => { + assert.notNestedInclude({'.a': {'b': 'x'}}, {'\\.a.b': 'y'}); + assert.notNestedInclude({'a': {'[b]': 'x'}}, {'a.\\[b\\]': 'y'}); + }); + + test('deepNestedInclude', () => { + assert.deepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {x: 1}}); + assert.deepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {x: 1}}); + }); + + test('notDeepNestedInclude', () => { + assert.notDeepNestedInclude({a: {b: [{x: 1}]}}, {'a.b[0]': {y: 1}}) + assert.notDeepNestedInclude({'.a': {'[b]': {x: 1}}}, {'\\.a.\\[b\\]': {y: 2}}); + }); + + test('ownInclude', () => { + assert.ownInclude({ a: 1 }, { a: 1 }); + }); + + test('notOwnInclude', () => { + assert.notOwnInclude({ a: 1 }, { a: 1 }); + }); + + test('deepOwnInclude', () => { + assert.deepOwnInclude({a: {b: 2}}, {a: {b: 2}}); + }); + + test('notDeepOwnInclude', () => { + assert.notDeepOwnInclude({a: {b: 2}}, {a: {c: 3}}); + }); + test('lengthOf', () => { assert.lengthOf([1, 2, 3], 3); assert.lengthOf('foobar', 6); @@ -1677,4 +1727,80 @@ suite('assert', () => { assert.notFrozen(obj); assert.notFrozen(obj, 'message'); }); + + test('hasAnyKeys', () => { + assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'iDontExist', 'baz']); + assert.hasAnyKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, iDontExist: 99, baz: 1337}); + assert.hasAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.hasAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('hasAllKeys', () => { + assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + assert.hasAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + assert.hasAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.hasAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('containsAllKeys', () => { + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'baz']); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, ['foo', 'bar', 'baz']); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, baz: 1337}); + assert.containsAllKeys({foo: 1, bar: 2, baz: 3}, {foo: 30, bar: 99, baz: 1337}); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}]); + assert.containsAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{foo: 1}, 'key']); + assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}]); + assert.containsAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{foo: 'bar'}, 'anotherKey']); + }); + + test('doesNotHaveAnyKeys', () => { + assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + assert.doesNotHaveAnyKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + assert.doesNotHaveAnyKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAnyKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + }); + + test('doesNotHaveAllKeys', () => { + assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, ['one', 'two', 'example']); + assert.doesNotHaveAllKeys({foo: 1, bar: 2, baz: 3}, {one: 1, two: 2, example: 'foo'}); + assert.doesNotHaveAllKeys(new Map([[{foo: 1}, 'bar'], ['key', 'value']]), [{one: 'two'}, 'example']); + assert.doesNotHaveAllKeys(new Set([{foo: 'bar'}, 'anotherKey']), [{one: 'two'}, 'example']); + }); + + test('hasAnyDeepKeys', () => { + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {three: 'three'}]); + assert.hasAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('hasAllDeepKeys', () => { + assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne']]), {one: 'one'}); + assert.hasAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.hasAllDeepKeys(new Set([{one: 'one'}]), {one: 'one'}); + assert.hasAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('containsAllDeepKeys', () => { + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {one: 'one'}); + assert.containsAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{one: 'one'}, {two: 'two'}]); + assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {one: 'one'}); + assert.containsAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {two: 'two'}]); + }); + + test('doesNotHaveAnyDeepKeys', () => { + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAnyDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + assert.doesNotHaveAnyDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{twenty: 'twenty'}, {fifty: 'fifty'}]); + }); + + test('doesNotHaveAllDeepKeys', () => { + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [1, 2]]), {thisDoesNot: 'exist'}); + assert.doesNotHaveAllDeepKeys(new Map([[{one: 'one'}, 'valueOne'], [{two: 'two'}, 'valueTwo']]), [{twenty: 'twenty'}, {one: 'one'}]); + assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), {twenty: 'twenty'}); + assert.doesNotHaveAllDeepKeys(new Set([{one: 'one'}, {two: 'two'}]), [{one: 'one'}, {fifty: 'fifty'}]); + }); }); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index bb730fe598..faafa3b2a8 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -7,6 +7,7 @@ // Matt Wistrand , // Josh Goldberg // Shaun Luttin +// Gintautas Miselis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @@ -706,13 +707,145 @@ declare namespace Chai { /** * Asserts that haystack does not include needle. * - * @type T Type of values in haystack. * @param haystack Container array. * @param needle Potential value contained in haystack. * @param message Message to display on error. */ notInclude(haystack: any[], needle: any, message?: string): void; + + /** + * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + deepInclude(haystack: string, needle: string, message?: string): void; + + /** + * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack Container string. + * @param needle Potential expected substring of haystack. + * @param message Message to display on error. + */ + notDeepInclude(haystack: string, needle: any, message?: string): void; + + /** + * Asserts that haystack does not include needle. Can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepInclude(haystack: any[], needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + nestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ does not include ‘needle’. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. + * + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes.Asserts that ‘haystack’ includes ‘needle’. + * Can be used to assert the inclusion of a subset of properties in an object. + * Enables the use of dot- and bracket-notation for referencing nested properties. + * ‘[]’ and ‘.’ in property names can be escaped using double backslashes. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepNestedInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + ownInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + deepOwnInclude(haystack: any, needle: any, message?: string): void; + + /** + * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality. + * + * @param haystack + * @param needle + * @param message Message to display on error. + */ + notDeepOwnInclude(haystack: any, needle: any, message?: string): void; + /** * Asserts that value matches the regular expression regexp. * @@ -1360,6 +1493,136 @@ declare namespace Chai { * @param message Message to display on error. */ isNotEmpty(object: T, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all of the `keys` provided but may have more keys not listed. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has none of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` does not have at least one of the `keys` provided. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has at least one of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` has all and only all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + hasAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + containsAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAnyDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; + + /** + * Asserts that `object` contains all of the `keys` provided. + * Since Sets and Maps can have objects as keys you can use this assertion to perform + * a deep comparison. + * You can also provide a single object instead of a `keys` array and its keys + * will be used as the expected set of keys. + * + * @type T Type of object. + * @param object Object to test. + * @param keys Keys to check + * @param message Message to display on error. + */ + doesNotHaveAllDeepKeys(object: T, keys: Array | { [key: string]: any }, message?: string): void; } export interface Config { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ed4339f60f..049488f8db 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chart.js 2.6 +// Type definitions for Chart.js 2.7 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Fabien Lavocat @@ -78,7 +78,7 @@ interface Size { } declare namespace Chart { - type ChartType = 'line' | 'bar' | 'radar' | 'doughnut' | 'polarArea' | 'bubble'; + type ChartType = 'line' | 'bar' | 'radar' | 'doughnut' | 'polarArea' | 'bubble' | 'pie'; type TimeUnit = 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; @@ -114,18 +114,25 @@ declare namespace Chart { index?: number; } + interface ChartTooltipLabelColor { + borderColor: ChartColor; + backgroundColor: ChartColor; + } + interface ChartTooltipCallback { - beforeTitle?(item?: ChartTooltipItem[], data?: any): void; - title?(item?: ChartTooltipItem[], data?: any): void; - afterTitle?(item?: ChartTooltipItem[], data?: any): void; - beforeBody?(item?: ChartTooltipItem[], data?: any): void; - beforeLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - label?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterLabel?(tooltipItem?: ChartTooltipItem, data?: any): void; - afterBody?(item?: ChartTooltipItem[], data?: any): void; - beforeFooter?(item?: ChartTooltipItem[], data?: any): void; - footer?(item?: ChartTooltipItem[], data?: any): void; - afterFooter?(item?: ChartTooltipItem[], data?: any): void; + beforeTitle?(item: ChartTooltipItem[], data: ChartData): string | string[]; + title?(item: ChartTooltipItem[], data: ChartData): string | string[]; + afterTitle?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeBody?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeLabel?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + label?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + labelColor?(tooltipItem: ChartTooltipItem, chart: Chart): ChartTooltipLabelColor; + labelTextColor?(tooltipItem: ChartTooltipItem, chart: Chart): string; + afterLabel?(tooltipItem: ChartTooltipItem, data: ChartData): string | string[]; + afterBody?(item: ChartTooltipItem[], data: ChartData): string | string[]; + beforeFooter?(item: ChartTooltipItem[], data: ChartData): string | string[]; + footer?(item: ChartTooltipItem[], data: ChartData): string | string[]; + afterFooter?(item: ChartTooltipItem[], data: ChartData): string | string[]; } interface ChartAnimationParameter { @@ -152,9 +159,10 @@ declare namespace Chart { interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; + aspectRatio?: number; maintainAspectRatio?: boolean; events?: string[]; - onClick?(any?: any): any; + onClick?(event?: MouseEvent, activeElements?: Array<{}>): any; title?: ChartTitleOptions; legend?: ChartLegendOptions; tooltips?: ChartTooltipOptions; @@ -411,8 +419,8 @@ declare namespace Chart { interface ChartDataSets { cubicInterpolationMode?: 'default' | 'monotone'; backgroundColor?: ChartColor | ChartColor[]; - borderWidth?: number; - borderColor?: ChartColor; + borderWidth?: number | number[]; + borderColor?: ChartColor | ChartColor[]; borderCapStyle?: string; borderDash?: number[]; borderDashOffset?: number; diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 2037e83c7a..8250848374 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Cheerio v0.22.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani , LiJinyao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Cheerio { @@ -172,7 +172,7 @@ interface Cheerio { empty(): Cheerio; - html(): string; + html(): string | null; html(html: string): Cheerio; text(): string; @@ -255,6 +255,7 @@ interface CheerioElement { children: CheerioElement[]; childNodes: CheerioElement[]; lastChild: CheerioElement; + firstChild: CheerioElement; next: CheerioElement; nextSibling: CheerioElement; prev: CheerioElement; @@ -262,6 +263,7 @@ interface CheerioElement { parent: CheerioElement; parentNode: CheerioElement; nodeValue: string; + data?: string; } interface CheerioAPI extends CheerioSelector, CheerioStatic { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index ca7b35bf0e..bb2b4afcb5 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -1426,8 +1426,7 @@ declare namespace chrome.declarativeContent { ports?: (number | number[])[]; } - /** Matches the state of a web page by various criteria. */ - interface PageStateMatcher { + class PageStateMatcherProperties { /** Optional. Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ pageUrl?: PageStateUrlDetails; /** Optional. Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's main frame. All selectors in this array must be compound selectors to speed up matching. Note that listing hundreds of CSS selectors or CSS selectors that match hundreds of times per page can still slow down web sites. */ @@ -1439,6 +1438,19 @@ declare namespace chrome.declarativeContent { */ isBookmarked?: boolean; } + + /** Matches the state of a web page by various criteria. */ + class PageStateMatcher { + constructor(options: PageStateMatcherProperties); + } + + /** Declarative event action that shows the extension's page action while the corresponding conditions are met. */ + class ShowPageAction {} + + /** Provides the Declarative Event API consisting of addRules, removeRules, and getRules. */ + interface PageChangedEvent extends chrome.events.Event<() => void> {} + + var onPageChanged: PageChangedEvent; } //////////////////// @@ -1664,7 +1676,7 @@ declare namespace chrome.devtools.inspectedWindow { * Parameter result: The result of evaluation. * Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression. */ - export function eval(expression: string, callback?: (result: Object, exceptionInfo: EvaluationExceptionInfo) => void): void; + export function eval(expression: string, callback?: (result: T, exceptionInfo: EvaluationExceptionInfo) => void): void; /** * Retrieves the list of resources from the inspected page. * @param callback A function that receives the list of resources when the request completes. @@ -5126,7 +5138,7 @@ declare namespace chrome.runtime { actions?: { type: string; }[]; - conditions?: chrome.declarativeContent.PageStateMatcher[] + conditions?: chrome.declarativeContent.PageStateMatcherProperties[] }[]; externally_connectable?: { ids?: string[]; @@ -5535,19 +5547,12 @@ declare namespace chrome.storage { */ set(items: Object, callback?: () => void): void; /** - * Removes one item from storage. - * @param key A single key for items to remove. + * Removes one or more items from storage. + * @param A single key or a list of keys for items to remove. * @param callback Optional. * Callback on success, or on failure (in which case runtime.lastError will be set). */ - remove(key: string, callback?: () => void): void; - /** - * Removes items from storage. - * @param keys A list of keys for items to remove. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - remove(keys: string[], callback?: () => void): void; + remove(keys: string | string[], callback?: () => void): void; /** * Gets one or more items from storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). @@ -7018,8 +7023,9 @@ declare namespace chrome.webNavigation { /** * The ID of the process runs the renderer for this tab. * @since Chrome 22. + * @deprecated since Chrome 49. Frames are now uniquely identified by their tab ID and frame ID; the process ID is no longer needed and therefore ignored. */ - processId: number; + processId?: number; /** The ID of the tab in which the frame is. */ tabId: number; /** The ID of the frame in the given tab. */ diff --git a/types/chui/index.d.ts b/types/chui/index.d.ts index 7042edd4bd..f80aaa3e5d 100644 --- a/types/chui/index.d.ts +++ b/types/chui/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/chocolatechipui/chocolatechip-ui // Definitions by: Robert Biggs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + // ChocolateChip-UI 3.9.1 /** These TypeScript delcarations for ChocolateChip-UI contain interfaces for both ChocolateChipJS and jQuery. Depending on which library you are using, you will get the type interfaces appropriate for it. @@ -1078,7 +1080,7 @@ interface JQueryStatic { data: { repeaterName?: any; }; - + /** * Use this value to output an index value in a template repeater. */ diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index b6471ddab6..dd0ec92164 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -52,6 +52,23 @@ function test_config() { [ 'list', 'indent', 'blocks', 'align', 'bidi' ], ], }; + var config3: CKEDITOR.config = { + toolbarGroups: [ + { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, + { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] }, + { name: 'links', groups: [ 'links' ] }, + { name: 'insert', groups: [ 'insert' ] }, + { name: 'tools', groups: [ 'tools' ] }, + { name: 'document', groups: [ 'mode' ] }, + { name: 'about', groups: [ 'about' ] }, + '/', + { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, + { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'paragraph' ] }, + '/', + { name: 'styles', groups: [ 'styles' ] }, + { name: 'colors', groups: [ 'colors' ] }, + ], + } } function test_dom_comment() { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 24ff341b38..20882269fd 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for CKEditor // Project: http://ckeditor.com/ -// Definitions by: Ondrej Sevcik +// Definitions by: Thomas Wittwer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // WORK-IN-PROGRESS: Any contribution support welcomed. @@ -602,13 +602,17 @@ declare namespace CKEDITOR { browserContextMenuOnCtrl?: boolean; clipboard_defaultContentType?: string; // html | text + clipboard_notificationDuration?: number; codeSnippet_codeClass?: string; codeSnippet_languages?: Object; coceSnippet_theme?: string; colorButton_backStyle?: config.styleObject; colorButton_colors?: string; + colorButton_colorsPerRow?: number; + colorButton_enableAutomatic?: boolean; colorButton_enableMore?: boolean; colorButton_foreStyle?: config.styleObject; + colorButton_normalizeBackground?: boolean; contentsCss?: string | string[]; contentsLangDirection?: string; contentsLanguage?: string; @@ -727,7 +731,7 @@ declare namespace CKEDITOR { magicline_holdDistance?: number; magicline_keystrokeNext?: number; magicline_keystrokePrevious?: number; - magicline_tabuList?: number; + magicline_tabuList?: string[]; magicline_triggerOffset?: number; mathJaxLib?: string; menu_groups?: string; @@ -814,7 +818,7 @@ declare namespace CKEDITOR { toolbar?: string | (string | string[])[]; toolbarCanCollapse?: boolean; toolbarGroupCycling?: boolean; - toolbarGroups?: toolbarGroups[]; + toolbarGroups?: (toolbarGroups | string)[]; toolbarLocation?: string; toolbarStartupExpanded?: boolean; diff --git a/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts b/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts new file mode 100644 index 0000000000..6d60f36d51 --- /dev/null +++ b/types/clean-webpack-plugin/clean-webpack-plugin-tests.ts @@ -0,0 +1,17 @@ +import CleanWebpackPlugin = require('clean-webpack-plugin'); + +const paths = [ + 'path', + 'glob/**/*.js', +]; + +new CleanWebpackPlugin(paths); +new CleanWebpackPlugin(paths, 'root-directory'); +new CleanWebpackPlugin(paths, {}); +new CleanWebpackPlugin(paths, { + root: 'root-directory', + verbose: true, + dry: true, + watch: true, + exclude: ['a, b'], +}); diff --git a/types/clean-webpack-plugin/index.d.ts b/types/clean-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..7fc45cc3e4 --- /dev/null +++ b/types/clean-webpack-plugin/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for clean-webpack-plugin 0.1 +// Project: https://github.com/johnagan/clean-webpack-plugin +// Definitions by: Jed Fox +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack'; + +export = CleanWebpackPlugin; + +declare class CleanWebpackPlugin extends Plugin { + /** + * @param paths A glob or array of globs to delete + */ + constructor(paths: string | ReadonlyArray, options?: string | CleanWebpackPlugin.Options); +} + +declare namespace CleanWebpackPlugin { + interface Options { + /** + * Absolute path to your webpack root folder (paths appended to this) + * Default: root of your package + */ + root?: string; + /** + * Write logs to the console. + */ + verbose?: boolean; + /** + * Set to `true` to emulate deletion without actually removing any files. + */ + dry?: boolean; + /** + * If true, remove files on recompile. + */ + watch?: boolean; + /** + * Instead of removing whole path recursively, + * remove all path's content with exclusion of provided immediate children. + * Good for not removing shared files from build directories. + */ + exclude?: ReadonlyArray; + /** + * Allow the plugin to clean folders outside of the webpack root + */ + allowExternal?: boolean; + } +} diff --git a/types/clean-webpack-plugin/tsconfig.json b/types/clean-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..2f342b4d42 --- /dev/null +++ b/types/clean-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clean-webpack-plugin-tests.ts" + ] +} diff --git a/types/clean-webpack-plugin/tslint.json b/types/clean-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clean-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 1ec788cd8f..17e8c1c512 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cleave.js 1.0 // Project: https://github.com/nosir/cleave.js -// Definitions by: C Lentfort +// Definitions by: C Lentfort , J Giancono // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/cleave.js/options.d.ts b/types/cleave.js/options.d.ts index 4320881649..81757fe097 100644 --- a/types/cleave.js/options.d.ts +++ b/types/cleave.js/options.d.ts @@ -10,6 +10,8 @@ export type CreditCardType = | "mastercard" | "uatp" | "unknown" + | "unionPay" + | "mir" | "visa"; export type CreditCardTypeChangeHandler = (owner: HTMLInputElement, type: CreditCardType) => void; @@ -33,7 +35,7 @@ export interface CleaveOptions { } // Numeral Options -export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan"; +export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan" | "none"; export interface CleaveOptions { numeral?: boolean; @@ -55,6 +57,7 @@ export interface CleaveOptions { lowercase?: boolean; numericOnly?: boolean; prefix?: string; + noImmediatePrefix?: boolean; rawValueTrimPrefix?: boolean; uppercase?: boolean; } diff --git a/types/cli/cli-tests.ts b/types/cli/cli-tests.ts index 294cb7dd8b..2a88a216db 100644 --- a/types/cli/cli-tests.ts +++ b/types/cli/cli-tests.ts @@ -52,7 +52,8 @@ cli.main(function (args, options) { } return str; } - for (i = 0, l = this.argc; i < l; i++) { + var l: number = this.argc; + for (i = 0; i < l; i++) { args[i] = escape(args[i]); } options.separator = escape(options.separator); diff --git a/types/co-body/index.d.ts b/types/co-body/index.d.ts index a2c15152e6..7906f38e81 100644 --- a/types/co-body/index.d.ts +++ b/types/co-body/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/cojs/co-body // Definitions by: Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index cfcbd9d5b3..4f479b29d0 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -105,9 +105,9 @@ declare namespace CodeMirror { function signal(target: any, name: string, ...args: any[]): void; type DOMEvent = 'mousedown' | 'dblclick' | 'touchstart' | 'contextmenu' | 'keydown' | 'keypress' | 'keyup' | 'cut' | 'copy' | 'paste' | 'dragstart' | 'dragenter' | 'dragover' | 'dragleave' | 'drop'; - + type CoordsMode = 'window' | 'page' | 'local'; - + interface Token { /** The character(on the given line) at which the token starts. */ start: number; @@ -202,10 +202,10 @@ declare namespace CodeMirror { /** Compute the line at the given pixel height. mode is the relative element to use to compute this line, it may be "window", "page" (the default), or "local" */ lineAtHeight(height: number, mode?: CoordsMode): number; - - /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", - "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value - is the bottom of the last line in the document. By default, the position of the actual text is returned. + + /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", + "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value + is the bottom of the last line in the document. By default, the position of the actual text is returned. If includeWidgets is true and the line has line widgets, the position above the first line widget is returned. */ heightAtLine(line: any, mode?: CoordsMode, includeWidgets?: boolean): number; @@ -292,7 +292,7 @@ declare namespace CodeMirror { charCoords(pos: CodeMirror.Position, mode?: CoordsMode): { left: number; right: number; top: number; bottom: number; }; /** Given an { left , top } object , returns the { line , ch } position that corresponds to it. - The optional mode parameter determines relative to what the coordinates are interpreted. + The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local". */ coordsChar(object: { left: number; top: number; }, mode?: CoordsMode): CodeMirror.Position; @@ -512,7 +512,7 @@ declare namespace CodeMirror { /** Get the currently selected code. */ getSelection(): string; - + /** Returns an array containing a string for each selection, representing the content of the selections. */ getSelections(lineSep?: string): Array; @@ -535,8 +535,14 @@ declare namespace CodeMirror { /** Set the cursor position.You can either pass a single { line , ch } object , or the line and the character as two separate parameters. */ setCursor(pos: CodeMirror.Position): void; - /** Set the selection range.anchor and head should be { line , ch } objects.head defaults to anchor when not given. */ - setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position): void; + /** Set a single selection range. anchor and head should be {line, ch} objects. head defaults to anchor when not given. */ + setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position, options?: { bias?: number, origin?: string, scroll?: boolean }): void; + + /** Sets a new set of selections. There must be at least one selection in the given array. When primary is a + number, it determines which selection is the primary one. When it is not given, the primary index is taken from + the previous selection, or set to the last range if the previous selection had less ranges than the new one. + Supports the same options as setSelection. */ + setSelections(ranges: Array<{ anchor: CodeMirror.Position, head: CodeMirror.Position }>, primary?: number, options?: { bias?: number, origin?: string, scroll?: boolean }): void; /** Similar to setSelection , but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. @@ -692,7 +698,7 @@ declare namespace CodeMirror { interface EditorChangeCancellable extends CodeMirror.EditorChange { /** may be used to modify the change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. */ - update(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string): void; + update(from?: CodeMirror.Position, to?: CodeMirror.Position, text?: string[]): void; cancel(): void; } @@ -779,7 +785,7 @@ declare namespace CodeMirror { /** Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). */ fixedGutter?: boolean; - + /** * Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also * provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models. @@ -1141,6 +1147,7 @@ declare namespace CodeMirror { interface LintStateOptions { async: boolean; hasGutters: boolean; + onUpdateLinting?: (annotationsNotSorted: Annotation[], annotations: Annotation[], codeMirror: Editor) => void; } /** diff --git a/types/combokeys/index.d.ts b/types/combokeys/index.d.ts index f7e1e5b035..24f3313582 100644 --- a/types/combokeys/index.d.ts +++ b/types/combokeys/index.d.ts @@ -35,7 +35,7 @@ declare namespace Combokeys { * @param {handler} optional - one of "keypress", "keydown", or "keyup" * @returns void */ - bind(keys: string | string[], callback: () => void, action?: string): void; + bind(keys: string | string[], callback: (event: KeyboardEvent) => void, action?: string): void; /** diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 442ee5cb93..332368d827 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for command-line-args 4.0.6 +// Type definitions for command-line-args 4.0.7 // Project: https://github.com/75lb/command-line-args // Definitions by: CzBuCHi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -25,50 +25,63 @@ */ declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any; -declare module commandLineArgs { +declare module commandLineArgs { - export interface OptionDefinition { - /** - * The only required definition property is name, the value of each option will be either a Boolean or string. - */ - name: string, - /** - * The type value is a setter function (you receive the output from this), enabling you to be specific about the type and value received. - */ - type?: (arg: string) => any, - /** - * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. - */ - alias?: string, - /** - * Set this flag if the option takes a list of values. You will receive an array of values, each passed through the type function (if specified). - */ - multiple?: boolean, - /** - * Any unclaimed command-line args will be set on this option. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. $ myapp *.js instead of $ myapp --files *.js). - */ - defaultOption?: boolean, - /** - * An initial value for the option. - */ - defaultValue?: any, - /** - * When your app has a large amount of options it makes sense to organise them in groups. - * There are two automatic groups: _all (contains all options) and _none (contains options without a group specified in their definition). - */ - group?: string | string[], - } + export interface OptionDefinition { + /** + * The only required definition property is name, the value of each option will be either a Boolean or string. + */ + name: string, + /** + * The type value is a setter function (you receive the output from this), + * enabling you to be specific about the type and value received. + */ + type?: (arg: string) => any, + /** + * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. + */ + alias?: string, + /** + * Set this flag if the option takes a list of values. You will receive an array of values, each passed + * through the type function (if specified). + */ + multiple?: boolean, + /** + * Any unclaimed command-line args will be set on this option. This flag is typically set on + * the most commonly-used option to make for more concise usage + * (i.e. $ myapp *.js instead of $ myapp --files *.js). + */ + defaultOption?: boolean, + /** + * An initial value for the option. + */ + defaultValue?: any, + /** + * When your app has a large amount of options it makes sense to organise them in groups. + * There are two automatic groups: _all (contains all options) and _none (contains options + * without a group specified in their definition). + */ + group?: string | string[], + /** + * Describes the option. + */ + description?: string, + /** + * A label for the type, e.g. . + */ + typeLabel?: string; + } - export interface Options { - /** - * An array of strings, which if passed will be parsed instead of `process.argv`. - */ - argv?: string[]; - /** - * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - */ - partial?: boolean; - } + export interface Options { + /** + * An array of strings, which if passed will be parsed instead of `process.argv`. + */ + argv?: string[]; + /** + * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. + */ + partial?: boolean; + } } export = commandLineArgs; diff --git a/types/compression/index.d.ts b/types/compression/index.d.ts index 75c37d4374..68d687a9c4 100644 --- a/types/compression/index.d.ts +++ b/types/compression/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/compression // Definitions by: Santi Albo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as express from 'express'; diff --git a/types/compute-stdev/compute-stdev-tests.ts b/types/compute-stdev/compute-stdev-tests.ts new file mode 100644 index 0000000000..72b9869ded --- /dev/null +++ b/types/compute-stdev/compute-stdev-tests.ts @@ -0,0 +1,4 @@ +import stdev = require('compute-stdev'); + +// $ExpectType number +stdev([1, 2, 3]); diff --git a/types/compute-stdev/index.d.ts b/types/compute-stdev/index.d.ts new file mode 100644 index 0000000000..7e981ae529 --- /dev/null +++ b/types/compute-stdev/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for compute-stdev 1.0 +// Project: https://github.com/compute-io/stdev +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function stdev(data: ArrayLike): number; + +export = stdev; diff --git a/types/compute-stdev/tsconfig.json b/types/compute-stdev/tsconfig.json new file mode 100644 index 0000000000..f622c386a3 --- /dev/null +++ b/types/compute-stdev/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "compute-stdev-tests.ts" + ] +} diff --git a/types/compute-stdev/tslint.json b/types/compute-stdev/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compute-stdev/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/connect-ensure-login/index.d.ts b/types/connect-ensure-login/index.d.ts index 9158255c40..6c91101ab5 100644 --- a/types/connect-ensure-login/index.d.ts +++ b/types/connect-ensure-login/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jaredhanson/connect-ensure-login // Definitions by: Pavel Puchkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { RequestHandler } from "express"; diff --git a/types/connect-flash/index.d.ts b/types/connect-flash/index.d.ts index cb7d460623..90540da3ed 100644 --- a/types/connect-flash/index.d.ts +++ b/types/connect-flash/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jaredhanson/connect-flash // Definitions by: Andreas Gassmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/connect-history-api-fallback/index.d.ts b/types/connect-history-api-fallback/index.d.ts index 9cd77ac174..a39fbfdbd6 100644 --- a/types/connect-history-api-fallback/index.d.ts +++ b/types/connect-history-api-fallback/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bripkens/connect-history-api-fallback#readme // Definitions by: Douglas Duteil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/connect-modrewrite/index.d.ts b/types/connect-modrewrite/index.d.ts index 41372046d1..910d56f9af 100644 --- a/types/connect-modrewrite/index.d.ts +++ b/types/connect-modrewrite/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/tinganho/connect-modrewrite // Definitions by: Tingan Ho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/connect-redis/index.d.ts b/types/connect-redis/index.d.ts index b5084609a2..5675512795 100644 --- a/types/connect-redis/index.d.ts +++ b/types/connect-redis/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Xavier Stouder // Albert Kurniawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// diff --git a/types/connect-slashes/index.d.ts b/types/connect-slashes/index.d.ts index ccb7eb82c3..440f54372c 100644 --- a/types/connect-slashes/index.d.ts +++ b/types/connect-slashes/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/avinoamr/connect-slashes // Definitions by: Sam Herrmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /* =================== USAGE =================== diff --git a/types/content-type/index.d.ts b/types/content-type/index.d.ts index 5ff4ae7ff1..c81c78c966 100644 --- a/types/content-type/index.d.ts +++ b/types/content-type/index.d.ts @@ -18,7 +18,7 @@ export interface MediaType { } export interface RequestLike { - headers: {[header: string]: string | string[]}; + headers: {[header: string]: string | string[] | undefined}; } export interface ResponseLike { diff --git a/types/cookie-session/index.d.ts b/types/cookie-session/index.d.ts index 29562d0320..001ba646d5 100644 --- a/types/cookie-session/index.d.ts +++ b/types/cookie-session/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/cookie-session // Definitions by: Borislav Zhivkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/cookies/index.d.ts b/types/cookies/index.d.ts index 8a897cfeae..380ce03b7d 100644 --- a/types/cookies/index.d.ts +++ b/types/cookies/index.d.ts @@ -4,6 +4,7 @@ // jKey Lu // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// import { IncomingMessage, ServerResponse } from 'http'; diff --git a/types/cordova-plugin-device/index.d.ts b/types/cordova-plugin-device/index.d.ts index cb75703d1a..0451afb4de 100644 --- a/types/cordova-plugin-device/index.d.ts +++ b/types/cordova-plugin-device/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/apache/cordova-plugin-device // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license +// Licensed under the MIT license /** * This plugin defines a global device object, which describes the device's hardware and software. @@ -26,11 +26,16 @@ interface Device { uuid: string; /** Get the operating system version. */ version: string; - /** Get the device's manufacturer. */ - manufacturer: string; - /** Whether the device is running on a simulator. */ - isVirtual: boolean; - /** Get the device hardware serial number. */ - serial: string;} + /** Get the device's manufacturer. */ + manufacturer: string; + /** Whether the device is running on a simulator. */ + isVirtual: boolean; + /** Get the device hardware serial number. */ + serial: string; +} + +interface Window { + device: Device; +} declare var device: Device; diff --git a/types/cordova-plugin-ibeacon/index.d.ts b/types/cordova-plugin-ibeacon/index.d.ts index eb2115448d..20d5733ea9 100644 --- a/types/cordova-plugin-ibeacon/index.d.ts +++ b/types/cordova-plugin-ibeacon/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/petermetz/cordova-plugin-ibeacon // Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from "q"; diff --git a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts index 767eaa6ed2..fa5cf72a30 100644 --- a/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts +++ b/types/cordova-plugin-keyboard/cordova-plugin-keyboard-tests.ts @@ -1,23 +1,31 @@ Keyboard.shrinkView(true); Keyboard.shrinkView(false); +Keyboard.shrinkView(null, (currentValue) => console.log(currentValue)); + Keyboard.hideFormAccessoryBar(true); Keyboard.hideFormAccessoryBar(false); +Keyboard.hideFormAccessoryBar(null, (currentValue) => console.log(currentValue)); + Keyboard.disableScrollingInShrinkView(true); Keyboard.disableScrollingInShrinkView(false); +Keyboard.disableScrollingInShrinkView(null, (currentValue) => console.log(currentValue)); + +Keyboard.hide(); + +Keyboard.show(); + if (Keyboard.isVisible) { console.log('Keyboard is visible'); } -Keyboard.automaticScrollToTopOnHiding = true; -Keyboard.onshow = function () { - console.log('onshow'); -}; -Keyboard.onhide = function () { - console.log('onhide'); -}; -Keyboard.onshowing = function () { - console.log('onshowing'); -}; -Keyboard.onhiding= function () { - console.log('onhiding'); -}; +Keyboard.automaticScrollToTopOnHiding = true; + +window.addEventListener('keyboardDidShow', () => console.log('keyboardDidShow')); + +window.addEventListener('keyboardDidHide', () => console.log('keyboardDidHide')); + +window.addEventListener('keyboardWillShow', () => console.log('keyboardWillShow')); + +window.addEventListener('keyboardWillHide', () => console.log('keyboardWillHide')); + +window.addEventListener('keyboardHeightWillChange', (event: CordovaKeyboardEvent) => console.log(`keyboardHeightWillChange - keyboard height: ${event.keyboardHeight}`)); diff --git a/types/cordova-plugin-keyboard/index.d.ts b/types/cordova-plugin-keyboard/index.d.ts index 427a5425e5..af880d732a 100644 --- a/types/cordova-plugin-keyboard/index.d.ts +++ b/types/cordova-plugin-keyboard/index.d.ts @@ -1,32 +1,9 @@ -// Type definitions for Apache Cordova Keyboard plugin v0.1.2 -// Project: https://github.com/apache/cordova-plugins/tree/master/keyboard -// Definitions by: Dan Manastireanu +// Type definitions for Apache Cordova Keyboard plugin v1.2.0 +// Project: https://github.com/cjpearson/cordova-plugin-keyboard +// Definitions by: Dan Manastireanu +// Jochen Becker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * The Keyboard object provides some functions to customize the iOS keyboard. - * - * Supported Platforms: iOS - * - * This plugin has only been tested in Cordova 3.2 or greater, - * and its use in previous Cordova versions is not recommended - * (potential conflict with keyboard customization code present in the core in previous Cordova versions). - * - * If you do use this plugin in an older Cordova version (again, not recommended), - * you have to make sure the HideKeyboardFormAccessoryBar and KeyboardShrinksView preference values are always false, - * and only use the API functions to turn things on/off. - * - * This plugin supports the HideKeyboardFormAccessoryBar (boolean) - * and KeyboardShrinksView (boolean) preferences in config.xml. - * - * Permissions in config.xml - * - * - * - * - * - * - */ interface Keyboard { // Methods @@ -39,15 +16,20 @@ interface Keyboard { * This applies to apps that position their elements relative to the bottom of the WebView. * This is the default behaviour on Android, and makes a lot of sense when building apps as opposed to webpages. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.shrinkView(true); * Keyboard.shrinkView(false); + * Keyboard.shrinkView(null, function (currentValue) { console.log(currentValue); }); * * * @param shrink + * @param successCallback A success callbackfunction */ - shrinkView(shrink:boolean): void, + shrinkView(shrink: boolean, successCallback?: (currentValue: any) => void): void, /** * Hide the keyboard toolbar. @@ -55,21 +37,29 @@ interface Keyboard { * Set to true to hide the additional toolbar that is on top of the keyboard. * This toolbar features the Prev, Next, and Done buttons. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.hideFormAccessoryBar(true); * Keyboard.hideFormAccessoryBar(false); + * Keyboard.hideFormAccessoryBar(null, function (currentValue) { console.log(currentValue); }); * * * @param hide + * @param successCallback A success callbackfunction */ - hideFormAccessoryBar(hide:boolean): void, + hideFormAccessoryBar(hide: boolean, successCallback?: (currentValue: any) => void): void, /** * Disable scrolling when the the WebView is shrunk. * * Set to true to disable scrolling when the WebView is shrunk. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.disableScrollingInShrinkView(true); @@ -77,8 +67,40 @@ interface Keyboard { * * * @param disable + * @param successCallback A success callbackfunction */ - disableScrollingInShrinkView(disable:boolean): void, + disableScrollingInShrinkView(disable: boolean, successCallback?: (currentValue: any) => void): void, + + /** + * Hide the keyboard + * + * Call this method to hide the keyboard + * + * Supported Platforms: + * - iOS + * - Android + * + * Example: + * + * Keyboard.hide(); + * + */ + hide(): void, + + /** + * Show the keyboard + * + * Call this method to show the keyboard. + * + * Supported Platforms: + * - Android + * + * Example: + * + * Keyboard.show(); + * + */ + show(): void, // Properties @@ -87,6 +109,9 @@ interface Keyboard { * * Read this property to determine if the keyboard is visible. * + * Supported Platforms: + * - iOS + * * Example: * * if (Keyboard.isVisible) { @@ -102,6 +127,9 @@ interface Keyboard { * Set this to true if you need that page scroll to beginning when keyboard is hiding. * This is allows to fix issue with elements declared with position: fixed, after keyboard is hiding. * + * Supported Platforms: + * - iOS + * * Example: * * Keyboard.automaticScrollToTopOnHiding = true; @@ -110,65 +138,48 @@ interface Keyboard { */ automaticScrollToTopOnHiding: boolean, - // Events + /** + * Deprecated Events + */ + onshow(): void, - /** - * If defined, this function is fired when keyboard fully shown. - * - * Attach handler to this event to be able to receive notification when keyboard is shown. - * - * Example: - * - * Keyboard.onshow = function () { - * // Describe your logic which will be run each time keyboard is shown. - * } - * - * - */ - onshow():void, - /** - * If defined, this function is fired when keyboard fully closed. - * - * Attach handler to this event to be able to receive notification when keyboard is closed. - * - * Example: - * - * Keyboard.onhide = function () { - * // Describe your logic which will be run each time keyboard is closed. - * } - * - * - */ - onhide():void, - /** - * If defined, this function is fired before keyboard will be shown. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be shown on the screen. - * - * Example: - * - * Keyboard.onshowing = function () { - * // Describe your logic which will be run each time when keyboard is about to be shown. - * } - * - * - */ - onshowing():void, - /** - * If defined, this function is fired when keyboard is about to be closed. - * - * Attach handler to this event to be able to receive notification when keyboard is about to be closed. - * - * Example: - * - * Keyboard.onhiding = function () { - * // Describe your logic which will be run each time when keyboard is about to be closed. - * } - * - * - */ - onhiding():void, + onhide(): void, + onhiding(): void, + + onshowing(): void } -declare var Keyboard:Keyboard; +interface CordovaKeyboardEvent extends Event { + /** The height of the keyboard */ + keyboardHeight: number; +} + +interface WindowEventMap { + /** + * This event is fired when keyboard fully shown. + */ + 'keyboardDidShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardDidHide': Event, + + /** + * This event fires before keyboard will be shown. + */ + 'keyboardWillShow': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardWillHide': Event, + + /** + * This event is fired when the keyboard is fully closed. + */ + 'keyboardHeightWillChange': CordovaKeyboardEvent + } + +declare var Keyboard: Keyboard; diff --git a/types/cors/cors-tests.ts b/types/cors/cors-tests.ts index f43b9ee153..83975549c7 100644 --- a/types/cors/cors-tests.ts +++ b/types/cors/cors-tests.ts @@ -2,7 +2,7 @@ import express = require('express'); import cors = require('cors'); -var app = express(); +const app = express(); app.use(cors()); app.use(cors({ maxAge: 100, @@ -28,6 +28,9 @@ app.use(cors({ app.use(cors({ origin: /example\.com$/ })); +app.use(cors({ + origin: [/example\.com$/, 'http://example.com'] +})); app.use(cors({ origin: ['http://example.com', 'http://fakeurl.com'] })); @@ -37,7 +40,7 @@ app.use(cors({ app.use(cors({ origin: (requestOrigin, cb) => { try { - var allow = requestOrigin.indexOf('.edu') !== -1; + const allow = requestOrigin.indexOf('.edu') !== -1; cb(null, allow); } catch (err) { cb(err); diff --git a/types/cors/index.d.ts b/types/cors/index.d.ts index 6c1fc3e4c3..ab8ba2ed2d 100644 --- a/types/cors/index.d.ts +++ b/types/cors/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/troygoode/node-cors/ // Definitions by: Mihhail Lapushkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 @@ -15,7 +16,7 @@ type CustomOrigin = ( declare namespace e { interface CorsOptions { - origin?: boolean | string | RegExp | string[] | RegExp[] | CustomOrigin; + origin?: boolean | string | RegExp | (string | RegExp)[] | CustomOrigin; methods?: string | string[]; allowedHeaders?: string | string[]; exposedHeaders?: string | string[]; diff --git a/types/coverup/coverup-tests.ts b/types/coverup/coverup-tests.ts new file mode 100644 index 0000000000..dc9ab7022f --- /dev/null +++ b/types/coverup/coverup-tests.ts @@ -0,0 +1,38 @@ +import coverup = require("coverup"); + +coverup("4242-4242-4242-4242"); // $ExpectType string +// => ******************* + +coverup("4242-4242-4242-4242", { char: "%" }); // $ExpectType string +// => %%%%%%%%%%%%%%%%%%% + +coverup("4242-4242-4242-4242", { keepSymbols: true }); // $ExpectType string +// => ****-****-****-**** + +coverup("4242-4242-4242-4242", { keepLeft: 1, keepRight: 1, compactTo: 4 }); // $ExpectType string +// => 4****2 + +coverup("4242-4242-4242-4242", { keepLeft: 4 }); // $ExpectType string +// => 4242*************** + +coverup("4242-4242-4242-4242", { keepRight: 4 }); // $ExpectType string +// => ***************4242 + +let options: coverup.Options = { + char: "x", + keepLeft: 3, + keepRight: 3, +}; + +coverup("4242-4242-4242-4242", options); // $ExpectType string +// => 424xxxxxxxxxxxxx242 + +options = { + keepLeft: 1, + keepRight: 1, + compactTo: 4, + keepSymbols: true, +}; + +coverup("4242-4242-4242-4242", options); // $ExpectError "you cannot define both compactTo and keepSymbols" +// => Error: you cannot define both compactTo and keepSymbols diff --git a/types/coverup/index.d.ts b/types/coverup/index.d.ts new file mode 100644 index 0000000000..d813984799 --- /dev/null +++ b/types/coverup/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for coverup 0.1 +// Project: https://github.com/jsonmaur/coverup +// Definitions by: Vadim Belorussov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace Coverup; + +export = coverup; + +declare function coverup(value: string, options?: coverup.Options): string; + +declare namespace coverup { + interface Options { + char?: string; + keepLeft?: number; + keepRight?: number; + compactTo?: number; + keepSymbols?: boolean; + } +} diff --git a/types/coverup/tsconfig.json b/types/coverup/tsconfig.json new file mode 100644 index 0000000000..6102ad61b3 --- /dev/null +++ b/types/coverup/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "coverup-tests.ts" + ] +} diff --git a/types/coverup/tslint.json b/types/coverup/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/coverup/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/croppie/index.d.ts b/types/croppie/index.d.ts index ec4626aa7f..e2e207db4c 100644 --- a/types/croppie/index.d.ts +++ b/types/croppie/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Foliotek/Croppie // Definitions by: Connor Peet // dklmuc +// Sarun Intaralawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export default class Croppie { @@ -15,10 +16,10 @@ export default class Croppie { useCanvas?: boolean, }): Promise; - result(options: ResultOptions & { type: 'base64' }): Promise; + result(options: ResultOptions & { type: 'base64' | 'canvas' }): Promise; result(options: ResultOptions & { type: 'html' }): Promise; result(options: ResultOptions & { type: 'blob' }): Promise; - result(options: ResultOptions & { type: 'canvas' }): Promise; + result(options: ResultOptions & { type: 'rawcanvas' }): Promise; result(options?: ResultOptions): Promise; rotate(degrees: 90 | 180 | 270 | -90 | -180 | -270): void; diff --git a/types/crossfilter/crossfilter-tests.ts b/types/crossfilter/crossfilter-tests.ts index 813ddae2b9..5d9981b6d1 100644 --- a/types/crossfilter/crossfilter-tests.ts +++ b/types/crossfilter/crossfilter-tests.ts @@ -118,10 +118,10 @@ var types = paymentCountByType.all(); paymentsByTotal.dispose(); crossfilter.bisect([], null, 0, 0); -var bisectBy = crossfilter.bisect.by(t => t); -bisectBy([], null, 0, 0); -bisectBy.left([], null, 0, 0); -bisectBy.right([], null, 0, 0); +var bisectBy = crossfilter.bisect.by<{value: string}, string>(t => t.value); +bisectBy([{value: 'a'}, {value: 'b'}], 'c', 0, 0); // 2 +bisectBy.left([], 'string', 0, 0); // 0 +bisectBy.right([], 'string', 0, 0); // 0 crossfilter.heap([], 0, 0); var heapBy = crossfilter.heap.by(t => t); diff --git a/types/crossfilter/index.d.ts b/types/crossfilter/index.d.ts index ed888f6959..a009e920dd 100644 --- a/types/crossfilter/index.d.ts +++ b/types/crossfilter/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for CrossFilter // Project: https://github.com/square/crossfilter -// Definitions by: Schmulik Raskin , Izaak Baker +// Definitions by: Schmulik Raskin , Izaak Baker , Einar Norðfjörð // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CrossFilter { @@ -15,7 +15,7 @@ declare namespace CrossFilter { permute(array: T[], index: number[]): T[]; bisect: { (array: T[], value: T, lo: number, hi: number): number; - by(value: Selector): Bisector; + by(accessor: (x: T)=> U): Bisector; } heap: { (array: T[], lo: number, hi: number): T[]; @@ -36,13 +36,13 @@ declare namespace CrossFilter { } } - export interface Bisection { - (array: T[], value: T, lo: number, hi: number): number; + export interface Bisection { + (array: T[], value: U, lo: number, hi: number): number; } - export interface Bisector extends Bisection { - left: Bisection - right: Bisection + export interface Bisector extends Bisection { + left: Bisection + right: Bisection } export interface Heap { diff --git a/types/cson/cson-tests.ts b/types/cson/cson-tests.ts index e5bdc67069..8d196e33c7 100644 --- a/types/cson/cson-tests.ts +++ b/types/cson/cson-tests.ts @@ -13,7 +13,7 @@ console.log('cson.createJSONString => %s', data); data = cson.createCSONString({hello: 'world'}); console.log('cson.createCSONString => %s', data); -var obj: Object = cson.parse(data); +var obj = cson.parse(data); console.log('cson.parse => %s', JSON.stringify(obj)); obj = cson.parseCSONString(data); diff --git a/types/cson/index.d.ts b/types/cson/index.d.ts index 72b985a82d..3366283721 100644 --- a/types/cson/index.d.ts +++ b/types/cson/index.d.ts @@ -5,27 +5,27 @@ // Create Strings -export declare function stringify(data: Object, opts?: Object, indent?: any): string; -export declare function createCSONString(data: Object, opts?: Object, next?: any): string; -export declare function createJSONString(data: Object, opts?: Object, next?: any): string; -export declare function createString(data: Object, opts?: Object, next?: any): string; +export declare function stringify(data: any, opts?: Object, indent?: any): string; +export declare function createCSONString(data: any, opts?: Object, next?: any): string; +export declare function createJSONString(data: any, opts?: Object, next?: any): string; +export declare function createString(data: any, opts?: Object, next?: any): string; // Parse Strings -export declare function parse(data: string, opts?: Object, next?: any): Object; -export declare function parseCSONString(data: string, opts?: Object, next?: any): Object; -export declare function parseJSONString(data: string, opts?: Object, next?: any): Object; -export declare function parseCSString(data: string, opts?: Object, next?: any): Object; -export declare function parseJSString(data: string, opts?: Object, next?: any): Object; -export declare function parseString(data: string, opts?: Object, next?: any): Object; +export declare function parse(data: string, opts?: Object, next?: any): any; +export declare function parseCSONString(data: string, opts?: Object, next?: any): any; +export declare function parseJSONString(data: string, opts?: Object, next?: any): any; +export declare function parseCSString(data: string, opts?: Object, next?: any): any; +export declare function parseJSString(data: string, opts?: Object, next?: any): any; +export declare function parseString(data: string, opts?: Object, next?: any): any; // Parse Files -export declare function load(filePath: string, opts?: Object, next?: any): Object; -export declare function parseCSONFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseJSONFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseCSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function parseJSFile(filePath: string, opts?: Object, next?: any): Object; +export declare function load(filePath: string, opts?: Object, next?: any): any; +export declare function parseCSONFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseJSONFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseCSFile(filePath: string, opts?: Object, next?: any): any; +export declare function parseJSFile(filePath: string, opts?: Object, next?: any): any; // Require Files -export declare function requireCSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function requireJSFile(filePath: string, opts?: Object, next?: any): Object; -export declare function requireFile(filePath: string, opts?: Object, next?: any): Object; +export declare function requireCSFile(filePath: string, opts?: Object, next?: any): any; +export declare function requireJSFile(filePath: string, opts?: Object, next?: any): any; +export declare function requireFile(filePath: string, opts?: Object, next?: any): any; diff --git a/types/css/index.d.ts b/types/css/index.d.ts index c892d5c3a2..be8f1323a0 100644 --- a/types/css/index.d.ts +++ b/types/css/index.d.ts @@ -112,7 +112,7 @@ export interface Comment extends Node { /** * The @charset at-rule. */ -export interface Charset { +export interface Charset extends Node { /** The part following @charset. */ charset?: string; } @@ -120,7 +120,7 @@ export interface Charset { /** * The @custom-media at-rule */ -export interface CustomMedia { +export interface CustomMedia extends Node { /** The ---prefixed name. */ name?: string; /** The part following the name. */ @@ -130,7 +130,7 @@ export interface CustomMedia { /** * The @document at-rule. */ -export interface Document { +export interface Document extends Node { /** The part following @document. */ document?: string; /** The vendor prefix in @document, or undefined if there is none. */ @@ -142,7 +142,7 @@ export interface Document { /** * The @font-face at-rule. */ -export interface FontFace { +export interface FontFace extends Node { /** Array of nodes with the types declaration and comment. */ declarations?: Array; } @@ -150,7 +150,7 @@ export interface FontFace { /** * The @host at-rule. */ -export interface Host { +export interface Host extends Node { /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array; } @@ -158,7 +158,7 @@ export interface Host { /** * The @import at-rule. */ -export interface Import { +export interface Import extends Node { /** The part following @import. */ import?: string; } @@ -166,7 +166,7 @@ export interface Import { /** * The @keyframes at-rule. */ -export interface KeyFrames { +export interface KeyFrames extends Node { /** The name of the keyframes rule. */ name?: string; /** The vendor prefix in @keyframes, or undefined if there is none. */ @@ -175,7 +175,7 @@ export interface KeyFrames { keyframes?: Array; } -export interface KeyFrame { +export interface KeyFrame extends Node { /** The list of "selectors" of the keyframe rule, split on commas. Each “selector” is trimmed from whitespace. */ values?: Array; /** Array of nodes with the types declaration and comment. */ @@ -185,7 +185,7 @@ export interface KeyFrame { /** * The @media at-rule. */ -export interface Media { +export interface Media extends Node { /** The part following @media. */ media?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -195,7 +195,7 @@ export interface Media { /** * The @namespace at-rule. */ -export interface Namespace { +export interface Namespace extends Node { /** The part following @namespace. */ namespace?: string; } @@ -203,7 +203,7 @@ export interface Namespace { /** * The @page at-rule. */ -export interface Page { +export interface Page extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: Array; /** Array of nodes with the types declaration and comment. */ @@ -213,7 +213,7 @@ export interface Page { /** * The @supports at-rule. */ -export interface Supports { +export interface Supports extends Node { /** The part following @supports. */ supports?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -223,16 +223,21 @@ export interface Supports { /** All at-rules. */ export type AtRule = Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; +/** + * A collection of rules + */ +export interface StyleRules { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules: Array; + /** Array of Errors. Errors collected during parsing when option silent is true. */ + parsingErrors?: Array +} + /** * The root node returned by css.parse. */ export interface Stylesheet extends Node { - stylesheet?: { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - /** Array of Errors. Errors collected during parsing when option silent is true. */ - parsingErrors?: Array - }; + stylesheet?: StyleRules; } // --------------------------------------------------------------------------------- diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index d72b3ee4ac..ce2f586d9b 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cucumber-js 2.0 +// Type definitions for cucumber-js 2.1 // Project: https://github.com/cucumber/cucumber-js // Definitions by: Abraão Alves // Jan Molak @@ -23,9 +23,7 @@ export interface TableDefinition { hashes(): Array<{ [colName: string]: string }>; } -export type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; - -export type StepDefinitionCode = (this: World, ...stepArgs: StepDefinitionParam[]) => PromiseLike | any | void; +export type StepDefinitionCode = (this: World, ...stepArgs: any[]) => any; export interface StepDefinitionOptions { timeout?: number; diff --git a/types/cypress/cypress-tests.ts b/types/cypress/cypress-tests.ts index ac987e757a..9502f1a63d 100644 --- a/types/cypress/cypress-tests.ts +++ b/types/cypress/cypress-tests.ts @@ -12,10 +12,13 @@ cy .get('.query-button') .contains('Save Form').should('have.class', 'btn'); +cy.location('host'); + cy .get('form') .find('input') - .then($input => $input.click()); + .then($input => $input.click()) + .then($input => $input.click(), {timeout: 12}); cy .wrap({ sum: (a: number, b: number, c: number) => a + b + c }) diff --git a/types/cypress/index.d.ts b/types/cypress/index.d.ts index e7f2a59447..1ffb365418 100644 --- a/types/cypress/index.d.ts +++ b/types/cypress/index.d.ts @@ -249,7 +249,8 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/location */ - location(options?: Loggable): Chainable; + location(options?: LoggableTimeoutable): Chainable; + location(key: string, options?: LoggableTimeoutable): Chainable; /** * @see https://on.cypress.io/api/log @@ -317,9 +318,9 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/route */ - route(url: string, response?: any): Chainable; - route(method: string, url: string, response?: any): Chainable; - route(fn: () => RouteOptions | RouteOptions): Chainable; + route(url: string | RegExp, response?: any): Chainable; + route(method: string, url: string | RegExp, response?: any): Chainable; + route(fn: (() => RouteOptions) | RouteOptions): Chainable; /** * @see https://on.cypress.io/api/screenshot @@ -369,7 +370,7 @@ declare namespace Cypress { /** * @see https://on.cypress.io/api/then */ - then(fn: (currentSubject: any) => any): Chainable; + then(fn: (currentSubject: any) => any, options?: Timeoutable): Chainable; /** * @see https://on.cypress.io/api/title diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index 21d6d4344b..85b3a97e46 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -178,7 +178,7 @@ declare namespace cytoscape { */ layout?: NullLayoutOptions | RandomLayoutOptions | PresetLayoutOptions | GridLayoutOptions | CircleLayoutOptions | ConcentricLayoutOptions | - BreadthFirstLayoutOptions | CoseLayoutOptions; + BreadthFirstLayoutOptions | CoseLayoutOptions | BaseLayoutOptions; /////////////////////////////////////// // initial viewport state: @@ -978,7 +978,7 @@ declare namespace cytoscape { * An analogue to run a layout on a subset of the graph exists as eles.layout(). * http://js.cytoscape.org/#cy.layout */ - layout(layout: LayoutOptions): void; + layout(layout: LayoutOptions): LayoutManipulation; /** * Get a new layout, which can be used to algorithmically * position the nodes in the graph. @@ -991,7 +991,7 @@ declare namespace cytoscape { * Note that you must call layout.run() in order for it to affect the graph. * An analogue to make a layout on a subset of the graph exists as eles.makeLayout(). */ - makeLayout(options: LayoutOptions): void; + makeLayout(options: LayoutOptions): LayoutManipulation; } /** @@ -4144,7 +4144,7 @@ declare namespace cytoscape { type LayoutOptions = NullLayoutOptions | PresetLayoutOptions | GridLayoutOptions | CircleLayoutOptions | ConcentricLayoutOptions | BreadthFirstLayoutOptions | - CoseLayoutOptions; + CoseLayoutOptions | BaseLayoutOptions; type LayoutHandler = () => void; diff --git a/types/d3-contour/index.d.ts b/types/d3-contour/index.d.ts index 789ff32a5f..1d82faae40 100644 --- a/types/d3-contour/index.d.ts +++ b/types/d3-contour/index.d.ts @@ -2,6 +2,7 @@ // Project: https://d3js.org/d3-contour/ // Definitions by: Tom Wanzek , Hugues Stefanski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Last module patch version validated against: 1.1.0 diff --git a/types/d3-dsv/d3-dsv-tests.ts b/types/d3-dsv/d3-dsv-tests.ts index 51127b7266..459fa7291b 100644 --- a/types/d3-dsv/d3-dsv-tests.ts +++ b/types/d3-dsv/d3-dsv-tests.ts @@ -21,7 +21,7 @@ const tsvTestStringWithHeader = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2. const pipedTestStringWithHeader = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; interface ParsedTestObject { - year: Date; + year: Date | null; make: string; model: string; length: number; @@ -35,8 +35,9 @@ let parseRowsMappedArray: ParsedTestObject[]; let columns: string[]; let num: number; -let date: Date; +let dateNull: Date | null; let str: string; +let strMaybe: string | undefined; // ------------------------------------------------------------------------------------------ // Test CSV @@ -50,7 +51,7 @@ parseArray = d3Dsv.csvParse(csvTestStringWithHeader); columns = parseArray.columns; -str = parseArray[0]['Year']; +strMaybe = parseArray[0]['Year']; // date = parseArray[0]['Year']; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -60,19 +61,39 @@ parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, colum const i: number = index; const c: string[] = columns; const pr: ParsedTestObject = { - year: new Date(+rr['Year'], 0, 1), - make: rr['Make'], - model: rr['Model'], - length: +rr['Length'] + year: rr['Year'] ? new Date(+rr['Year']!, 0, 1) : null, + make: rr['Make'] ? rr['Make']! : "Missing Value", + model: rr['Model'] ? rr['Model']! : "Missing Value", + length: ['Length'] ? +rr['Length']! : NaN }; return pr; }); +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: string[] = columns; + const d: number | null = rr['Year'] ? +rr['Year']! : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr['Make'] ? rr['Make']! : "Missing Value", + model: rr['Model'] ? rr['Model']! : "Missing Value", + length: ['Length'] ? +rr['Length']! : NaN + } + : undefined + ) + : null; + return pr; +}); + columns = parseMappedArray.columns; -date = parseMappedArray[0].year; -str = parseMappedArray[0].make; -str = parseMappedArray[0].model; +dateNull = parseMappedArray[0].year; +strMaybe = parseMappedArray[0].make; +strMaybe = parseMappedArray[0].model; num = parseMappedArray[0].length; // csvParseRows(...) ============================================================================ @@ -81,7 +102,7 @@ num = parseMappedArray[0].length; parseRowsArray = d3Dsv.csvParseRows(csvTestString); -str = parseRowsArray[0][0]; // 'Year' of first row +strMaybe = parseRowsArray[0][0]; // 'Year' of first row // date = parseRowsArray[0][0]; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -89,18 +110,25 @@ str = parseRowsArray[0][0]; // 'Year' of first row parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { const rr: string[] = rawRow; const i: number = index; - const pr: ParsedTestObject = { - year: new Date(+rr[0], 0, 1), - make: rr[1], - model: rr[2], - length: +rr[3] - }; + const d: number | null = rr[0].length ? +rr[0] : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr[1].length ? rr[1] : "Missing Value", + model: rr[2].length ? rr[2] : "Missing Value", + length: rr[3].length ? +rr[3] : NaN + } + : undefined + ) + : null; return pr; }); -date = parseRowsMappedArray[0].year; -str = parseRowsMappedArray[0].make; -str = parseRowsMappedArray[0].model; +dateNull = parseRowsMappedArray[0].year; +strMaybe = parseRowsMappedArray[0].make; +strMaybe = parseRowsMappedArray[0].model; num = parseRowsMappedArray[0].length; // csvFormat(...) ============================================================================ @@ -111,7 +139,7 @@ str = d3Dsv.csvFormat(parseRowsMappedArray, columns); // csvFormatRows(...) ======================================================================== str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ - d.year.getFullYear().toString(), + d.year ? d.year.getFullYear().toString() : '', d.make, d.model, d.length.toString() @@ -129,7 +157,7 @@ parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader); columns = parseArray.columns; -str = parseArray[0]['Year']; +strMaybe = parseArray[0]['Year']; // date = parseArray[0]['Year']; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -138,20 +166,27 @@ parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, colum const rr: d3Dsv.DSVRowString = rawRow; const i: number = index; const c: string[] = columns; - const pr: ParsedTestObject = { - year: new Date(+rr['Year'], 0, 1), - make: rr['Make'], - model: rr['Model'], - length: +rr['Length'] - }; + const d: number | null = rr['Year'] ? +rr['Year']! : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr['Make'] ? rr['Make']! : "Missing Value", + model: rr['Model'] ? rr['Model']! : "Missing Value", + length: ['Length'] ? +rr['Length']! : NaN + } + : undefined + ) + : null; return pr; }); columns = parseMappedArray.columns; -date = parseMappedArray[0].year; -str = parseMappedArray[0].make; -str = parseMappedArray[0].model; +dateNull = parseMappedArray[0].year; +strMaybe = parseMappedArray[0].make; +strMaybe = parseMappedArray[0].model; num = parseMappedArray[0].length; // tsvParseRows(...) ============================================================================ @@ -160,7 +195,7 @@ num = parseMappedArray[0].length; parseRowsArray = d3Dsv.tsvParseRows(tsvTestString); -str = parseRowsArray[0][0]; // 'Year' of first row +strMaybe = parseRowsArray[0][0]; // 'Year' of first row // date = parseRowsArray[0][0]; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -168,18 +203,25 @@ str = parseRowsArray[0][0]; // 'Year' of first row parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { const rr: string[] = rawRow; const i: number = index; - const pr: ParsedTestObject = { - year: new Date(+rr[0], 0, 1), - make: rr[1], - model: rr[2], - length: +rr[3] - }; + const d: number | null = rr[0].length ? +rr[0] : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr[1].length ? rr[1] : "Missing Value", + model: rr[2].length ? rr[2] : "Missing Value", + length: rr[3].length ? +rr[3] : NaN + } + : undefined + ) + : null; return pr; }); -date = parseRowsMappedArray[0].year; -str = parseRowsMappedArray[0].make; -str = parseRowsMappedArray[0].model; +dateNull = parseRowsMappedArray[0].year; +strMaybe = parseRowsMappedArray[0].make; +strMaybe = parseRowsMappedArray[0].model; num = parseRowsMappedArray[0].length; // tsvFormat(...) ============================================================================ @@ -190,7 +232,7 @@ str = d3Dsv.tsvFormat(parseRowsMappedArray, columns); // tsvFormatRows(...) ======================================================================== str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [ - d.year.getFullYear().toString(), + d.year ? d.year.getFullYear().toString() : '', d.make, d.model, d.length.toString() @@ -213,7 +255,7 @@ parseArray = dsv.parse(pipedTestStringWithHeader); columns = parseArray.columns; -str = parseArray[0]['Year']; +strMaybe = parseArray[0]['Year']; // date = parseArray[0]['Year']; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -222,20 +264,27 @@ parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) const rr: d3Dsv.DSVRowString = rawRow; const i: number = index; const c: string[] = columns; - const pr: ParsedTestObject = { - year: new Date(+rr['Year'], 0, 1), - make: rr['Make'], - model: rr['Model'], - length: +rr['Length'] - }; + const d: number | null = rr['Year'] ? +rr['Year']! : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr['Make'] ? rr['Make']! : "Missing Value", + model: rr['Model'] ? rr['Model']! : "Missing Value", + length: ['Length'] ? +rr['Length']! : NaN + } + : undefined + ) + : null; return pr; }); columns = parseMappedArray.columns; -date = parseMappedArray[0].year; -str = parseMappedArray[0].make; -str = parseMappedArray[0].model; +dateNull = parseMappedArray[0].year; +strMaybe = parseMappedArray[0].make; +strMaybe = parseMappedArray[0].model; num = parseMappedArray[0].length; // parseRows(...) ============================================================================ @@ -244,7 +293,7 @@ num = parseMappedArray[0].length; parseRowsArray = dsv.parseRows(pipedTestString); -str = parseRowsArray[0][0]; // 'Year' of first row +strMaybe = parseRowsArray[0][0]; // 'Year' of first row // date = parseRowsArray[0][0]; // fails, return value is string // with row mapper --------------------------------------------------------------------------- @@ -252,18 +301,25 @@ str = parseRowsArray[0][0]; // 'Year' of first row parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { const rr: string[] = rawRow; const i: number = index; - const pr: ParsedTestObject = { - year: new Date(+rr[0], 0, 1), - make: rr[1], - model: rr[2], - length: +rr[3] - }; + const d: number | null = rr[0].length ? +rr[0] : null; + const pr: ParsedTestObject | null | undefined = d !== null + ? ( + d > 1997 + ? { + year: new Date(d, 0, 1), + make: rr[1].length ? rr[1] : "Missing Value", + model: rr[2].length ? rr[2] : "Missing Value", + length: rr[3].length ? +rr[3] : NaN + } + : undefined + ) + : null; return pr; }); -date = parseRowsMappedArray[0].year; -str = parseRowsMappedArray[0].make; -str = parseRowsMappedArray[0].model; +dateNull = parseRowsMappedArray[0].year; +strMaybe = parseRowsMappedArray[0].make; +strMaybe = parseRowsMappedArray[0].model; num = parseRowsMappedArray[0].length; // format(...) ============================================================================ @@ -274,7 +330,7 @@ str = dsv.format(parseRowsMappedArray, columns); // formatRows(...) ======================================================================== str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [ - d.year.getFullYear().toString(), + d.year ? d.year.getFullYear().toString() : '', d.make, d.model, d.length.toString() diff --git a/types/d3-dsv/index.d.ts b/types/d3-dsv/index.d.ts index eaf9797b02..80b2ebc54e 100644 --- a/types/d3-dsv/index.d.ts +++ b/types/d3-dsv/index.d.ts @@ -3,19 +3,35 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.0.30 + // ------------------------------------------------------------------------------------------ // Shared Types and Interfaces // ------------------------------------------------------------------------------------------ +/** + * An object representing a DSV parsed row with values represented as strings. + */ export interface DSVRowString { - [key: string]: string; + [key: string]: string | undefined; } +/** + * An object representing a DSV parsed row with values represented as an arbitrary datatype, depending + * on the performed parsed row mapping. + */ export interface DSVRowAny { [key: string]: any; } +/** + * An array object representing all parsed rows. The array is enhanced with a property listing + * the names of the parsed columns. + */ export interface DSVParsedArray extends Array { + /** + * List of column names. + */ columns: string[]; } @@ -25,20 +41,108 @@ export interface DSVParsedArray extends Array { // csvParse(...) ============================================================================ +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike csvParseRows, this method requires that the first line of the CSV content contains a comma-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to dsvFormat(",").parse. + * + * @param csvString A string, which must be in the comma-separated values format. + */ export function csvParse(csvString: string): DSVParsedArray; -export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike csvParseRows, this method requires that the first line of the CSV content contains a comma-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to dsvFormat(",").parse. + * + * @param csvString A string, which must be in the comma-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csvParse( + csvString: string, + row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null +): DSVParsedArray; // csvParseRows(...) ======================================================================== +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * Equivalent to dsvFormat(",").parseRows. + * + * @param csvString A string, which must be in the comma-separated values format. + */ export function csvParseRows(csvString: string): string[][]; -export function csvParseRows(csvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; +/** + * Parses the specified string, which must be in the comma-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * Equivalent to dsvFormat(",").parseRows. + * + * @param csvString A string, which must be in the comma-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function csvParseRows( + csvString: string, + row: (rawRow: string[], index: number) => ParsedRow | undefined | null +): ParsedRow[]; // csvFormat(...) ============================================================================ +/** + * Formats the specified array of object rows as comma-separated values, returning a string. + * This operation is the inverse of csvParse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the comma-delimiter. + * Values that contain either the comma-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * Equivalent to dsvFormat(",").format. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ export function csvFormat(rows: DSVRowAny[], columns?: string[]): string; // csvFormatRows(...) ======================================================================== +/** + * Formats the specified array of array of string rows as comma-separated values, returning a string. + * This operation is the reverse of csvParseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the comma-delimiter. + * Values that contain either the comma-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * Equivalent to dsvFormat(",").formatRows. + * + * @param rows An array of array of string rows. + */ export function csvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ @@ -47,33 +151,209 @@ export function csvFormatRows(rows: string[][]): string; // tsvParse(...) ============================================================================ +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike tsvParseRows, this method requires that the first line of the TSV content contains a tab-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to dsvFormat("\t").parse. + * + * @param tsvString A string, which must be in the tab-separated values format. + */ export function tsvParse(tsvString: string): DSVParsedArray; -export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow): DSVParsedArray; +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. + * + * Unlike tsvParseRows, this method requires that the first line of the TSV content contains a tab-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * Equivalent to dsvFormat("\t").parse. + * + * @param tsvString A string, which must be in the tab-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsvParse( + tsvString: string, + row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow | undefined | null +): DSVParsedArray; // tsvParseRows(...) ======================================================================== +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * Equivalent to dsvFormat("\t").parseRows. + * + * @param tsvString A string, which must be in the tab-separated values format. + */ export function tsvParseRows(tsvString: string): string[][]; -export function tsvParseRows(tsvString: string, row: (rawRow: string[], index: number) => MappedRow): MappedRow[]; +/** + * Parses the specified string, which must be in the tab-separated values format, returning an array of arrays representing the parsed rows. + * + * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * Equivalent to dsvFormat("\t").parseRows. + * + * @param tsvString A string, which must be in the tab-separated values format. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ +export function tsvParseRows( + tsvString: string, + row: (rawRow: string[], index: number) => MappedRow | undefined | null +): MappedRow[]; // tsvFormat(...) ============================================================================ +/** + * Formats the specified array of object rows as tab-separated values, returning a string. + * This operation is the inverse of tsvParse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the tab-delimiter. + * Values that contain either the tab-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * Equivalent to dsvFormat("\t").format. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ export function tsvFormat(rows: DSVRowAny[], columns?: string[]): string; // tsvFormatRows(...) ======================================================================== +/** + * Formats the specified array of array of string rows as tab-separated values, returning a string. + * This operation is the reverse of tsvParseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the tab-delimiter. + * Values that contain either the tab-delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * Equivalent to dsvFormat("\t").formatRows. + * + * @param rows An array of array of string rows. + */ export function tsvFormatRows(rows: string[][]): string; // ------------------------------------------------------------------------------------------ // DSV Generalized Parsers and Formatters // ------------------------------------------------------------------------------------------ +/** + * A DSV parser and formatter + */ export interface DSV { + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. + * + * Unlike dsv.parseRows, this method requires that the first line of the DSV content contains a delimiter-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + */ parse(dsvString: string): DSVParsedArray; - parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DSVParsedArray; + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. + * + * Unlike dsv.parseRows, this method requires that the first line of the DSV content contains a delimiter-separated list of column names; + * these column names become the attributes on the returned objects. + * + * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), + * the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ + parse( + dsvString: string, + row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + ): DSVParsedArray; + + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows. + * + * Unlike dsv.parse, this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. + * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + */ parseRows(dsvString: string): string[][]; - parseRows(dsvString: string, row: (rawRow: string[], index: number) => ParsedRow): ParsedRow[]; + /** + * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows. + * + * Unlike dsv.parse, this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. + * Each row is represented as an array rather than an object. Rows may have variable length. + * + * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. + * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) + * starting at zero for the first row, and the array of column names. If the returned value is null or undefined, + * the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. + * In effect, row is similar to applying a map and filter operator to the returned rows. + */ + parseRows( + dsvString: string, + row: (rawRow: string[], index: number) => ParsedRow | undefined | null + ): ParsedRow[]; + + /** + * Formats the specified array of object rows as delimiter-separated values, returning a string. + * This operation is the inverse of dsv.parse. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the delimiter (such as a comma, ,). + * Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; + * the order of columns is nondeterministic. + * + * @param rows Array of object rows. + * @param columns An array of strings representing the column names. + */ format(rows: DSVRowAny[], columns?: string[]): string; + + /** + * Formats the specified array of array of string rows as delimiter-separated values, returning a string. + * This operation is the reverse of dsv.parseRows. Each row will be separated by a newline (\n), + * and each column within each row will be separated by the delimiter (such as a comma, ,). + * Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes. + * + * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. + * If you like, you can also array.concat this result with an array of column names to generate the first row. + * + * @param rows An array of array of string rows. + */ formatRows(rows: string[][]): string; } +/** + * Constructs a new DSV parser and formatter for the specified delimiter. + * + * @param delimiter A delimiter character. The delimiter must be a single character (i.e., a single 16-bit code unit); + * so, ASCII delimiters are fine, but emoji delimiters are not. + */ export function dsvFormat(delimiter: string): DSV; diff --git a/types/d3-dsv/tsconfig.json b/types/d3-dsv/tsconfig.json index 82e3ef399f..400095c38d 100644 --- a/types/d3-dsv/tsconfig.json +++ b/types/d3-dsv/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "d3-dsv-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 349303df71..7efbb72010 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Last module patch version validated against: 1.9.0 @@ -35,7 +36,10 @@ export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere; export interface ExtendedGeometryCollection { type: string; bbox?: number[]; - crs?: GeoJSON.CoordinateReferenceSystem; + crs?: { + type: string; + properties: any; + }; geometries: GeometryType[]; } diff --git a/types/d3-selection-multi/d3-selection-multi-tests.ts b/types/d3-selection-multi/d3-selection-multi-tests.ts index 515dd8e92e..f40c3723f2 100644 --- a/types/d3-selection-multi/d3-selection-multi-tests.ts +++ b/types/d3-selection-multi/d3-selection-multi-tests.ts @@ -34,7 +34,7 @@ selection = selection.attrs({ }); // Function that returns a map -selection = selection.attrs(function(d, i, g) { +selection = selection.attrs(function(d, i, g): {} | { id: string } { const that: HTMLAnchorElement = this; const index: number = i; const group: HTMLAnchorElement[] | ArrayLike = g; @@ -89,7 +89,7 @@ selection = selection.properties({ }); // Function that returns an object -selection = selection.properties(function(d, i, g) { +selection = selection.properties(function(d, i, g): {} | { href: string } { const that: HTMLAnchorElement = this; const index: number = i; const group: HTMLAnchorElement[] | ArrayLike = g; @@ -118,7 +118,7 @@ transition = transition.attrs({ }); // Function that returns a map -transition = transition.attrs(function(d, i, g) { +transition = transition.attrs(function(d, i, g): {} | { id: string } { const that: HTMLAnchorElement = this; const index: number = i; const group: HTMLAnchorElement[] | ArrayLike = g; diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index 96d421f828..6019084be2 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1036,6 +1036,19 @@ positions = d3Selection.touches(svg, changedTouches); positions = d3Selection.touches(g, changedTouches); positions = d3Selection.touches(h, changedTouches); +// clientPoint() --------------------------------------------------------------------- + +let clientPoint: [number, number]; +declare let mEvt: MouseEvent; +declare let tEvt: Touch; +declare let msgEvt: MSGestureEvent; +declare let customEvt: {clientX: number, clientY: number}; // minimally conforming object + +clientPoint = d3Selection.clientPoint(svg, mEvt); +clientPoint = d3Selection.clientPoint(g, tEvt); +clientPoint = d3Selection.clientPoint(h, msgEvt); +clientPoint = d3Selection.clientPoint(h, customEvt); + // --------------------------------------------------------------------------------------- // Tests of style // --------------------------------------------------------------------------------------- diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts index abbb14db0f..b5231f37c2 100644 --- a/types/d3-selection/index.d.ts +++ b/types/d3-selection/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for D3JS d3-selection module 1.1 +// Type definitions for D3JS d3-selection module 1.2 // Project: https://github.com/d3/d3-selection/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1 +// Last module patch version validated against: 1.2.0 // -------------------------------------------------------------------------- // Shared Type Definitions and Interfaces @@ -44,6 +44,14 @@ export interface EnterElement { */ export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement; +/** + * A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export interface ClientPointEvent { + clientX: number; + clientY: number; +} + /** * Interface for optional parameters map, when dispatching custom events * on a selection @@ -670,7 +678,8 @@ export interface Selection; /** - * Return the exit selection: existing DOM elements in the selection for which no new datum was found. - * The exit selection is determined by the previous selection.data, and is thus empty until the selection is - * joined to data. If the exit selection is retrieved more than once after a data join, subsequent calls return - * the empty selection. + * Returns the exit selection: existing DOM elements in the selection for which no new datum was found. + * (The exit selection is empty for selections not returned by selection.data.) * * IMPORTANT: The generic refers to the type of the old datum associated with the exit selection elements. * Ensure you set the generic to the correct type, if you need to access the data on the exit selection in @@ -972,6 +979,16 @@ export function touch(container: ContainerElement, touches: TouchList, identifie */ export function touches(container: ContainerElement, touches?: TouchList): Array<[number, number]>; +/** + * Returns the x and y coordinates of the specified event relative to the specified container. + * (The event may also be a touch.) The container may be an HTML or SVG container element, such as a G element or an SVG element. + * The coordinates are returned as a two-element array of numbers [x, y]. + * + * @param container Container element relative to which coordinates are calculated. + * @param event A User interface event (e.g. mouse event, touch or MSGestureEvent) with captured clientX and clientY properties. + */ +export function clientPoint(container: ContainerElement, event: ClientPointEvent): [number, number]; + // --------------------------------------------------------------------------- // style // --------------------------------------------------------------------------- diff --git a/types/d3-transition/index.d.ts b/types/d3-transition/index.d.ts index 1ff8d46d04..eb60cec49f 100644 --- a/types/d3-transition/index.d.ts +++ b/types/d3-transition/index.d.ts @@ -569,7 +569,7 @@ export interface Transition(name: string): Transition; +export function transition(name?: string): Transition; /** * Returns a new transition from an existing transition. diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 8ff3f566f5..669b4af8ff 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -121,6 +121,26 @@ let svgZoom: d3Zoom.ZoomBehavior; svgZoom = d3Zoom.zoom(); +// constrain() ------------------------------------------------------------- + +// chainable +svgZoom = svgZoom.constrain((transform, extent, translateExtent) => { + const t: d3Zoom.ZoomTransform = transform; + const ve: [[number, number], [number, number]] = extent; + const te: [[number, number], [number, number]] = translateExtent; + const dx0 = t.invertX(ve[0][0]) - te[0][0]; + const dx1 = t.invertX(ve[1][0]) - te[1][0]; + const dy0 = transform.invertY(ve[0][1]) - te[0][1]; + const dy1 = transform.invertY(ve[1][1]) - te[1][1]; + return t.translate( + dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1), + dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1) + ); +}); + +let constraintFn: (transform: d3Zoom.ZoomTransform, extent: [[number, number], [number, number]], translateExtent: [[number, number], [number, number]]) => d3Zoom.ZoomTransform; +constraintFn = svgZoom.constrain(); + // filter() ---------------------------------------------------------------- // chainable diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index 1ca39261a5..cf9b1ac89d 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.6 +// Type definitions for d3JS d3-zoom module 1.7 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.6.0 +// Last module patch version validated against: 1.7.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -499,6 +499,19 @@ export interface ZoomBehavior, k: ValueFn): void; + /** + * Returns the current constraint function. + * The default implementation attempts to ensure that the viewport extent does not go outside the translate extent. + */ + constrain(): (transform: ZoomTransform, extent: [[number, number], [number, number]], translateExtent: [[number, number], [number, number]]) => ZoomTransform; + /** + * Sets the transform constraint function to the specified function and returns the zoom behavior. + * + * @param constraint A constraint function which returns a transform given the current transform, viewport extent and translate extent. + * The default implementation attempts to ensure that the viewport extent does not go outside the translate extent. + */ + constrain(constraint: ((transform: ZoomTransform, extent: [[number, number], [number, number]], translateExtent: [[number, number], [number, number]]) => ZoomTransform)): this; + /** * Returns the current filter function. */ @@ -647,7 +660,7 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace d3; diff --git a/types/d3/v3/index.d.ts b/types/d3/v3/index.d.ts index 90afdd3938..0fbc7502b0 100644 --- a/types/d3/v3/index.d.ts +++ b/types/d3/v3/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* tslint:disable */ - // Latest patch version of module validated against: 3.5.17 export = d3; diff --git a/types/d3kit/index.d.ts b/types/d3kit/index.d.ts index c374a59501..5a07821700 100644 --- a/types/d3kit/index.d.ts +++ b/types/d3kit/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/twitter/d3kit // Definitions by: Morgan Benton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/dagre-d3/index.d.ts b/types/dagre-d3/index.d.ts index 9a14ecbae4..dc0d8ad639 100644 --- a/types/dagre-d3/index.d.ts +++ b/types/dagre-d3/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/cpettitt/dagre-d3 // Definitions by: Mark Wong Siang Kai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as d3 from "d3"; import * as dagre from "dagre"; diff --git a/types/dagre/dagre-tests.ts b/types/dagre/dagre-tests.ts index ae81c2c896..a29cf0128a 100644 --- a/types/dagre/dagre-tests.ts +++ b/types/dagre/dagre-tests.ts @@ -1,8 +1,39 @@ -const gDagre = new dagre.graphlib.Graph(); +const gDagre = new dagre.graphlib.Graph({compound: true, multigraph: false}); gDagre.setGraph({}) .setDefaultEdgeLabel(() => ({})) + .setDefaultNodeLabel(() => ({})) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); dagre.layout(gDagre); + +gDagre.edge({v: 'b', w: 'c'}); +gDagre.hasEdge({v: 'b', w: 'c'}); +gDagre.inEdges('c'); +gDagre.outEdges('c'); + +gDagre.setParent('a', 'b'); +gDagre.children('b'); +gDagre.hasNode('d'); +gDagre.neighbors('c'); +gDagre.node({}); +gDagre.parent('a'); +gDagre.predecessors('d'); +gDagre.successors('b'); + +gDagre.removeEdge('c', 'd').removeNode('d'); + +dagre.graphlib.json.read(dagre.graphlib.json.write(gDagre)); + +dagre.graphlib.alg.components(gDagre); +dagre.graphlib.alg.dijkstra(gDagre, 'a', (edge) => 5); +dagre.graphlib.alg.dijkstraAll(gDagre); +dagre.graphlib.alg.findCycles(gDagre); +dagre.graphlib.alg.floydWarchall(gDagre); +dagre.graphlib.alg.isAcyclic(gDagre); +dagre.graphlib.alg.postorder(gDagre, 'a'); +dagre.graphlib.alg.preorder(gDagre, ['b', 'c']); +dagre.graphlib.alg.prim(gDagre); +dagre.graphlib.alg.tarjam(gDagre); +dagre.graphlib.alg.topsort(gDagre); diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 55d98b0535..6c5e5e00ec 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Qinfeng Chen // Lisa Vallfors // Pete Vilter +// David Newell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -10,24 +11,69 @@ export as namespace dagre; export namespace graphlib { class Graph { - edges(): Edge[]; - edge(id: any): any; - nodes(): string[]; - node(id: any): any; - setDefaultEdgeLabel(callback: string|(() => string|object)): Graph; - setDefaultNodeLabel(callback: string|(() => string|object)): Graph; - setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; - setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; - setGraph(label: GraphLabel): Graph; - setNode(id: string, node: { [key: string]: any }): Graph; - graph(): GraphLabel; - constructor(opt?: {directed?: boolean, multigraph?: boolean, compound?: boolean}); - setParent(name: string, parentName: string): void; + + graph(): GraphLabel; + isDirected(): boolean; + isMultiGraph(): boolean; + setGraph(label: GraphLabel): Graph; + + edge(edgeObj: Edge): GraphEdge; + edge(outNodeName: string, inNodeName: string, name?: string): GraphEdge; + edgeCount(): number; + edges(): Edge[]; + hasEdge(edgeObj: Edge): boolean; + hasEdge(outNodeName: string, inNodeName: string, name?: string): boolean; + inEdges(inNodeName: string, outNodeName?: string): Edge[]|undefined; + outEdges(outNodeName: string, inNodeName?: string): Edge[]|undefined; + removeEdge(outNodeName: string, inNodeName: string): Graph; + setDefaultEdgeLabel(callback: string|((edge: Edge) => string|Label)): Graph; + setEdge(params: Edge, value?: string|{[key: string]: any}): Graph; + setEdge(sourceId: string, targetId: string, value?: string|Label, name?: string): Graph; + + children(parentName: string): string|undefined; hasNode(name: string): boolean; + neighbors(name: string): Node[]|undefined; + node(id: string|Label): Node; + nodeCount(): number; + nodes(): string[]; + parent(childName: string): string|undefined; + predecessors(name: string): Node[]|undefined; + removeNode(name: string): Graph; + setDefaultNodeLabel(callback: string|((nodeId: string) => string|Label)): Graph; + setNode(name: string, label: string|Label): Graph; + setParent(childName: string, parentName: string): void; + sinks(): Node[]; + sources(): Node[]; + successors(name: string): Node[]|undefined; + } + + namespace json { + function read(graph: any): Graph; + function write(graph: Graph): any; + } + + namespace alg { + function components(graph: Graph): string[][]; + function dijkstra(graph: Graph, source: string, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function dijkstraAll(graph: Graph, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function findCycles(graph: Graph): string[][]; + function floydWarchall(graph: Graph, weightFn?: WeightFn, edgeFn?: EdgeFn): any; + function isAcyclic(graph: Graph): boolean; + function postorder(graph: Graph, nodeNames: string|string[]): string[]; + function preorder(graph: Graph, nodeNames: string|string[]): string[]; + function prim(graph: Graph, weightFn?: WeightFn): Graph; + function tarjam(graph: Graph): string[][]; + function topsort(graph: Graph): string[]; } } +export interface Label { + [key: string]: any; +} +export type WeightFn = (edge: Edge) => number; +export type EdgeFn = (outNodeName: string) => GraphEdge[]; + export interface GraphLabel { width?: number; height?: number; @@ -43,10 +89,37 @@ export interface GraphLabel { ranker?: string; } -export function layout(graph: graphlib.Graph): void; +export interface NodeConfig { + width?: number; + height?: number; +} + +export interface EdgeConfig { + minlen: number; + weight: number; + width: number; + height: number; + lablepos: 'l'|'c'|'r'; + labeloffest: number; +} + +export function layout(graph: graphlib.Graph, layout?: GraphLabel&NodeConfig&EdgeConfig): void; export interface Edge { v: string; w: string; name?: string; } + +export interface GraphEdge { + points: Array<{x: number, y: number}>; + [key: string]: any; +} + +export interface Node { + x: number; + y: number; + width: number; + height: number; + [key: string]: any; +} diff --git a/types/datadog-metrics/datadog-metrics-tests.ts b/types/datadog-metrics/datadog-metrics-tests.ts index f783e22b8e..ffbeccda89 100644 --- a/types/datadog-metrics/datadog-metrics-tests.ts +++ b/types/datadog-metrics/datadog-metrics-tests.ts @@ -1,9 +1,12 @@ import metrics = require('datadog-metrics'); metrics.init({ host: 'myhost', prefix: 'myapp.' }); metrics.gauge('mygauge', 42); +metrics.gauge('mykey', 11, ['a', 'b', 'c'], Date.now()); metrics.increment('test.requests_served'); metrics.increment('test.awesomeness_factor', 10); -metrics.histogram('test.service_time', 0.248); +metrics.increment('test.service_time', 0.248); +metrics.histogram('mykey', 11, ['a', 'b', 'c'], Date.now()); +metrics.histogram('mykey', 11, ['a', 'b', 'c'], Date.now()); metrics.flush(); metrics.flush(() => {}); metrics.flush(() => {}, err => {}); @@ -16,9 +19,12 @@ const metricsLogger = new metrics.BufferedMetricsLogger({ defaultTags: ['env:staging', 'region:us-east-1'] }); metricsLogger.gauge('mygauge', 42); +metricsLogger.gauge('mykey', 11, ['a', 'b', 'c'], Date.now()); metricsLogger.increment('test.requests_served'); metricsLogger.increment('test.awesomeness_factor', 10); +metricsLogger.increment('mykey', 11, ['a', 'b', 'c'], Date.now()); metricsLogger.histogram('test.service_time', 0.248); +metricsLogger.histogram('mykey', 11, ['a', 'b', 'c'], Date.now()); metricsLogger.flush(); metricsLogger.flush(() => {}); metricsLogger.flush(() => {}, err => {}); diff --git a/types/datadog-metrics/index.d.ts b/types/datadog-metrics/index.d.ts index 43ab6f440a..2d7c910eba 100644 --- a/types/datadog-metrics/index.d.ts +++ b/types/datadog-metrics/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for datadog-metrics 0.4 +// Type definitions for datadog-metrics 0.6 // Project: https://github.com/dbader/node-datadog-metrics // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -44,21 +44,21 @@ export class BufferedMetricsLogger { * the metric. This should be used for sum values such as total hard disk space, * process uptime, total number of active users, or number of rows in a database table. */ - gauge(key: string, value: number, ...tags: string[]): void; + gauge(key: string, value: number, tags?: string[], timestamp?: number): void; /** * Increment the counter by the given value (or 1 by default). Optionally, specify a * list of tags to associate with the metric. This is useful for counting things such * as incrementing a counter each time a page is requested. */ - increment(key: string, value?: number, ...tags: string[]): void; + increment(key: string, value?: number, tags?: string[], timestamp?: number): void; /** * Sample a histogram value. Histograms will produce metrics that describe the distribution * of the recorded values, namely the minimum, maximum, average, count and the 75th, 85th, * 95th and 99th percentiles. Optionally, specify a list of tags to associate with the metric. */ - histogram(key: string, value: number, ...tags: string[]): void; + histogram(key: string, value: number, tags?: string[], timestamp?: number): void; /** * Calling flush sends any buffered metrics to DataDog. Unless you set flushIntervalSeconds @@ -77,21 +77,21 @@ export function init(options: BufferedMetricsLoggerOptions): void; * the metric. This should be used for sum values such as total hard disk space, * process uptime, total number of active users, or number of rows in a database table. */ -export function gauge(key: string, value: number, ...tags: string[]): void; +export function gauge(key: string, value: number, tags?: string[], timestamp?: number): void; /** * Increment the counter by the given value (or 1 by default). Optionally, specify a * list of tags to associate with the metric. This is useful for counting things such * as incrementing a counter each time a page is requested. */ -export function increment(key: string, value?: number, ...tags: string[]): void; +export function increment(key: string, value?: number, tags?: string[], timestamp?: number): void; /** * Sample a histogram value. Histograms will produce metrics that describe the distribution * of the recorded values, namely the minimum, maximum, average, count and the 75th, 85th, * 95th and 99th percentiles. Optionally, specify a list of tags to associate with the metric. */ -export function histogram(key: string, value: number, ...tags: string[]): void; +export function histogram(key: string, value: number, tags?: string[], timestamp?: number): void; /** * Calling flush sends any buffered metrics to DataDog. Unless you set flushIntervalSeconds diff --git a/types/datatables.net-rowreorder/index.d.ts b/types/datatables.net-rowreorder/index.d.ts index 110da7a747..c95c7a1fb9 100644 --- a/types/datatables.net-rowreorder/index.d.ts +++ b/types/datatables.net-rowreorder/index.d.ts @@ -2,7 +2,7 @@ // Project: http://datatables.net/extensions/rowreorder/ // Definitions by: Vincent Biret // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /// diff --git a/types/datatables.net-select/index.d.ts b/types/datatables.net-select/index.d.ts index 201d00ba27..e24f6b8ab6 100644 --- a/types/datatables.net-select/index.d.ts +++ b/types/datatables.net-select/index.d.ts @@ -2,6 +2,8 @@ // Project: https://datatables.net/extensions/select/ // Definitions by: Jared Szechy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + /// /// diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index f01ffd59a3..4fddcc4fbd 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -25,6 +25,7 @@ declare namespace daterangepicker { startDate: moment.Moment; endDate: moment.Moment; + container: JQuery; setStartDate(date: Date | moment.Moment | string): void; setEndDate(date: Date | moment.Moment | string): void; diff --git a/types/dc/index.d.ts b/types/dc/index.d.ts index 7d893baf3e..62fbd8330c 100644 --- a/types/dc/index.d.ts +++ b/types/dc/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for DCJS // Project: https://github.com/dc-js/dc.js -// Definitions by: hans windhoff , matt traynham +// Definitions by: hans windhoff +// matt traynham +// matthias jobst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files @@ -49,8 +51,9 @@ declare namespace dc { format: Accessor; } + // http://dc-js.github.io/dc.js/docs/html/dc.units.html export interface UnitFunction { - (start: number, end: number, domain?: Array): number|Array; + (start: number|Date, end: number|Date, domain?: number|Array): number | Array; } export interface FloatPointUnits { @@ -135,12 +138,13 @@ declare namespace dc { minHeight: IGetSet; dimension: IGetSet; data: IGetSetComputed<(group: any) => Array, Array, T>; - group: IGetSet; + // http://dc-js.github.io/dc.js/docs/html/dc.baseMixin.html#group__anchor + group: IBiGetSet; ordering: IGetSet, T>; filterAll(): void; - select(selector: d3.Selection|string): d3.Selection; - selectAll(selector: d3.Selection|string): d3.Selection; - anchor(anchor: BaseMixin|d3.Selection|string, chartGroup?: string): d3.Selection; + select(selector: d3.Selection | string): d3.Selection; + selectAll(selector: d3.Selection | string): d3.Selection; + anchor(anchor: BaseMixin | d3.Selection | string, chartGroup?: string): d3.Selection; anchorName(): string; svg: IGetSet, d3.Selection>; resetSvg(): void; @@ -196,10 +200,11 @@ declare namespace dc { } export interface ColorMixin { - colors: IGetSet | Scale, T>; - ordinalColors(r: Array): void; - linearColors(r: Array): void; - colorAccessor: IGetSet, T>; + // http://dc-js.github.io/dc.js/docs/html/dc.colorMixin.html + colors: IGetSet | Scale | string, T>; + ordinalColors(r: Array): T; + linearColors(r: Array): T; + colorAccessor: IGetSet, T>; colorDomain: IGetSet, T>; calculateColorDomain(): void; getColor(datum: any, index?: number): string; @@ -291,7 +296,7 @@ declare namespace dc { dashStyle: IGetSet, LineChart>; renderArea: IGetSet; dotRadius: IGetSet; - renderDataPoints: IGetSet; + renderDataPoints: IGetSet; } export interface DataCountWidgetHTML { @@ -307,7 +312,7 @@ declare namespace dc { export interface DataTableWidget extends BaseMixin { size: IGetSet; showGroups: IGetSet; - columns: IGetSet|Columns>, DataTableWidget>; + columns: IGetSet | Columns>, DataTableWidget>; sortBy: IGetSet, DataTableWidget>; order: IGetSet<(a: any, b: any) => number, DataTableWidget>; } @@ -336,7 +341,7 @@ declare namespace dc { rightYAxis: IGetSet>; } - export interface CompositeChart extends ICompositeChart {} + export interface CompositeChart extends ICompositeChart { } export interface SeriesChart extends ICompositeChart { chart: IGetSet<(c: any) => BaseMixin, SeriesChart>; @@ -444,11 +449,16 @@ declare namespace dc { round: Round; utils: Utils; + // http://dc-js.github.io/dc.js/docs/html/core.js.html, Line 20 + version: string; + legend(): Legend; pieChart(parent: string, chartGroup?: string): PieChart; - barChart(parent: string, chartGroup?: string): BarChart; - lineChart(parent: string, chartGroup?: string): LineChart; + // http://dc-js.github.io/dc.js/docs/html/dc.barChart.html + barChart(parent: string | CompositeChart, chartGroup?: string): BarChart; + // http://dc-js.github.io/dc.js/docs/html/dc.lineChart.html + lineChart(parent: string | CompositeChart, chartGroup?: string): LineChart; dataCount(parent: string, chartGroup?: string): DataCountWidget; dataTable(parent: string, chartGroup?: string): DataTableWidget; dataGrid(parent: string, chartGroup?: string): DataGridWidget; @@ -463,5 +473,4 @@ declare namespace dc { heatMap(parent: string, chartGroup?: string): HeatMap; boxPlot(parent: string, chartGroup?: string): BoxPlot; } -} - +} \ No newline at end of file diff --git a/types/deepmerge/index.d.ts b/types/deepmerge/index.d.ts index 797e52c8a5..05f5c96d2e 100644 --- a/types/deepmerge/index.d.ts +++ b/types/deepmerge/index.d.ts @@ -18,3 +18,10 @@ declare namespace deepmerge { function all(objects: Array>, options?: Options): T; } + +declare global { + interface Window { + deepmerge(x: Partial, y: Partial, options?: deepmerge.Options): T; + deepmerge(x: T1, y: T2, options?: deepmerge.Options): T1 & T2; + } +} diff --git a/types/detect-browser/detect-browser-tests.ts b/types/detect-browser/detect-browser-tests.ts index 336da5150a..48abb964f8 100644 --- a/types/detect-browser/detect-browser-tests.ts +++ b/types/detect-browser/detect-browser-tests.ts @@ -1,5 +1,7 @@ +import { detect } from 'detect-browser'; +const browser = detect(); -import detectBrowser = require("detect-browser"); - -const n: string = detectBrowser.name; -const v: string = detectBrowser.version; +if (browser) { + const name: string = browser.name; + const version: string = browser.version; +} diff --git a/types/detect-browser/index.d.ts b/types/detect-browser/index.d.ts index 57ed80c411..351067ff59 100644 --- a/types/detect-browser/index.d.ts +++ b/types/detect-browser/index.d.ts @@ -1,14 +1,27 @@ -// Type definitions for detect-browser v1.6.2 +// Type definitions for detect-browser 2.0 // Project: https://github.com/DamonOehlman/detect-browser // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped -/** - * Browser name - */ -export const name: "edge" | "yandexbrowser" | "chrome" | "crios" | "firefox" | "opera" | "ie" | "bb10" | "android" | "ios" | "safari"; +export type BrowserName = + "android" | + "bb10" | + "chrome" | + "crios" | + "edge" | + "firefox" | + "fxios" | + "ie" | + "ios" | + "kakaotalk" | + "opera" | + "phantomjs" | + "safari" | + "vivaldi" | + "yandexbrowser"; -/** - * Browser version - */ -export const version: string; +export function detect(): null | { + name: BrowserName | "node"; + version: string; + os: string; +}; diff --git a/types/detect-browser/tsconfig.json b/types/detect-browser/tsconfig.json index 076582077e..b1319407fc 100644 --- a/types/detect-browser/tsconfig.json +++ b/types/detect-browser/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/detect-browser/tslint.json b/types/detect-browser/tslint.json index a41bf5d19a..dc8ddaa586 100644 --- a/types/detect-browser/tslint.json +++ b/types/detect-browser/tslint.json @@ -1,79 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "indent": [ + true, + "spaces", + 4 + ] } } diff --git a/types/dhtmlxscheduler/index.d.ts b/types/dhtmlxscheduler/index.d.ts index 96c9670a4d..007a049623 100644 --- a/types/dhtmlxscheduler/index.d.ts +++ b/types/dhtmlxscheduler/index.d.ts @@ -1212,6 +1212,14 @@ interface SchedulerStatic { * @param config the configuration object of the timespan to mark/block */ addMarkedTimespan(config: any): number; + + /** + * adds a new keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param handler the handler of the shortcut call + * @param scope the name of the context element to attach the handler function to (list of scopes) + */ + addShortcut(shortcut: string, handler: () => void, scope?: any): void; /** * adds a section to the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) @@ -1558,6 +1566,13 @@ interface SchedulerStatic { * @param type ('json', 'xml', 'ical') the data type. The default value - 'xml' */ parse(data: any, type?: string): void; + + /** + * removes a keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param scope the element to which the shortcut is attached (list of scopes) + */ + removeShortcut(shortcut: string, scope: any): void; /** * creates a mini calendar diff --git a/types/docker-file-parser/docker-file-parser-tests.ts b/types/docker-file-parser/docker-file-parser-tests.ts new file mode 100644 index 0000000000..21cd715f47 --- /dev/null +++ b/types/docker-file-parser/docker-file-parser-tests.ts @@ -0,0 +1,25 @@ +import { parse, CommandEntry, ParseOptions } from 'docker-file-parser'; + +const file = ` +FROM node:8 + +ADD . /opt/ +WORKDIR /opt + +RUN npm install --production + +EXPOSE 8080 +VOLUME /opt/scripts + +CMD ["npm", "start"] +`; + +const options: ParseOptions = { + includeComments: false +}; + +const result: CommandEntry[] = parse(file, options); +const line1Name = result[0].name; +const line1Number = result[0].lineno; +const line1Args = result[0].args; +const line1Raw = result[0].raw; diff --git a/types/docker-file-parser/index.d.ts b/types/docker-file-parser/index.d.ts new file mode 100644 index 0000000000..5263ef3353 --- /dev/null +++ b/types/docker-file-parser/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for docker-file-parser 1.0 +// Project: https://github.com/joyent/docker-file-parse +// Definitions by: Yash Kulshrestha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface CommandEntry { + name: string; + args: string[]; + lineno: number; + raw: string; + error?: string; +} + +export interface ParseOptions { + includeComments: boolean; +} + +export function parse( + contents: string, + options?: ParseOptions +): CommandEntry[]; diff --git a/types/docker-file-parser/tsconfig.json b/types/docker-file-parser/tsconfig.json new file mode 100644 index 0000000000..7c529341c4 --- /dev/null +++ b/types/docker-file-parser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "docker-file-parser-tests.ts" + ] +} diff --git a/types/docker-file-parser/tslint.json b/types/docker-file-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/docker-file-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotdir-regex/dotdir-regex-tests.ts b/types/dotdir-regex/dotdir-regex-tests.ts new file mode 100644 index 0000000000..ff40d153f8 --- /dev/null +++ b/types/dotdir-regex/dotdir-regex-tests.ts @@ -0,0 +1,4 @@ +import dotdir = require('dotdir-regex'); + +// $ExpectType RegExp +dotdir(); diff --git a/types/dotdir-regex/index.d.ts b/types/dotdir-regex/index.d.ts new file mode 100644 index 0000000000..59b68ae322 --- /dev/null +++ b/types/dotdir-regex/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for dotdir-regex 1.0 +// Project: https://github.com/regexhq/dotdir-regex +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function dotdirRegex(): RegExp; + +export = dotdirRegex; diff --git a/types/dotdir-regex/tsconfig.json b/types/dotdir-regex/tsconfig.json new file mode 100644 index 0000000000..48f516abd8 --- /dev/null +++ b/types/dotdir-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dotdir-regex-tests.ts" + ] +} diff --git a/types/dotdir-regex/tslint.json b/types/dotdir-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotdir-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotfile-regex/dotfile-regex-tests.ts b/types/dotfile-regex/dotfile-regex-tests.ts new file mode 100644 index 0000000000..f6bad1d84b --- /dev/null +++ b/types/dotfile-regex/dotfile-regex-tests.ts @@ -0,0 +1,4 @@ +import dotfile = require('dotfile-regex'); + +// $ExpectType RegExp +dotfile(); diff --git a/types/dotfile-regex/index.d.ts b/types/dotfile-regex/index.d.ts new file mode 100644 index 0000000000..3a96f4fbad --- /dev/null +++ b/types/dotfile-regex/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for dotfile-regex 1.0 +// Project: https://github.com/regexhq/dotfile-regex +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function dotfileRegex(): RegExp; + +export = dotfileRegex; diff --git a/types/dotfile-regex/tsconfig.json b/types/dotfile-regex/tsconfig.json new file mode 100644 index 0000000000..899be54b3b --- /dev/null +++ b/types/dotfile-regex/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dotfile-regex-tests.ts" + ] +} diff --git a/types/dotfile-regex/tslint.json b/types/dotfile-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotfile-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/download/download-tests.ts b/types/download/download-tests.ts new file mode 100644 index 0000000000..7a498ef0dd --- /dev/null +++ b/types/download/download-tests.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import download = require('download'); + +download('http://unicorn.com/foo.jpg', 'dist').then(() => { + console.log('done!'); +}); + +download('http://unicorn.com/foo.jpg').then(data => { + fs.writeFileSync('dist/foo.jpg', data); +}); + +download('unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg')); + +download('unicorn.com/foo.jpg', 'dest', { + body: '', + decompress: true, + encoding: 'utf8', + extract: true, + filename: 'filename', + followRedirect: true, + proxy: '', + query: '', + retries: (retry: number, error: any) => 4, + timeout: { + connect: 20, + request: 20, + socket: 20 + }, + useElectronNet: true +}); diff --git a/types/download/index.d.ts b/types/download/index.d.ts new file mode 100644 index 0000000000..f3af9778bf --- /dev/null +++ b/types/download/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for download 6.2 +// Project: https://github.com/kevva/download +// Definitions by: Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; +} +type RetryFunction = (retry: number, error: any) => number; + +interface DownloadOptions { + body?: string | Buffer | NodeJS.ReadableStream; + encoding?: string | null; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + /** + * If set to true, try extracting the file using decompress. + */ + extract?: boolean; + /** + * Name of the saved file. + */ + filename?: string; + /** + * Proxy endpoint + */ + proxy?: string; +} + +declare function download(url: string, destination?: string, options?: DownloadOptions): Promise & NodeJS.WritableStream & NodeJS.ReadableStream; + +export = download; diff --git a/types/download/tsconfig.json b/types/download/tsconfig.json new file mode 100644 index 0000000000..634ae5ab32 --- /dev/null +++ b/types/download/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "download-tests.ts" + ] +} diff --git a/types/download/tslint.json b/types/download/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/download/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index dae23b90ef..63821eda98 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -12,7 +12,17 @@ import { SelectionState, getDefaultKeyBinding, ContentState, - convertFromHTML + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, + RawDraftContentState, + DraftBlockType, + DraftInlineStyleType, + DraftEntityMutability, + DraftEntityType, + convertFromHTML, + convertToRaw } from 'draft-js'; const SPLIT_HEADER_BLOCK = 'split-header-block'; @@ -30,7 +40,7 @@ type SyntheticKeyboardEvent = React.KeyboardEvent<{}>; class RichEditorExample extends React.Component<{}, { editorState: EditorState }> { constructor() { - super(); + super({}); const sampleMarkup = 'Bold text, Italic text

' + @@ -182,9 +192,17 @@ function getBlockStyle(block: ContentBlock) { } } -class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}> { - constructor() { - super(); +interface Props { + key: string + active: boolean + label: string + onToggle: (blockType: string) => void + style: string +} + +class StyleButton extends React.Component { + constructor(props: Props) { + super(props); } onToggle: (event: Event) => void = (event: Event) => { @@ -266,7 +284,7 @@ var INLINE_STYLES = [ const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { var currentStyle = props.editorState.getCurrentInlineStyle(); - return ( + return (
{INLINE_STYLES.map(type => , document.getElementById('target') ); + +const editorState = EditorState.createEmpty(); +const contentState = editorState.getCurrentContent(); +const rawContentState: RawDraftContentState = convertToRaw(contentState); + +rawContentState.blocks.forEach((block: RawDraftContentBlock) => { + block.entityRanges.forEach((entityRange: RawDraftEntityRange) => { + const { key, offset, length } = entityRange; + const entity: RawDraftEntity = rawContentState.entityMap[key]; + const entityType: DraftEntityType = entity.type; + const entityMutability: DraftEntityMutability = entity.mutability; + console.log(entityType, entityMutability, offset, length); + }); + + block.inlineStyleRanges.forEach((inlineStyleRange: RawDraftInlineStyleRange) => { + const { offset, length } = inlineStyleRange + const inlineStyle: DraftInlineStyleType = inlineStyleRange.style; + console.log(inlineStyle, offset, length); + }); +}); diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 088d083a7f..3eaa05aa30 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Draft.js v0.10.3 +// Type definitions for Draft.js v0.10.4 // Project: https://facebook.github.io/draft-js/ // Definitions by: Dmitry Rogozhny // Eelco Lempsink @@ -156,6 +156,8 @@ declare namespace Draft { onTab?(e: SyntheticKeyboardEvent): void, onUpArrow?(e: SyntheticKeyboardEvent): void, onDownArrow?(e: SyntheticKeyboardEvent): void, + onRightArrow?(e: SyntheticKeyboardEvent): void, + onLeftArrow?(e: SyntheticKeyboardEvent): void, onBlur?(e: SyntheticEvent): void, onFocus?(e: SyntheticEvent): void, @@ -260,9 +262,10 @@ declare namespace Draft { * or block types. */ "bold" | - "italic" | - "underline" | "code" | + "italic" | + "strikethrough" | + "underline" | /** * Split a block in two. @@ -326,6 +329,60 @@ declare namespace Draft { * another fragment or if the selected fragment shall be replaced */ type DraftInsertionType = "replace" | "before" | "after"; + + /** + * Valid inline styles. + */ + type DraftInlineStyleType = ( + "BOLD" | + "CODE" | + "ITALIC" | + "STRIKETHROUGH" | + "UNDERLINE" + ) + + /** + * Default entity types. + */ + type ComposedEntityType = ( + "LINK" | + "TOKEN" | + "PHOTO" | + "IMAGE" + ) + + /** + * Possible entity types. + */ + type DraftEntityType = string | ComposedEntityType; + + /** + * Possible "mutability" options for an entity. This refers to the behavior + * that should occur when inserting or removing characters in a text range + * with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; } namespace Decorators { @@ -406,14 +463,24 @@ declare namespace Draft { } namespace Encoding { + import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; import ContentState = Draft.Model.ImmutableData.ContentState; import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; - import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + /** + * A plain object representation of an inline style range. + */ + interface RawDraftInlineStyleRange { + style: DraftInlineStyleType; + offset: number; + length: number; + } /** * A plain object representation of an entity attribution. @@ -421,21 +488,12 @@ declare namespace Draft { * The `key` value corresponds to the key of the entity in the `entityMap` of * a `ComposedText` object, not for use with `DraftEntity.get()`. */ - interface EntityRange { + interface RawDraftEntityRange { key: number, offset: number, length: number, } - /** - * A plain object representation of an inline style range. - */ - interface InlineStyleRange { - style: string; - offset: number; - length: number; - } - /** * A plain object representation of an EntityInstance. */ @@ -454,8 +512,8 @@ declare namespace Draft { type: DraftBlockType; text: string; depth: number; - inlineStyleRanges: Array; - entityRanges: Array; + inlineStyleRanges: Array; + entityRanges: Array; data?: Object; } @@ -479,36 +537,8 @@ declare namespace Draft { } namespace Entity { - type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; - type DraftEntityType = string | ComposedEntityType; - - /** - * An enum representing the possible "mutability" options for an entity. - * This refers to the behavior that should occur when inserting or removing - * characters in a text range with an entity applied to it. - * - * `MUTABLE`: - * The text range can be modified freely. Generally used in cases where - * the text content and the entity do not necessarily have a direct - * relationship. For instance, the text and URI for a link may be completely - * different. The user is allowed to edit the text as needed, and the entity - * is preserved and applied to any characters added within the range. - * - * `IMMUTABLE`: - * Not to be confused with immutable data structures used to represent the - * state of the editor. Immutable entity ranges cannot be modified in any - * way. Adding characters within the range will remove the entity from the - * entire range. Deleting characters will delete the entire range. Example: - * Facebook Page mentions. - * - * `SEGMENTED`: - * Segmented entities allow the removal of partial ranges of text, as - * separated by a delimiter. Adding characters wihin the range will remove - * the entity from the entire range. Deleting characters within a segmented - * entity will delete only the segments affected by the deletion. Example: - * Facebook User mentions. - */ - type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; /** * A "document entity" is an object containing metadata associated with a @@ -577,10 +607,10 @@ declare namespace Draft { namespace ImmutableData { import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -936,6 +966,10 @@ import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; +import RawDraftInlineStyleRange = Draft.Model.Encoding.RawDraftInlineStyleRange; +import RawDraftEntityRange = Draft.Model.Encoding.RawDraftEntityRange; +import RawDraftEntity = Draft.Model.Encoding.RawDraftEntity; +import RawDraftContentBlock = Draft.Model.Encoding.RawDraftContentBlock; import RawDraftContentState = Draft.Model.Encoding.RawDraftContentState; import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; @@ -948,6 +982,9 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; +import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; +import DraftEntityType = Draft.Model.Constants.DraftEntityType; import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; import DraftHandleValue = Draft.Model.Constants.DraftHandleValue; import DraftInsertionType = Draft.Model.Constants.DraftInsertionType; @@ -977,6 +1014,10 @@ export { DefaultDraftBlockRenderMap, DefaultDraftInlineStyle, + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, RawDraftContentState, convertFromRaw, convertToRaw, @@ -989,6 +1030,9 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftInlineStyleType, + DraftEntityType, + DraftEntityMutability, DraftRemovalDirection, DraftHandleValue, DraftInsertionType, diff --git a/types/dropzone/dropzone-tests.ts b/types/dropzone/dropzone-tests.ts index 53cedba333..4abc3a6223 100644 --- a/types/dropzone/dropzone-tests.ts +++ b/types/dropzone/dropzone-tests.ts @@ -56,6 +56,7 @@ const dropzoneWithOptions = new Dropzone(".test", { dictRemoveFile: "", dictRemoveFileConfirmation: "", dictMaxFilesExceeded: "", + dictFileSizeUnits: { tb: "", gb: "", mb: "", kb: "", b: "" }, accept: (file: Dropzone.DropzoneFile, done: (error?: string | Error) => void) => { if (file.accepted) { diff --git a/types/dropzone/index.d.ts b/types/dropzone/index.d.ts index f809f84227..0295afbed2 100644 --- a/types/dropzone/index.d.ts +++ b/types/dropzone/index.d.ts @@ -26,6 +26,14 @@ declare namespace Dropzone { accepted: boolean; xhr?: XMLHttpRequest; } + + export interface DropzoneDictFileSizeUnits { + tb?: string; + gb?: string; + mb?: string; + kb?: string; + b?: string; + } export interface DropzoneOptions { url?: string; @@ -72,6 +80,7 @@ declare namespace Dropzone { dictRemoveFile?: string; dictRemoveFileConfirmation?: string; dictMaxFilesExceeded?: string; + dictFileSizeUnits?: DropzoneDictFileSizeUnits; accept?(file: DropzoneFile, done: (error?: string | Error) => void): void; init?(): void; diff --git a/types/dts-generator/index.d.ts b/types/dts-generator/index.d.ts index 9de25e1f91..5ef99eb2b0 100644 --- a/types/dts-generator/index.d.ts +++ b/types/dts-generator/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/SitePen/dts-generator#readme // Definitions by: Matt Traynham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import ts = require('typescript'); import Bluebird = require('bluebird'); diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index c8617b18fc..6e45d5ccd7 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -526,6 +526,12 @@ declare namespace dygraphs { */ highlightSeriesBackgroundAlpha?: number; + /** + * Sets the background color used to fade out the series in conjunction with 'highlightSeriesBackgroundAlpha'. + * Default: rgb(255, 255, 255) + */ + highlightSeriesBackgroundColor?: string; + /** * When set, the options from this object are applied to the timeseries closest to the mouse * pointer for interactive highlighting. See also 'highlightCallback'. Example: diff --git a/types/dynogels/dynogels-tests.ts b/types/dynogels/dynogels-tests.ts new file mode 100644 index 0000000000..ca16707256 --- /dev/null +++ b/types/dynogels/dynogels-tests.ts @@ -0,0 +1,795 @@ +import dynogels = require("dynogels"); +import { DynamoDB } from "aws-sdk"; +import * as Joi from "joi"; + +// AWS Configs +dynogels.AWS.config.loadFromPath('credentials.json'); +dynogels.AWS.config.update({ region: "REGION" }); + +// Define a Model +const Account = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string(), + age: Joi.number(), + roles: dynogels.types.stringSet(), + settings: { + nickname: Joi.string(), + acceptedTerms: Joi.boolean().default(false), + test: { + evan: Joi.string() + } + } + } +}); + +const BlogPost = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + tags: dynogels.types.stringSet(), + } +}); + +const BlogPost1 = dynogels.define('BlogPost', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string() + }, + validation: { + // allow properties not defined in the schema + allowUnknown: true + } +}); + +// Create Tables +dynogels.createTables((err) => { }); + +dynogels.createTables({ + BlogPost: { readCapacity: 5, writeCapacity: 10 }, + Account: { + readCapacity: 20, + writeCapacity: 4, + streamSpecification: { + streamEnabled: true, + streamViewType: 'NEW_IMAGE' + } + } +}, (err) => { }); + +dynogels.createTables({ + $dynogels: { pollingInterval: 100 } +}, (err) => { }); + +// Delete Table +BlogPost.deleteTable((err) => { }); + +// UUID +const Tweet = dynogels.define('Tweet', { + hashKey: 'TweetID', + timestamps: true, + schema: { + TweetID: dynogels.types.uuid(), + content: Joi.string(), + } +}); + +// Configuration +const Account1 = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + } +}); + +const Account2 = dynogels.define('Account', { + hashKey: 'email', + + // enable timestamps support + timestamps: true, + + // I don't want createdAt + createdAt: false, + + // I want updatedAt to actually be called updateTimestamp + updatedAt: 'updateTimestamp', + + schema: { + email: Joi.string().email(), + } +}); + +const Event = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + tableName: 'deviceEvents' +}); + +const Event1 = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: () => { + const d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +Account.config({ tableName: 'AccountsTable' }); + +const dynamodb = new DynamoDB(); +Account.config({ dynamodb }); + +// or globally use custom DynamoDB instance +// all defined models will now use this driver +dynogels.dynamoDriver(dynamodb); + +// Saving Models To DynamoDB +Account.create({ email: 'foo@example.com', name: 'Foo Bar', age: 21 }, (err, acc) => { + acc.get('email'); +}); + +const acc = new Account({ email: 'test@example.com', name: 'Test Example' }); +acc.save((err) => { + acc.get('email'); +}); + +BlogPost.create({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + content: 'Today, we are excited to announce the limited preview...' +}, (err, post) => { }); + +const item1 = { email: 'foo1@example.com', name: 'Foo 1', age: 10 }; +const item2 = { email: 'foo2@example.com', name: 'Foo 2', age: 20 }; +const item3 = { email: 'foo3@example.com', name: 'Foo 3', age: 30 }; + +Account.create([item1, item2, item3], (err, accounts) => { }); + +const params: dynogels.CreateItemOptions = {}; + +params.ConditionExpression = '#i <> :x'; +params.ExpressionAttributeNames = { '#i': 'id' }; +params.ExpressionAttributeValues = { ':x': 123 }; + +Account.create({ id: 123, name: 'Kurt Warner' }, params, (error, acc) => { }); + +// setting overwrite to false will generate +// the same Condition Expression as in the previous example +Account.create({ id: 123, name: 'Kurt Warner' }, { overwrite: false }, (error, acc) => { }); + +// Updating +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, (err, acc) => { }); + +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { ReturnValues: 'ALL_OLD' }, (err, acc) => { }); + +// Only update the account if the current age of the account is 22 +Account.update({ email: 'foo@example.com', name: 'Bar Tester' }, { expected: { age: 22 } }, (err, acc) => { }); + +// setting an attribute to null will delete the attribute from DynamoDB +Account.update({ email: 'foo@example.com', age: null }, (err, acc) => { }); + +Account.update( + { email: 'foo@example.com', name: 'FooBar Testers' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { } +); + +Account.update( + { email: 'baz@example.com', name: 'Bar Tester' }, + { expected: { email: { Exists: true } } }, + (err, acc) => { } +); + +Account.update({ email: 'foo@example.com', age: { $add: 1 } }, (err, acc) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: 'cloud' } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $add: ['cloud', 'dynamodb'] } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: 'cloud' } +}, (err, post) => { }); + +BlogPost.update({ + email: 'werner@example.com', + title: 'Expanding the Cloud', + tags: { $del: ['aws', 'node'] } +}, (err, post) => { }); + +const params1: dynogels.UpdateItemOptions = {}; +params1.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag'; +params1.ConditionExpression = '#year = :current'; +params1.ExpressionAttributeNames = { + '#year': 'releaseYear', + '#dir': 'director', + '#act': 'actors' +}; + +params1.ExpressionAttributeValues = { + ':inc': 1, + ':current': 2001, + ':title': ['The Man'], + ':firstName': 'Rob', + ':tag': dynogels.Set(['Sports', 'Horror'], 'S') +}; + +BlogPost.update({ title: 'Movie 0', description: 'This is a description' }, params1, (err, mov) => { }); + +// Deleting +Account.destroy('foo@example.com', (err) => { }); + +// Destroy model using hash and range key +BlogPost.destroy('foo@example.com', 'Hello World!', (err) => { }); + +BlogPost.destroy({ email: 'foo@example.com', title: 'Another Post' }, (err) => { }); + +Account.destroy('foo@example.com', { ReturnValues: 'ALL_OLD' }, (err, acc) => { }); + +Account.destroy('foo@example.com', { expected: { age: 22 } }, (err) => { }); + +const params2: dynogels.DestroyItemOptions = {}; +params2.ConditionExpression = '#v = :x'; +params2.ExpressionAttributeNames = { '#v': 'version' }; +params2.ExpressionAttributeValues = { ':x': '2' }; + +Account.destroy({ id: 123 }, params2, (err, acc) => { }); + +// Loading Models from DynamoDB +Account.get('test@example.com', (err, acc) => { + console.log('got account', acc.get('email')); +}); + +Account.get('test@example.com', { ConsistentRead: true }, (err, acc) => { }); + +Account.get('test@example.com', { ConsistentRead: true, AttributesToGet: ['name', 'age'] }, (err, acc) => { }); + +BlogPost.get('werner@example.com', 'dynamodb-keeps-getting-better-and-cheaper', (err, post) => { }); + +BlogPost.get({ email: 'werner@example.com', title: 'Expanding the Cloud' }, (err, post) => { }); + +BlogPost.get({ id: '123456789' }, { ProjectionExpression: 'email, age, settings.nickname' }, (err, acc) => { }); + +// Query + +const callback = () => { }; +// query for blog posts by werner@example.com +BlogPost + .query('werner@example.com') + .exec(callback); + +// same as above, but load all results +BlogPost + .query('werner@example.com') + .loadAll() + .exec(callback); + +// only load the first 5 posts by werner +BlogPost + .query('werner@example.com') + .limit(5) + .exec(callback); + +// query for posts by werner where the tile begins with 'Expanding' +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(callback); + +// return only the count of documents that begin with the title Expanding +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .select('COUNT') + .exec(callback); + +// query the first 10 posts by werner@example.com but only return +// the title and content from posts where the title starts with 'Expanding' +// WARNING: See notes below on the implementation of limit in DynamoDB +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .attributes(['title', 'content']) + .limit(10) + .exec(callback); + +// sorting by title ascending +BlogPost + .query('werner@example.com') + .ascending() + .exec(callback); + +// sorting by title descending +BlogPost + .query('werner@example.com') + .descending() + .exec(callback); + +// All query options are chainable +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .attributes(['title', 'content']) + .limit(10) + .ascending() + .loadAll() + .exec(callback); + +// Traversing Map Data Types +Account + .query('werner@example.com') + .filter('settings.acceptedTerms').equals(true) + .exec(callback); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .exec(); + +// less than equals +BlogPost + .query('werner@example.com') + .where('title').lte('Expanding') + .exec(); + +// less than +BlogPost + .query('werner@example.com') + .where('title').lt('Expanding') + .exec(); + +// greater than +BlogPost + .query('werner@example.com') + .where('title').gt('Expanding') + .exec(); + +// greater than equals +BlogPost + .query('werner@example.com') + .where('title').gte('Expanding') + .exec(); + +// attribute doesn't exist +BlogPost + .query('werner@example.com') + .where('title').null() + .exec(); + +// attribute exists +BlogPost + .query('werner@example.com') + .where('title').exists() + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').beginsWith('Expanding') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').between('foo@example.com', 'test@example.com') + .exec(); + +BlogPost + .query('werner@example.com') + .where('title').equals('Expanding') + .filter('tags').contains('cloud') + .exec(); + +BlogPost + .query('werner@example.com') + .filterExpression('#title < :t') + .expressionAttributeValues({ ':t': 'Expanding' }) + .expressionAttributeNames({ '#title': 'title' }) + .projectionExpression('#title, tag') + .exec(); + +const GameScore = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', rangeKey: 'topScore', name: 'GameTitleIndex', type: 'global' + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .descending() + .exec(callback); + +const GameScore1 = dynogels.define('GameScore', { + hashKey: 'userId', + rangeKey: 'gameTitle', + schema: { + userId: Joi.string(), + gameTitle: Joi.string(), + topScore: Joi.number(), + topScoreDateTime: Joi.date(), + wins: Joi.number(), + losses: Joi.number() + }, + indexes: [{ + hashKey: 'gameTitle', + rangeKey: 'topScore', + name: 'GameTitleIndex', + type: 'global', + projection: { NonKeyAttributes: ['wins'], ProjectionType: 'INCLUDE' } // optional, defaults to ALL + }] +}); + +GameScore + .query('Galaxy Invaders') + .usingIndex('GameTitleIndex') + .where('topScore').gt(1000) + .descending() + .exec((err, data) => { }); + +const BlogPost5 = dynogels.define('Account', { + hashKey: 'email', + rangeKey: 'title', + schema: { + email: Joi.string().email(), + title: Joi.string(), + content: Joi.binary(), + PublishedDateTime: Joi.date() + }, + + indexes: [{ + hashKey: 'email', rangeKey: 'PublishedDateTime', type: 'local', name: 'PublishedIndex' + }] +}); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .ascending() + .exec(callback); + +BlogPost + .query('werner@example.com') + .usingIndex('PublishedIndex') + .descending() + .loadAll() + .exec(callback); + +// scan all accounts, returning the first page or results +Account.scan().exec(callback); + +// scan all accounts, this time loading all results +// note this will potentially make several calls to DynamoDB +// in order to load all results +Account + .scan() + .loadAll() + .exec(callback); + +// Load 20 accounts +Account + .scan() + .limit(20) + .exec(); + +// Load All accounts, 20 at a time per request +Account + .scan() + .limit(20) + .loadAll() + .exec(); + +// Load accounts which match a filter +// only return email and created attributes +// and return back the consumed capacity the request took +Account + .scan() + .where('email').gte('f@example.com') + .attributes(['email', 'created']) + .returnConsumedCapacity() + .exec(); + +// Load All accounts, if settings.acceptedTerms is true +Account + .scan() + .where('settings.acceptedTerms').equals(true) + .exec(); + +// Returns number of matching accounts, rather than the matching accounts themselves +Account + .scan() + .where('age').gte(21) + .select('COUNT') + .exec(); + +// Start scan using start key +Account + .scan() + .where('age').notNull() + .startKey('foo@example.com') + .exec(); + +// equals +Account + .scan() + .where('name').equals('Werner') + .exec(); + +// not equals +Account + .scan() + .where('name').ne('Werner') + .exec(); + +// less than equals +Account + .scan() + .where('name').lte('Werner') + .exec(); + +// less than +Account + .scan() + .where('name').lt('Werner') + .exec(); + +// greater than equals +Account + .scan() + .where('name').gte('Werner') + .exec(); + +// greater than +Account + .scan() + .where('name').gt('Werner') + .exec(); + +// name attribute doesn't exist +Account + .scan() + .where('name').null() + .exec(); + +// name attribute exists +Account + .scan() + .where('name').notNull() + .exec(); + +// contains +Account + .scan() + .where('name').contains('ner') + .exec(); + +// not contains +Account + .scan() + .where('name').notContains('ner') + .exec(); + +// in +Account + .scan() + .where('name').in(['foo@example.com', 'bar@example.com']) + .exec(); + +// begins with +Account + .scan() + .where('name').beginsWith('Werner') + .exec(); + +// between +Account + .scan() + .where('name').between('Bar', 'Foo') + .exec(); + +// multiple filters +Account + .scan() + .where('name').equals('Werner') + .where('age').notNull() + .exec(); + +Account.scan() + .filterExpression('#age BETWEEN :low AND :high AND begins_with(#email, :e)') + .expressionAttributeValues({ ':low': 18, ':high': 22, ':e': 'test1' }) + .expressionAttributeNames({ '#age': 'age', '#email': 'email' }) + .projectionExpression('#age, #email') + .exec(); + +const totalSegments = 8; + +Account.parallelScan(totalSegments) + .where('age').gte(18) + .attributes('age') + .exec(callback); + +// Load All accounts +Account + .parallelScan(totalSegments) + .exec(); + +Account.getItems(['foo@example.com', 'bar@example.com', 'test@example.com'], (err, accounts) => { + console.log(`loaded ${accounts.length} accounts`); // prints loaded 3 accounts +}); + +// Get both accounts, using a consistent read +Account.getItems(['foo@example.com', 'bar@example.com'], { ConsistentRead: true }, (err, accounts) => { + console.log(`loaded ${accounts.length} accounts`); // prints loaded 2 accounts +}); + +// Streaming API + +const stream = Account.parallelScan(4).exec(); + +stream.on('readable', () => { + console.log('single parallel scan response', stream.read()); +}); + +stream.on('end', () => { + console.log('Parallel scan of accounts finished'); +}); + +const querystream = BlogPost.query('werner@dynogels.com').loadAll().exec(); + +querystream.on('readable', () => { + console.log('single query response', stream.read()); +}); + +querystream.on('end', () => { + console.log('query for blog posts finished'); +}); + +// Dynamic Table Names + +const Event2 = dynogels.define('Event', { + hashKey: 'name', + schema: { + name: Joi.string(), + total: Joi.number() + }, + + // store monthly event data + tableName: () => { + const d = new Date(); + return ['events', d.getFullYear(), d.getMonth() + 1].join('_'); + } +}); + +// Logging + +const accountLogger = { + info: (...args: any[]) => { }, + warn: (...args: any[]) => { } +}; + +dynogels.log = accountLogger; + +const Account3 = dynogels.define('Account', { + hashKey: 'email', + log: accountLogger +}); // INFO level on account table + +const Account4 = dynogels.define('Account', { + hashKey: 'email', + + // add the timestamp attributes (updatedAt, createdAt) + timestamps: true, + + schema: { + email: Joi.string().email(), + name: Joi.string().required(), + age: Joi.number(), + } +}); + +Account.create({ email: 'test@example.com', name: 'Test Account' }, (err, acc) => { + console.log('created account at', acc.get('created')); // prints created Date + + acc.set({ age: 22 }); + + acc.update((err) => { + console.log('updated account age'); + }); +}); + +// For models with range keys you must pass in objects of hash and range key attributes +const postKey1 = { email: 'test@example.com', title: 'Hello World!' }; +const postKey2 = { email: 'test@example.com', title: 'Another Post' }; + +BlogPost.getItems([postKey1, postKey2], (err, posts) => { + console.log('loaded posts'); +}); + +dynogels.log.info("test", "123", {}); +dynogels.log.warn("test", "123", {}); + +// Lifecycle hooks +Account.before('create', (data, next) => { + if (!data.name) { + data.name = 'Foo Bar'; + } + + next(null, data); +}); + +Account.before('update', (data, next) => { + data.age = 45; + next(null, data); +}); + +Account.after('create', item => { + console.log('Account created', item.get()); +}); + +Account.after('update', item => { + console.log('Account updated', item.get()); +}); + +Account.after('destroy', item => { + console.log('Account destroyed', item.get()); +}); + +dynogels.createTables(err => { + if (err) { + process.exit(1); + } + + Account.create({ email: 'test11@example.com' }, (err, acc) => { + acc.set({ age: 25 }); + + acc.update(() => { + acc.destroy({ ReturnValues: 'ALL_OLD' }); + }); + }); +}); diff --git a/types/dynogels/index.d.ts b/types/dynogels/index.d.ts new file mode 100644 index 0000000000..2e4c5acbf4 --- /dev/null +++ b/types/dynogels/index.d.ts @@ -0,0 +1,263 @@ +// Type definitions for dynogels 8.0 +// Project: https://github.com/clarkie/dynogels#readme +// Definitions by: Spartan Labs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export import AWS = require("aws-sdk"); +import * as joi from "joi"; +import stream = require("stream"); + +// Dynogels Data Members +export let log: Log; +export let models: { [key: string]: Model }; +export let types: { + stringSet(): joi.AnySchema; + numberSet(): joi.AnySchema; + binarySet(): joi.AnySchema; + uuid(): joi.AnySchema; + timeUUID(): joi.AnySchema; +}; + +export interface Log { + info(...args: any[]): void; + warn(...args: any[]): void; +} + +// Dynogels global functions +export function dynamoDriver(dynamoDB: AWS.DynamoDB): AWS.DynamoDB; +export function reset(): void; +export function define(modelName: string, config: ModelConfiguration): Model; +export function createTables(callback: (err: string) => void): void; +export function createTables(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: string) => void): void; +export function Set(...args: any[]): any; + +export interface DynogelsGlobalOptions { + $dynogels: { + pollingInterval: number; + }; +} + +export interface CreateTablesOptions { + readCapacity?: number; + writeCapacity?: number; + streamSpecification?: { + streamEnabled: boolean; + streamViewType: string; + }; +} + +export type LifeCycleAction = "create" | "update" | "destroy"; + +// Dynogels Model +export interface Model { + new(attrs: { [key: string]: any }): Item; + + get(hashKey: any, rangeKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(haskKey: any, options: GetItemOptions, callback: DynogelsItemCallback): void; + get(hashKey: any, callback: DynogelsItemCallback): void; + get(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + create(item: any, options: CreateItemOptions, callback: DynogelsItemCallback): void; + create(item: any, callback: DynogelsItemCallback): void; + update(item: any, options: UpdateItemOptions, callback: DynogelsItemCallback): void; + update(item: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(haskKey: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(hashKey: any, callback: DynogelsItemCallback): void; + destroy(hashKey: any, rangeKey: any, callback: DynogelsItemCallback): void; + destroy(item: any, options: DestroyItemOptions, callback: DynogelsItemCallback): void; + destroy(item: any, callback: DynogelsItemCallback): void; + query(hashKey: any): Query; + scan(): Scan; + parallelScan(totalSegments: number): Scan; + getItems(items: string[] | Array<{ [key: string]: string }>, callback: (err: Error, items: any[]) => void): void; + getItems(items: string[] | Array<{ [key: string]: string }>, options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | Array<{ [key: string]: string }>, callback: (err: Error, items: any[]) => void): void; + batchGetItems(items: string[] | Array<{ [key: string]: string }>, options: GetItemOptions, callback: (err: Error, items: any[]) => void): void; + createTable(options: { [key: string]: CreateTablesOptions } | DynogelsGlobalOptions, callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + createTable(callback: (err: Error, data: AWS.DynamoDB.CreateTableOutput) => void): void; + updateTable(throughput: Throughput, callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + updateTable(callback: (err: Error, data: AWS.DynamoDB.UpdateTableOutput) => void): void; + describeTable(callback: (err: Error, data: AWS.DynamoDB.DescribeTableOutput) => void): void; + deleteTable(callback: (err: Error) => void): void; + tableName(): string; + + after(action: LifeCycleAction, listner: (item: Item) => void): void; + before(action: LifeCycleAction, listner: (data: any, next: (err: Error | null, data: any) => void) => void): void; + config(config: ModelConfig): { name: string }; +} + +export type DynogelsItemCallback = (err: Error, data: Item) => void; + +export interface Throughput { + readCapacity: number; + writeCapacity: number; +} + +export interface CreateItemOptions { + expected?: { [key: string]: any }; + overwrite?: boolean; + + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface UpdateItemOptions { + expected?: { [key: string]: any }; + + AttributeUpdates?: AWS.DynamoDB.AttributeUpdates; + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + UpdateExpression?: AWS.DynamoDB.UpdateExpression; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface DestroyItemOptions { + Expected?: AWS.DynamoDB.ExpectedAttributeMap; + ConditionalOperator?: AWS.DynamoDB.ConditionalOperator; + ReturnValues?: AWS.DynamoDB.ReturnValue; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ReturnItemCollectionMetrics?: AWS.DynamoDB.ReturnItemCollectionMetrics; + ConditionExpression?: AWS.DynamoDB.ConditionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; + ExpressionAttributeValues?: { [key: string]: any }; +} + +export interface GetItemOptions { + AttributesToGet?: AWS.DynamoDB.AttributeNameList; + ConsistentRead?: AWS.DynamoDB.ConsistentRead; + ReturnConsumedCapacity?: AWS.DynamoDB.ReturnConsumedCapacity; + ProjectionExpression?: AWS.DynamoDB.ProjectionExpression; + ExpressionAttributeNames?: AWS.DynamoDB.ExpressionAttributeNameMap; +} + +export interface ModelConfig { + tableName?: string; + docClient?: any; + dynamodb?: AWS.DynamoDB; +} + +// Dynogels Item +export interface Item { + get(key?: string): { [key: string]: any }; + set(params: {}): Item; + save(callback?: DynogelsItemCallback): void; + update(options: UpdateItemOptions, callback?: DynogelsItemCallback): void; + update(callback?: DynogelsItemCallback): void; + destroy(options: DestroyItemOptions, callback?: DynogelsItemCallback): void; + destroy(callback?: DynogelsItemCallback): void; + toJSON(): any; + toPlainObject(): any; +} + +export interface BaseChain { + equals(value: any): T; + eq(value: any): T; + lte(value: any): T; + lt(value: any): T; + gte(value: any): T; + gt(value: any): T; + null(): T; + exists(): T; + beginsWith(value: any): T; + between(value1: any, value2: any): T; +} + +export interface ExtendedChain extends BaseChain { + contains(value: any): T; + notContains(value: any): T; + in(values: any[]): T; + ne(value: any): T; +} + +export type QueryWhereChain = BaseChain; +export type QueryFilterChain = ExtendedChain; + +// Dynogels Query +export interface Query { + limit(number: number): Query; + filterExpression(expression: any): Query; + expressionAttributeNames(data: any): Query; + expressionAttributeValues(data: any): Query; + projectionExpression(data: any): Query; + usingIndex(name: string): Query; + consistentRead(read: boolean): Query; + addKeyCondition(condition: any): Query; + addFilterCondition(condition: any): Query; + startKey(hashKey: any, rangeKey: any): Query; + attributes(attrs: any): Query; + ascending(): Query; + descending(): Query; + select(value: any): Query; + returnConsumedCapacity(value: any): Query; + loadAll(): Query; + where(keyName: string): QueryWhereChain; + filter(keyName: string): QueryFilterChain; + exec(): stream.Readable; + exec(callback: (err: Error, data: any) => void): void; +} + +export interface ScanWhereChain extends ExtendedChain { + notNull(): Scan; +} + +// Dynogels Scan +export interface Scan { + limit(number: number): Scan; + addFilterCondition(condition: any): Scan; + startKey(hashKey: any, rangeKey?: any): Scan; + attributes(attrs: any): Scan; + select(value: any): Scan; + returnConsumedCapacity(): Scan; + segments(segment: any, totalSegments: number): Scan; + where(keyName: string): ScanWhereChain; + filterExpression(expression: any): Scan; + expressionAttributeNames(data: any): Scan; + expressionAttributeValues(data: any): Scan; + projectionExpression(data: any): Scan; + exec(): stream.Readable; + exec(callback: (err: Error, data: any) => void): void; + loadAll(): Scan; +} + +export type tableResolve = () => string; + +export interface SchemaType { + [key: string]: joi.AnySchema | SchemaType; +} + +export interface ModelConfiguration { + hashKey: string; + rangeKey?: string; + timestamps?: boolean; + createdAt?: boolean; + updatedAt?: string; + schema?: SchemaType; + validation?: joi.ValidationOptions; + tableName?: string | tableResolve; + indexes?: any[]; + log?: Log; +} + +export interface Document { + [key: string]: any; +} + +export interface DocumentCollection { + Items: Document[]; + Count: number; + ScannedCount: number; +} diff --git a/types/dynogels/package.json b/types/dynogels/package.json new file mode 100644 index 0000000000..28676516a3 --- /dev/null +++ b/types/dynogels/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": "^2.58.0" + } +} \ No newline at end of file diff --git a/types/dynogels/tsconfig.json b/types/dynogels/tsconfig.json new file mode 100644 index 0000000000..40297f0a43 --- /dev/null +++ b/types/dynogels/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "strictFunctionTypes": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dynogels-tests.ts" + ] +} \ No newline at end of file diff --git a/types/dynogels/tslint.json b/types/dynogels/tslint.json new file mode 100644 index 0000000000..c7d87e32cc --- /dev/null +++ b/types/dynogels/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} \ No newline at end of file diff --git a/types/easeljs/index.d.ts b/types/easeljs/index.d.ts index d47f631728..462c9f04cf 100644 --- a/types/easeljs/index.d.ts +++ b/types/easeljs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for EaselJS 0.8.0 +// Type definitions for EaselJS 1.0.0 // Project: http://www.createjs.com/#!/EaselJS // Definitions by: Pedro Ferreira , Chris Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -53,6 +53,22 @@ declare namespace createjs { clone(): Bitmap; } + export class BitmapCache { + constructor(); + + // properties + cacheID: number; + + // methods + static getFilterBounds(target: DisplayObject, output?: Rectangle): Rectangle; + toString(): string; + define(target: DisplayObject, x: number, y: number, width: number, height: number, scale?: number): void; + update(compositeOperation?: string): void; + release(): void; + getCacheDataURL(): string; + draw(ctx: CanvasRenderingContext2D): boolean; + } + export class ScaleBitmap extends DisplayObject { constructor(imageOrUrl: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Object | string, scale9Grid: Rectangle); @@ -211,6 +227,7 @@ declare namespace createjs { // properties alpha: number; + bitmapCache: BitmapCache; cacheCanvas: HTMLCanvasElement | Object; cacheID: number; compositeOperation: string; @@ -924,6 +941,60 @@ declare namespace createjs { } + interface IStageGLOptions { + preserveBuffer?: boolean; + antialias?: boolean; + transparent?: boolean; + premultiply?: boolean; + autoPurge?: number; + } + + export class StageGL extends Stage { + constructor(canvas: HTMLCanvasElement | string | Object, options?: IStageGLOptions); + + // properties + static VERTEX_PROPERTY_COUNT: number; + static INDICIES_PER_CARD: number; + static DEFAULT_MAX_BATCH_SIZE: number; + static WEBGL_MAX_INDEX_NUM: number; + static UV_RECT: number; + static COVER_VERT: Float32Array; + static COVER_UV: Float32Array; + static COVER_UV_FLIP: Float32Array; + static REGULAR_VARYING_HEADER: string; + static REGULAR_VERTEX_HEADER: string; + static REGULAR_FRAGMENT_HEADER: string; + static REGULAR_VERTEX_BODY: string; + static REGULAR_FRAGMENT_BODY: string; + static REGULAR_FRAG_COLOR_NORMAL: string; + static REGULAR_FRAG_COLOR_PREMULTIPLY: string; + static PARTICLE_VERTEX_BODY: string; + static PARTICLE_FRAGMENT_BODY: string; + static COVER_VARYING_HEADER: string; + static COVER_VERTEX_HEADER: string; + static COVER_FRAGMENT_HEADER: string; + static COVER_VERTEX_BODY: string; + static COVER_FRAGMENT_BODY: string; + isWebGL: boolean; + autoPurge: number; + vocalDebug: boolean; + + // methods + static buildUVRects(spritesheet: SpriteSheet, target?: number, onlyTarget?: boolean): Object; + static isWebGLActive(ctx: CanvasRenderingContext2D): boolean; + cacheDraw(target: DisplayObject, filters: Filter[], manager: BitmapCache): boolean; + getBaseTexture(w?: number, h?: number): WebGLTexture | null; + getFilterShader(filter: Filter | Object): WebGLProgram; + getRenderBufferTexture (w: number, h: number): WebGLTexture; + getTargetRenderTexture (target: DisplayObject, w: number, h: number): Object; + protectTextureSlot(id: number, lock?: boolean): void; + purgeTextures(count?: number): void; + releaseTexture(item: DisplayObject | WebGLTexture | HTMLImageElement | HTMLCanvasElement): void; + setTextureParams(gl: WebGLRenderingContext, isPOT?: boolean): void; + updateSimultaneousTextureCount(count?: number): void; + updateViewport(width: number, height: number): void; + } + export class Text extends DisplayObject { constructor(text?: string, font?: string, color?: string); diff --git a/types/easy-jsend/index.d.ts b/types/easy-jsend/index.d.ts index 6cf9f48d03..c0280736e9 100644 --- a/types/easy-jsend/index.d.ts +++ b/types/easy-jsend/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/easy-jsend // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/easy-x-headers/index.d.ts b/types/easy-x-headers/index.d.ts index 35ede3ef2e..1dffb8adc8 100644 --- a/types/easy-x-headers/index.d.ts +++ b/types/easy-x-headers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/easy-x-headers // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/easy-xapi-supertest/index.d.ts b/types/easy-xapi-supertest/index.d.ts index f67dc4345b..6f8b6764fd 100644 --- a/types/easy-xapi-supertest/index.d.ts +++ b/types/easy-xapi-supertest/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/easy-x-headers // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/easy-xapi-utils/index.d.ts b/types/easy-xapi-utils/index.d.ts index 5085af7551..c845b17a58 100644 --- a/types/easy-xapi-utils/index.d.ts +++ b/types/easy-xapi-utils/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/DeadAlready/easy-xapi-utils // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /// /// diff --git a/types/easy-xapi/index.d.ts b/types/easy-xapi/index.d.ts index aa7316288b..5d3cdb2eb1 100644 --- a/types/easy-xapi/index.d.ts +++ b/types/easy-xapi/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/DeadAlready/easy-xapi // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /// /// diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index bcae4299d3..0ea8aa0c6a 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -4,77 +4,91 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace echarts { - function init(dom:HTMLDivElement|HTMLCanvasElement, theme?:Object|string, opts?:{ + function init(dom: HTMLDivElement | HTMLCanvasElement, theme?: Object | string, opts?: { devicePixelRatio?: number renderer?: string - }):ECharts; + }): ECharts; const graphic: { clipPointsByRect(points: number[][], rect: ERectangle): number[][]; clipRectByRect(targetRect: ERectangle, rect: ERectangle): ERectangle; + LinearGradient: { new (x: number, y: number, x2: number, y2: number, colorStops: Array, globalCoord?: boolean): LinearGradient } + + }; + + + function connect(group: string | Array): void; + + function disConnect(group: string): void; + + function dispose(target: ECharts | HTMLDivElement | HTMLCanvasElement): void; + + function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement): void; + + function registerMap(mapName: string, geoJson: Object, specialAreas?: Object): void; + + function registerTheme(themeName: string, theme: Object): void; + + interface LinearGradient { + colorStops: Array; + global: boolean; + type: string; + x: number + x2: number + y: number + y2: number } - - function connect(group:string|Array):void; - function disConnect(group:string):void; - - function dispose(target:ECharts|HTMLDivElement|HTMLCanvasElement):void; - - function getInstanceByDom(target:HTMLDivElement|HTMLCanvasElement):void; - - function registerMap(mapName:string, geoJson:Object, specialAreas?:Object):void; - - function registerTheme(themeName:string, theme:Object):void; interface ECharts { - group:string; + group: string; - setOption(option:EChartOption, notMerge?:boolean, notRefreshImmediately?:boolean):void + setOption(option: EChartOption, notMerge?: boolean, notRefreshImmediately?: boolean): void - getWidth():number + getWidth(): number - getHeight():number + getHeight(): number - getDom():HTMLCanvasElement|HTMLDivElement + getDom(): HTMLCanvasElement | HTMLDivElement - getOption():Object + getOption(): Object - resize():void + resize(): void - dispatchAction(payload:Object):void + dispatchAction(payload: Object): void - on(eventName:string, handler:Function, context?:Object):void + on(eventName: string, handler: Function, context?: Object): void - off(eventName:string, handler?:Function):void + off(eventName: string, handler?: Function): void - showLoading(type?:string, opts?:Object):void + showLoading(type?: string, opts?: Object): void - hideLoading():void + hideLoading(): void - getDataURL(opts:{ + getDataURL(opts: { // 导出的格式,可选 png, jpeg type?: string, // 导出的图片分辨率比例,默认为 1。 pixelRatio?: number, // 导出的图片背景色,默认使用 option 里的 backgroundColor backgroundColor?: string - }):string + }): string - getConnectedDataURL(opts:{ + getConnectedDataURL(opts: { // 导出的格式,可选 png, jpeg type: string, // 导出的图片分辨率比例,默认为 1。 pixelRatio: number, // 导出的图片背景色,默认使用 option 里的 backgroundColor backgroundColor: string - }):string + }): string - clear():void + clear(): void - isDisposed():boolean + isDisposed(): boolean + + dispose(): void - dispose():void - // 转换逻辑点到像素 convertToPixel(finder: { seriesIndex?: number, @@ -92,8 +106,8 @@ declare namespace echarts { gridIndex?: number, gridId?: string gridName?: string - } | string, value: string|Array): string|Array - + } | string, value: string | Array): string | Array + convertFromPixel(finder: { seriesIndex?: number, seriesId?: string, @@ -110,7 +124,7 @@ declare namespace echarts { gridIndex?: number, gridId?: string gridName?: string - } | string, value: Array|string): Array|string + } | string, value: Array | string): Array | string } interface ERectangle { @@ -177,6 +191,6 @@ declare namespace echarts { } } -declare module "echarts" { +declare module 'echarts' { export = echarts; } diff --git a/types/egg-mock/index.d.ts b/types/egg-mock/index.d.ts index 9ccf6989dd..7308d52184 100644 --- a/types/egg-mock/index.d.ts +++ b/types/egg-mock/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/eggjs/egg-mock // Definitions by: Eward Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { Application, Context } from 'egg'; diff --git a/types/ej.web.all/ej.web.all-tests.ts b/types/ej.web.all/ej.web.all-tests.ts index d1d67be14c..9a1b418da0 100644 --- a/types/ej.web.all/ej.web.all-tests.ts +++ b/types/ej.web.all/ej.web.all-tests.ts @@ -1,4 +1,6 @@ /* tslint:disable */ +/* tslint:disable */ + module AccordionComponent { $(function () { @@ -76,6 +78,35 @@ module Bulletgraphcomponent { $(function () { var bulletsample = new ej.datavisualization.BulletGraph($("#BulletGraph"), { isResponsive: true, + load: function () { + var sender = $("#BulletGraph").data("ejBulletGraph"); + var bulletTheme = window.themeStyle + window.themeColor + window.themeVarient; + if (bulletTheme) { + switch (bulletTheme) { + case "flatdark": + case "flatazuredark": + case "flatlimedark": + case "flatsaffrondark": + case "gradientdark": + case "gradientazuredark": + case "gradientlimedark": + case "gradientsaffrondark": + case "flathigh-contrast-01dark": + case "flathigh-contrast-02dark": + theme = "flatdark"; + break; + case "flatoffice-365light": + case "flatmateriallight": + theme = "material"; + break; + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } + + }, tooltipSettings: { visible: true }, quantitativeScaleSettings: { featureMeasures: [{ @@ -232,10 +263,50 @@ module ChartComponent { model.primaryYAxis.labelIntersectAction = "rotate45"; model.primaryYAxis.edgeLabelPlacement = "hide"; } + var theme = window.themeStyle + window.themeColor + window.themeVarient; + if (theme) { + switch (theme) { + case "flatdark": + case "flatazuredark": + case "flatlimedark": + case "flatsaffrondark": + theme = "flatdark"; + break; + case "gradientlight": + case "gradientazurelight": + case "gradientlimelight": + case "gradientsaffronlight": + theme = "gradientlight"; + break; + case "gradientdark": + case "gradientazuredark": + case "gradientlimedark": + case "gradientsaffrondark": + theme = "gradientdark"; + break; + case "flatbootstraplight": + theme = "bootstrap"; + break; + case "flathigh-contrast-01dark": + case "flathigh-contrast-02dark": + theme = "high-contrast-01"; + break; + case "flatmateriallight": + case "flatoffice-365light": + theme = "material"; + break; + + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } }, title: { text: 'Efficiency of oil-fired power production' }, size: { height: "600" }, - legend: { visible: true} + legend: { visible: true}, + load:"loadTheme" }); }); } @@ -307,6 +378,28 @@ module ColorPickerComponent { } + + +module ComboBoxComponent{ + var BikeList = [ + { empid: "bk1", text: "Apache RTR" }, { empid: "bk2", text: "CBR 150-R" }, { empid: "bk3", text: "CBZ Xtreme" }, + { empid: "bk4", text: "Discover" }, { empid: "bk5", text: "Dazzler" }, { empid: "bk6", text: "Flame" }, + { empid: "bk7", text: "Fazzer" }, { empid: "bk8", text: "FZ-S" }, { empid: "bk9", text: "Pulsar" }, + { empid: "bk10", text: "Shine" }, { empid: "bk11", text: "R15" }, { empid: "bk12", text: "Unicorn" } + ]; + $(function () { + var comboboxInstance =new ej.ComboBox($("#selectCar"), { + width: "100%", + placeholder: "Select a Bike", + fields: { text: "text", value: "empid" }, + dataSource: BikeList, + autofill: true + }); + }); +} + + + module DatePickerComponent { @@ -1065,7 +1158,8 @@ module PivotChartOlap { size: { height: "460px", width: "100%" }, primaryXAxis: { title: { text: "Date - Fiscal" }, labelRotation: 0 }, primaryYAxis: { title: { text: "Internet Sales Amount" } }, - legend: { visible: true, rowCount: 2 } + legend: { visible: true, rowCount: 2 }, + load:"loadTheme" }); }); } @@ -1139,7 +1233,8 @@ module PivotChartRelational { }, size: { height: "460px", width: "100%" }, primaryYAxis: { title: { text: "Amount" } }, - legend: { visible: true } + legend: { visible: true }, + load:"loadTheme" }); }); } @@ -1650,7 +1745,67 @@ module rangecomponent { fill: '#69D2E7' } ]; - } + }, + loaded: function () { + var sender = $("#RangeNavigator").data("ejRangeNavigator"); + var theme = window.themeStyle + window.themeColor + window.themeVarient; + if (theme) { + switch (theme) { + case "flatazurelight": + theme = "azurelight"; + break; + case "flatlimelight": + theme = "limelight"; + break; + case "flatsaffronlight": + theme = "saffronlight"; + break; + case "gradientazurelight": + theme = "gradientazure"; + break; + case "gradientlimelight": + theme = "gradientlime"; + break; + case "gradientsaffronlight": + theme = "gradientsaffron"; + break; + case "flatazuredark": + theme = "azuredark"; + break; + case "flatlimedark": + theme = "limedark"; + break; + case "flatsaffrondark": + theme = "saffrondark"; + break; + case "gradientazuredark": + theme = "gradientazuredark"; + break; + case "gradientlimedark": + theme = "gradientlimedark"; + break; + case "gradientsaffrondark": + theme = "gradientsaffrondark"; + break; + case "flathigh-contrast-01dark": + theme = "highcontrast01"; + break; + case "flathigh-contrast-02dark": + theme = "highcontrast02"; + break; + case "flatmateriallight": + theme = "material"; + break; + case "flatoffice-365light": + theme = "office"; + break; + default: + theme = "flatlight"; + break; + } + sender.model.theme = theme; + } + } }); }); @@ -2621,7 +2776,9 @@ module ScrollerComponent { }); $(window).bind('resize', function () { scrollerSample.refresh(); - }); }); + }); + + }); } @@ -2893,9 +3050,20 @@ module sunburstcomponent { enableAnimation:false, size:{height:"600"}, innerRadius:0.2, + load: function () { + var sender = $("#Sunburst").data("ejSunburstChart"); + var SunBurstTheme = window.themeStyle + window.themeColor + window.themeVarient; + SunBurstTheme = SunBurstTheme.toString(); + if (SunBurstTheme.indexOf("dark") > -1 || SunBurstTheme.indexOf("contrast") > -1) + SunBurstTheme = "flatdark"; + else + SunBurstTheme = "flatlight"; + sender.model.theme = SunBurstTheme; + }, title:{text:"Employees Count"}, zoomSettings:{enable:false}, - legend:{visible:true,position:'top'} + legend:{visible:true,position:'top'}, + load:"loadTheme" }); }); } diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index e9f83b680c..ae1948ba86 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 15.3 +// Type definitions for ej.web.all 15.4 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,10 @@ /// + /*! * filename: ej.web.all.d.ts -* version : 15.3.0.33 +* version : 15.4.0.17 * Copyright Syncfusion Inc. 2001 - 2017. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -54,7 +55,7 @@ declare namespace ej { function getNameSpace(className: string): string; function getOffset(ele: string): any; function getRenderMode(): string; - function getScrollableParents(element: any): void; + function getScrollableParents(element: any): JQuery; function getTheme(): string; function getZindexPartial(element: any, popupEle: string): number; function hasRenderMode(element: string): void; @@ -5131,6 +5132,10 @@ declare namespace ej { */ beforeUpload?(e: BeforeUploadEventArgs): void; + /** Fires before opening the upload dialog. + */ + beforeUploadDialogOpen?(e: BeforeUploadDialogOpenEventArgs): void; + /** Fires when FileExplorer control was created */ create?(e: CreateEventArgs): void; @@ -5355,6 +5360,21 @@ declare namespace ej { type?: string; } + export interface BeforeUploadDialogOpenEventArgs { + + /** returns Selected FileList objects + */ + files?: any; + + /** returns the FileExplorer model + */ + model?: any; + + /** returns the name of the event. + */ + type?: string; + } + export interface CreateEventArgs { /** Set to true when the event has to be canceled, else false. @@ -16921,6 +16941,11 @@ declare namespace ej { */ readOnly?: boolean; + /** Shows/Hides the increment and decrement buttons of the slider. + * @Default {false} + */ + showButtons?: boolean; + /** Specifies the rounded corner behavior for slider. * @Default {false} */ @@ -32630,17 +32655,13 @@ declare namespace ej { export interface ActionBeginEventArgs { - /** Returns the current date value. - */ - currentDate?: any; - /** Returns the cancel option value. */ cancel?: boolean; - /** Returns the current view value. + /** Returns the data about the view change action. */ - currentView?: string; + data?: any; /** Returns the Schedule model. */ @@ -32650,21 +32671,17 @@ declare namespace ej { */ requestType?: string; - /** Returns the target of the click. - */ - target?: any; - /** Returns the name of the event. */ type?: string; - /** Returns the save appointment value. + /** Returns the name of the CRUD action performed. */ - data?: any; + currentAction?: string; - /** Returns the id of delete appointment. + /** Returns the GUid of appointment. */ - id?: number; + id?: string; } export interface ActionCompleteEventArgs { @@ -32689,6 +32706,10 @@ declare namespace ej { */ type?: string; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the appointment data dropped. */ appointment?: any; @@ -32719,13 +32740,17 @@ declare namespace ej { export interface BeforeAppointmentRemoveEventArgs { + /** Returns the deleted appointment object. + */ + appointment?: any; + /** Returns the cancel option value. */ cancel?: boolean; - /** Returns the deleted appointment object. + /** Returns the name of the CRUD action performed. */ - appointment?: any; + currentAction?: string; /** Returns the Schedule model. */ @@ -32746,10 +32771,18 @@ declare namespace ej { */ cancel?: boolean; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -32881,14 +32914,14 @@ declare namespace ej { export interface CellClickEventArgs { - /** Returns the object of cellClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the index of the cell. + */ + cellIndex?: number; + /** Returns the end time of the clicked cell. */ endTime?: any; @@ -32897,6 +32930,14 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns day, date and time information. + */ + quickString?: string; + + /** Returns the object of the resource. + */ + resources?: any; + /** Returns the start time of the clicked cell. */ startTime?: any; @@ -32912,10 +32953,6 @@ declare namespace ej { export interface CellDoubleClickEventArgs { - /** Returns the object of cellDoubleClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -32928,6 +32965,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the object of the resource. + */ + resources?: any; + /** Returns the start time of the double clicked cell. */ startTime?: any; @@ -32943,26 +32984,30 @@ declare namespace ej { export interface CellHoverEventArgs { - /** Returns the object of cellHover event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; /** Returns the index of the hovered cell. */ - cellIndex?: any; + cellIndex?: number; - /** Returns the current date of the hovered cell. + /** Returns the end time of the clicked cell. */ - currentDate?: any; + endTime?: any; /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the object of the resource. + */ + resources?: any; + + /** Returns the start time of the clicked cell. + */ + startTime?: any; + /** Returns the target of the clicked cell. */ target?: any; @@ -33004,10 +33049,6 @@ declare namespace ej { export interface DragEventArgs { - /** Returns the object of dragOver event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33023,13 +33064,17 @@ declare namespace ej { /** Returns the name of the event. */ type?: string; + + /** Returns the default dragging interval range in minutes + */ + interval?: number; } export interface DragStartEventArgs { - /** Returns the object of dragStart event. + /** Returns the dragged appointment. */ - object?: any; + appointment?: any; /** Returns the cancel option value. */ @@ -33050,10 +33095,6 @@ declare namespace ej { export interface DragStopEventArgs { - /** Returns the object of dragDrop event. - */ - object?: any; - /** Returns the dropped appointment object. */ appointment?: any; @@ -33073,10 +33114,6 @@ declare namespace ej { export interface MenuItemClickEventArgs { - /** Returns the object of menuItemClick event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33089,6 +33126,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the right clicked cell details. + */ + targetInfo?: any; + /** Returns the name of the event. */ type?: string; @@ -33120,6 +33161,10 @@ declare namespace ej { */ target?: any; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the event. */ type?: string; @@ -33193,10 +33238,6 @@ declare namespace ej { export interface ResizeEventArgs { - /** Returns the object of resizing event. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; @@ -33205,6 +33246,10 @@ declare namespace ej { */ element?: any; + /** Returns the default appointment resizing range . + */ + interval?: number; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; @@ -33216,9 +33261,9 @@ declare namespace ej { export interface ResizeStartEventArgs { - /** Returns the object of resizeStart event. + /** Returns the object of the resized appointment. */ - object?: any; + appointment?: any; /** Returns the cancel option value. */ @@ -33239,10 +33284,6 @@ declare namespace ej { export interface ResizeStopEventArgs { - /** Returns the object of resizeStop event. - */ - object?: any; - /** Returns the resized appointment value. */ appointment?: any; @@ -33266,14 +33307,14 @@ declare namespace ej { export interface OverflowButtonClickEventArgs { - /** Returns the object consisting of start time, end time and resource value of the underlying cell on which the clicked overflow button is present. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the icon rendered cell information. + */ + Datas?: any; + /** Returns the object of menu item event. */ events?: any; @@ -33289,17 +33330,17 @@ declare namespace ej { export interface OverflowButtonHoverEventArgs { - /** Returns the object consisting of start time, end time and resource value of the underlying cell on which the overflow button is currently hovered. - */ - object?: any; - /** Returns the cancel option value. */ cancel?: boolean; + /** Returns the icon rendered cell information. + */ + datas?: any; + /** Returns the object of menu item event. */ - events?: any; + event?: any; /** Returns the Schedule model. */ @@ -33343,6 +33384,10 @@ declare namespace ej { */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -33358,10 +33403,18 @@ declare namespace ej { */ cancel?: boolean; + /** Returns the name of the CRUD action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -33377,10 +33430,18 @@ declare namespace ej { */ appointment?: any; + /** Returns the name of the CRDU action performed. + */ + currentAction?: string; + /** Returns the Schedule model. */ model?: ej.Schedule.Model; + /** Returns the name of the Scheduler event. + */ + requestType?: string; + /** Returns the name of the Scheduler event. */ type?: string; @@ -34190,6 +34251,11 @@ declare namespace ej { */ enablePredecessorValidation?: boolean; + /** Enables or disables serial number column for Gantt. When enabled, the records will be number sequenced. + * @Default {false} + */ + enableSerialNumber?: boolean; + /** Specifies the baseline background color in Gantt * @Default {#fba41c} */ @@ -34271,6 +34337,10 @@ declare namespace ej { */ editDialogFields?: EditDialogField[]; + /** Options for filtering and customizing filter actions. + */ + filterSettings?: FilterSettings; + /** Enables or disables the responsiveness of Gantt * @Default {false} */ @@ -34655,6 +34725,32 @@ declare namespace ej { */ workWeek?: any[]; + /** Specifies the view type for a project in the Gantt. + * @Default {ej.Gantt.ViewType.ProjectView} + */ + viewType?: ej.Gantt.ViewType|string; + + /** Specifies the data collection for grouping the resources in resource allocation view in Gantt. + * @Default {[]} + */ + groupCollection?: any[]; + + /** Default Value + */ + resourceCollectionMapping?: string; + + /** Default Value + */ + taskCollectionMapping?: string; + + /** Default Value + */ + groupIdMapping?: string; + + /** Default Value + */ + groupNameMapping?: string; + /** Triggered for every Gantt action before its starts. */ actionBegin?(e: ActionBeginEventArgs): void; @@ -35479,6 +35575,33 @@ declare namespace ej { editType?: string; } + export interface FilterSettingsFilteredColumn { + + /** Specifies the value to be filtered in Gantt. + */ + value?: string; + + /** Specifies the field where filtering has to be performed. + */ + field?: string; + + /** Specifies the predicate(and/or) value to perform filtering. + */ + predicate?: string; + + /** Specifies the filter condition to filtered column. See operator + */ + operator?: string; + } + + export interface FilterSettings { + + /** Specifies the column collection for filtering the Gantt content on initial load + * @Default {[]} + */ + filteredColumns?: FilterSettingsFilteredColumn[]; + } + export interface SplitterSettings { /** Specifies position of the splitter in Gantt , splitter can be placed either based on percentage values or pixel values. @@ -35867,6 +35990,16 @@ declare namespace ej { TimeScale24Hours } + + enum ViewType { + + ///Displays the project in task view in Gantt. + ProjectView, + + ///Displays the project in resource allocation view in Gantt. + ResourceView + } + } class ReportViewer extends ej.Widget { @@ -36620,6 +36753,141 @@ declare namespace ej { * @returns {void} */ reorderColumn(fieldName: string, targetIndex: string): void; + + /** To get the updated data source of TreeGrid. + * @returns {any[]} + */ + getUpdatedRecords(): any[]; + + /** Sends request to navigate to a specific page in TreeGrid. + * @param {number} Pass the page index to perform paging at specified page index. + * @returns {void} + */ + gotoPage(PageIndex: number): void; + + /** To change the checkbox selection to any column. + * @param {string} Pass the column field name to check box selection to that column. + * @returns {void} + */ + updateCheckboxColumn(fieldName: string): void; + + /** Gets the selected cell(s) element details in TreeGrid. + * @returns {any[]} + */ + getSelectedCells(): any[]; + + /** Sets the minimum responsive width for TreeGrid. + * @param {string} Pass the minimum responsive width, above which the TreeGrid needs to work in responsive mode. + * @returns {void} + */ + updateResponsiveMinWidth(width: string): void; + + /** To open the dialog to add new record/row in TreeGrid. + * @returns {void} + */ + showAddDialog(): void; + + /** To open the dialog to edit a row/record in TreeGrid. + * @param {number} Pass the index of row to be edit. + * @returns {void} + */ + showEditDialog(Index: number): void; + + /** Sets the scroll left and scroll top offsets of TreeGrid. + * @param {string} Pass a value to set left position of horizontal scroll bar. + * @param {string} Pass a value to set top position of vertical scroll bar. + * @returns {void} + */ + scrollOffset(Left: string, Top: string): void; + + /** Gets the scroll top offset of TreeGrid. + * @returns {number} + */ + getScrollTopOffset(): number; + + /** Gets the scroll left offset of TreeGrid. + * @returns {number} + */ + getScrollLeftOffset(): number; + + /** Sets the scroll top offset of TreeGrid to 0. + * @returns {void} + */ + scrollToTop(): void; + + /** Sets the scroll top offset of TreeGrid to maximum value. + * @returns {void} + */ + scrollToBottom(): void; + + /** To expand and collapse an item in TreeGrid using item’s index. + * @param {number} Pass the row index of row to expand/collapse. + * @returns {void} + */ + expandCollapseRow(Index: number): void; + + /** To expand all the root level nodes in TreeGrid. + * @returns {void} + */ + expandAll(): void; + + /** Show/Hide the detail row of a specific record. + * @param {number} Pass the row index of record to show/hide the detail row. + * @returns {void} + */ + showHideDetailsRow(rowIndex: number): void; + + /** Sends filtering request to filter a column in TreeGrid. + * @param {string} Pass the field name of the column. + * @param {string} string/integer/dateTime operator. + * @param {string} Pass the value to be filtered in a column. + * @param {string} Pass the predicate as and/or. + * @param {boolean} Optional pass the match case value as true/false. + * @param {any} Optional actualFilterValue denote the filter object of current filtered columns. + * @returns {void} + */ + filterColumn(fieldName: string, filterOperator: string, filterValue: string, predicate: string, matchcase: boolean, actualFilterValue: any): void; + + /** To change the index of the tree column in TreeGrid. + * @param {number} Pass the column index to make the column as treeColumnIndex. + * @returns {void} + */ + columnIndex(Index: number): void; + + /** To clear the sorting from sorted columns in TreeGrid. + * @returns {void} + */ + clearSorting(): void; + + /** Gets the column index of specific column with data source field. + * @param {string} Pass the column field name to get its index. + * @returns {number} + */ + getColumnIndexByField(fieldName: string): number; + + /** Gets the column field name using column header text. + * @param {string} Pass the column header text to get its field name. + * @returns {string} + */ + getFieldNameByHeaderText(headerText: string): string; + + /** Gets the column object of specific column. + * @param {string} Pass the column header text to get details of that column. + * @returns {any} + */ + getColumnByHeaderText(headerText: string): any; + + /** Clears the filter applied to a specific column. + * @param {string} Pass the column field name to clear filtering done in that column. + * @returns {void} + */ + clearFilter(fieldName: string): void; + + /** Gets the column object of specific column. + * @param {string} Pass the column field name to get details of that column. + * @returns {any} + */ + getColumnByField(fieldName: string): any; } export namespace TreeGrid { @@ -36851,6 +37119,16 @@ declare namespace ej { */ detailsRowHeight?: number; + /** Gets or sets a value that indicates stacked header should be shown on TreeGrid layout when the property “stackedHeaderRows” is set. + * @Default {false} + */ + showStackedHeader?: boolean; + + /** Gets or sets an object that indicates to managing the collection of stacked header rows for the treegrid. + * @Default {[]} + */ + stackedHeaderRows?: StackedHeaderRow[]; + /** Specifies the visibility of summary row * @Default {false} */ @@ -38263,6 +38541,42 @@ declare namespace ej { enableSelectAll?: boolean; } + export interface StackedHeaderRowsStackedHeaderColumn { + + /** Gets or sets a value that indicates the header text for the particular stacked header column. + * @Default {null} + */ + column?: any; + + /** Gets or sets a value that indicates class to the corresponding stackedHeaderColumn. + * @Default {null} + */ + cssClass?: string; + + /** Gets or sets a value that indicates the header text for the particular stacked header column. + * @Default {null} + */ + headerText?: string; + + /** Gets or sets a value that indicates the text alignment of the corresponding headerText. + * @Default {ej.TextAlign.Left} + */ + textAlign?: string; + + /** Sets the template for tooltip for the Grid stackedHeaderColumns. + * @Default {null} + */ + tooltip?: string; + } + + export interface StackedHeaderRow { + + /** Gets or sets a value that indicates whether to add stacked header columns into the stacked header rows + * @Default {[]} + */ + stackedHeaderColumns?: StackedHeaderRowsStackedHeaderColumn[]; + } + export interface SummaryRowsSummaryColumn { /** Specifies the summary type to perform calculations in a corresponding summary column. See summaryType. @@ -39019,63 +39333,79 @@ declare namespace ej { export interface AjaxCompleteEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. + /** Instance of the navigation drawer model object. + */ + model?: ej.NavigationDrawer.Model; + + /** Name of the event. */ type?: string; - /** returns the model value of the control. + /** URL of the content. */ - model?: ej.NavigationDrawer.Model; + URL?: string; + + /** Response content. + */ + data?: string; } export interface AjaxErrorEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. - */ - type?: string; - - /** returns the model value of the control. + /** Instance of the navigation drawer model object. */ model?: ej.NavigationDrawer.Model; - /** returns the error thrown in the AJAX post. + /** Name of the event. */ - errorThrown?: any; + type?: string; - /** returns the status. + /** URL of the content. */ - textStatus?: any; + URL?: string; + + /** Error page content. + */ + responseText?: string; + + /** Error code. + */ + status?: number; + + /** The corresponding error description. + */ + statusText?: string; } export interface AjaxSuccessEventArgs { - /** returns true if the event should be canceled; otherwise, false. + /** Set this option to true to cancel the event. */ cancel?: boolean; - /** returns the name of the event. - */ - type?: string; - - /** returns the model value of the control. + /** Instance of the navigation drawer model object. */ model?: ej.NavigationDrawer.Model; - /** returns the AJAX current content. + /** Name of the event. */ - content?: string; + type?: string; - /** returns the current URL of the AJAX post. + /** URL of the content. */ URL?: string; + + /** Response content. + */ + data?: string; } export interface BeforeCloseEventArgs { @@ -45056,6 +45386,12 @@ declare namespace ej { */ enableAsync?: boolean; + /** Sets the data type for the ajax call used within the SpellCheck control, denoting the type of data that are expected to be retrieved from the server. The applicable values are + * json and jsonp. + * @Default {jsonp} + */ + ajaxDataType?: string; + /** Triggers on the success of AJAX call request. */ actionSuccess?(e: ActionSuccessEventArgs): void; @@ -45789,209 +46125,283 @@ declare namespace ej.datavisualization { destroy(): void; /** To export Image + * @param {number} for the Image + * @param {number} for the Image * @returns {void} */ - exportImage(): void; + exportImage(fileName: number, fileType: number): void; /** To get Bar Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarDistanceFromScale(): any; + getBarDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get Bar Pointer Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarPointerValue(): any; + getBarPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get Bar Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBarWidth(): any; + getBarWidth(scaleIndex: number, pointerIndex: number): any; /** To get CustomLabel Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelAngle(): any; + getCustomLabelAngle(scaleIndex: number, customLabelIndex: number): any; /** To get CustomLabel Value in string + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelValue(): any; + getCustomLabelValue(scaleIndex: number, customLabelIndex: number): any; /** To get Label Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelAngle(): any; + getLabelAngle(scaleIndex: number, labelIndex: number): any; /** To get LabelPlacement in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelPlacement(): any; + getLabelPlacement(scaleIndex: number, labelIndex: number): any; /** To get LabelStyle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelStyle(): any; + getLabelStyle(scaleIndex: number, labelIndex: number): any; /** To get Label XDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelXDistanceFromScale(): any; + getLabelXDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getLabelYDistanceFromScale(): any; + getLabelYDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get Major Interval Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMajorIntervalValue(): any; + getMajorIntervalValue(scaleIndex: number): any; /** To get MarkerStyle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerStyle(): any; + getMarkerStyle(scaleIndex: number, pointerIndex: number): any; /** To get Maximum Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMaximumValue(): any; + getMaximumValue(scaleIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getMinimumValue(): any; + getMinimumValue(scaleIndex: number, pointerIndex: number): any; /** To get Minor Interval Value in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinorIntervalValue(): any; + getMinorIntervalValue(scaleIndex: number): any; /** To get Pointer Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerDistanceFromScale(): any; + getPointerDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get PointerHeight in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerHeight(): any; + getPointerHeight(scaleIndex: number, pointerIndex: number): any; /** To get Pointer Placement in String + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerPlacement(): any; + getPointerPlacement(scaleIndex: number, pointerIndex: number): any; /** To get PointerValue in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerValue(): any; + getPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get PointerWidth in number + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerWidth(): any; + getPointerWidth(scaleIndex: number, pointerIndex: number): any; /** To get Range Border Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeBorderWidth(): any; + getRangeBorderWidth(scaleIndex: number, rangeIndex: number): any; /** To get Range Distance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeDistanceFromScale(): any; + getRangeDistanceFromScale(scaleIndex: number, rangeIndex: number): any; /** To get Range End Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndValue(): any; + getRangeEndValue(scaleIndex: number, rangeIndex: number): any; /** To get Range End Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndWidth(): any; + getRangeEndWidth(scaleIndex: number, rangeIndex: number): any; /** To get Range Position in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangePosition(): any; + getRangePosition(scaleIndex: number, rangeIndex: number): any; /** To get Range Start Value in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartValue(): any; + getRangeStartValue(scaleIndex: number, rangeIndex: number): any; /** To get Range Start Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartWidth(): any; + getRangeStartWidth(scaleIndex: number, rangeIndex: number): any; /** To get ScaleBarLength in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBarLength(): any; + getScaleBarLength(scaleIndex: number): any; /** To get Scale Bar Size in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getScaleBarSize(): any; + getScaleBarSize(scaleIndex: number, pointerIndex: number): any; /** To get Scale Border Width in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBorderWidth(): any; + getScaleBorderWidth(scaleIndex: number): any; /** To get Scale Direction in number + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleDirection(): any; + getScaleDirection(scaleIndex: number): any; /** To get Scale Location in object + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleLocation(): any; + getScaleLocation(scaleIndex: number): any; /** To get Scale Style in string + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleStyle(): any; + getScaleStyle(scaleIndex: number): any; /** To get Tick Angle in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickAngle(): any; + getTickAngle(scaleIndex: number, tickIndex: number): any; /** To get Tick Height in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickHeight(): any; + getTickHeight(scaleIndex: number, tickIndex: number): any; /** To get getTickPlacement in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickPlacement(): any; + getTickPlacement(scaleIndex: number, tickIndex: number): any; /** To get Tick Style in string + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickStyle(): any; + getTickStyle(scaleIndex: number, tickIndex: number): any; /** To get Tick Width in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickWidth(): any; + getTickWidth(scaleIndex: number, tickIndex: number): any; /** To get get Tick XDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickXDistanceFromScale(): any; + getTickXDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** To get Tick YDistance From Scale in number + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge * @returns {any} */ - getTickYDistanceFromScale(): any; + getTickYDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** Specifies the scales. * @returns {void} @@ -45999,204 +46409,314 @@ declare namespace ej.datavisualization { scales(): void; /** To set setBarDistanceFromScale + * @param {number} scaleIndex,value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar DistanceFromScale value for Gauge * @returns {void} */ - setBarDistanceFromScale(): void; + setBarDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setBarPointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar Pointer Value for Gauge * @returns {void} */ - setBarPointerValue(): void; + setBarPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setBarWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Bar Width for Gauge * @returns {void} */ - setBarWidth(): void; + setBarWidth(scaleIndex: number, pointerIndex: number, value: number): void; /** To set setCustomLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge + * @param {number} Custom Label Angle for Gauge * @returns {void} */ - setCustomLabelAngle(): void; + setCustomLabelAngle(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set setCustomLabelValue + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge + * @param {number} CustomLabel value for Gauge * @returns {void} */ - setCustomLabelValue(): void; + setCustomLabelValue(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set setLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label Angle for Gauge * @returns {void} */ - setLabelAngle(): void; + setLabelAngle(scaleIndex: number, labelIndex: number, angle: number): void; /** To set setLabelPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label Placement for Gauge * @returns {void} */ - setLabelPlacement(): void; + setLabelPlacement(scaleIndex: number, labelIndex: number, value: number): void; /** To set setLabelStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {string} Label Style for Gauge * @returns {void} */ - setLabelStyle(): void; + setLabelStyle(scaleIndex: number, labelIndex: number, value: string): void; /** To set setLabelXDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label XDistance From Scale for Gauge * @returns {void} */ - setLabelXDistanceFromScale(): void; + setLabelXDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set setLabelYDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Label YDistance From Scale for Gauge * @returns {void} */ - setLabelYDistanceFromScale(): void; + setLabelYDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set setMajorIntervalValue + * @param {number} scaleIndex value for the Gauge + * @param {number} Major Interval Value for Gauge * @returns {void} */ - setMajorIntervalValue(): void; + setMajorIntervalValue(scaleIndex: number, value: number): void; /** To set setMarkerStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {string} marker Style for Gauge * @returns {void} */ - setMarkerStyle(): void; + setMarkerStyle(scaleIndex: number, pointerIndex: number, value: string): void; /** To set setMaximumValue + * @param {number} scaleIndex value for the Gauge + * @param {number} MaximumValue for Gauge * @returns {void} */ - setMaximumValue(): void; + setMaximumValue(scaleIndex: number, value: number): void; /** To set setMinimumValue + * @param {number} scaleIndex value for the Gauge + * @param {number} MinimumValue for Gauge * @returns {void} */ - setMinimumValue(): void; + setMinimumValue(scaleIndex: number, value: number): void; /** To set setMinorIntervalValue + * @param {number} scaleIndex value for the Gauge + * @param {number} Minor Interval Value for Gauge * @returns {void} */ - setMinorIntervalValue(): void; + setMinorIntervalValue(scaleIndex: number, value: number): void; /** To set setPointerDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setPointerDistanceFromScale(): void; + setPointerDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setPointerHeight(): void; + setPointerHeight(scaleIndex: number, pointerIndex: number, height: number): void; /** To set setPointerPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} pointer placement for Gauge * @returns {void} */ - setPointerPlacement(): void; + setPointerPlacement(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Pointer value for Gauge * @returns {void} */ - setPointerValue(): void; + setPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge + * @param {number} Pointer width for Gauge * @returns {void} */ - setPointerWidth(): void; + setPointerWidth(scaleIndex: number, pointerIndex: number, width: number): void; /** To set setRangeBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Border Width for Gauge * @returns {void} */ - setRangeBorderWidth(): void; + setRangeBorderWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Distance FromScale for Gauge * @returns {void} */ - setRangeDistanceFromScale(): void; + setRangeDistanceFromScale(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeEndValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range end value for Gauge * @returns {void} */ - setRangeEndValue(): void; + setRangeEndValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeEndWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range End Width for Gauge * @returns {void} */ - setRangeEndWidth(): void; + setRangeEndWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangePosition + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Position for Gauge * @returns {void} */ - setRangePosition(): void; + setRangePosition(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeStartValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} range start value for Gauge * @returns {void} */ - setRangeStartValue(): void; + setRangeStartValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setRangeStartWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge + * @param {number} Range Start Width for Gauge * @returns {void} */ - setRangeStartWidth(): void; + setRangeStartWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set setScaleBarLength + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Bar Length for Gauge * @returns {void} */ - setScaleBarLength(): void; + setScaleBarLength(scaleIndex: number, value: number): void; /** To set setScaleBarSize + * @param {number} scaleIndex value for the Gauge + * @param {number} ScaleBarSize for Gauge * @returns {void} */ - setScaleBarSize(): void; + setScaleBarSize(scaleIndex: number, value: number): void; /** To set setScaleBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Border Width for Gauge * @returns {void} */ - setScaleBorderWidth(): void; + setScaleBorderWidth(scaleIndex: number, value: number): void; /** To set setScaleDirection + * @param {number} scaleIndex value for the Gauge + * @param {number} Scale Direction for Gauge * @returns {void} */ - setScaleDirection(): void; + setScaleDirection(scaleIndex: number, value: number): void; /** To set setScaleLocation + * @param {number} scaleIndex value for the Gauge + * @param {any} Scale position for Gauge * @returns {void} */ - setScaleLocation(): void; + setScaleLocation(scaleIndex: number, value: any): void; /** To set setScaleStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} for Gauge * @returns {void} */ - setScaleStyle(): void; + setScaleStyle(scaleIndex: number, value: number): void; /** To set setTickAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Angle for Gauge * @returns {void} */ - setTickAngle(): void; + setTickAngle(scaleIndex: number, tickIndex: number, angle: number): void; /** To set setTickHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Height for Gauge * @returns {void} */ - setTickHeight(): void; + setTickHeight(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Placement for Gauge * @returns {void} */ - setTickPlacement(): void; + setTickPlacement(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {string} Tick Style for Gauge * @returns {void} */ - setTickStyle(): void; + setTickStyle(scaleIndex: number, tickIndex: number, value: string): void; /** To set setTickWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick Width for Gauge * @returns {void} */ - setTickWidth(): void; + setTickWidth(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickXDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick XDistance From Scale for Gauge * @returns {void} */ - setTickXDistanceFromScale(): void; + setTickXDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; /** To set setTickYDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} value for the Gauge + * @param {number} Tick YDistance From Scale for Gauge * @returns {void} */ - setTickYDistanceFromScale(): void; + setTickYDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; } export namespace LinearGauge { @@ -47833,419 +48353,601 @@ declare namespace ej.datavisualization { destroy(): void; /** To export Image + * @param {string} fileName for the Image + * @param {string} fileType for the Image * @returns {boolean} */ - exportImage(): boolean; + exportImage(fileName: string, fileType: string): boolean; /** To get BackNeedleLength + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getBackNeedleLength(): any; + getBackNeedleLength(scaleIndex: number, pointerIndex: number): any; /** To get CustomLabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelAngle(): any; + getCustomLabelAngle(scaleIndex: number, customLabelIndex: number): any; /** To get CustomLabelValue + * @param {number} scaleIndex value for the Gauge + * @param {number} customLabelIndex value for the Gauge * @returns {any} */ - getCustomLabelValue(): any; + getCustomLabelValue(scaleIndex: number, customLabelIndex: number): any; /** To get LabelAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelAngle(): any; + getLabelAngle(scaleIndex: number, labelIndex: number): any; /** To get LabelDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelDistanceFromScale(): any; + getLabelDistanceFromScale(scaleIndex: number, labelIndex: number): any; /** To get LabelPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelPlacement(): any; + getLabelPlacement(scaleIndex: number, labelIndex: number): any; /** To get LabelStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getLabelStyle(): any; + getLabelStyle(scaleIndex: number, labelIndex: number): any; /** To get MajorIntervalValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMajorIntervalValue(): any; + getMajorIntervalValue(scaleIndex: number): any; /** To get MarkerDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerDistanceFromScale(): any; + getMarkerDistanceFromScale(scaleIndex: number, pointerIndex: number): any; /** To get MarkerStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getMarkerStyle(): any; + getMarkerStyle(scaleIndex: number, pointerIndex: number): any; /** To get MaximumValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMaximumValue(): any; + getMaximumValue(scaleIndex: number): any; /** To get MinimumValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinimumValue(): any; + getMinimumValue(scaleIndex: number): any; /** To get MinorIntervalValue + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getMinorIntervalValue(): any; + getMinorIntervalValue(scaleIndex: number): any; /** To get NeedleStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getNeedleStyle(): any; + getNeedleStyle(scaleIndex: number, pointerIndex: number): any; /** To get PointerCapBorderWidth + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getPointerCapBorderWidth(): any; + getPointerCapBorderWidth(scaleIndex: number): any; /** To get PointerCapRadius + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getPointerCapRadius(): any; + getPointerCapRadius(scaleIndex: number): any; /** To get PointerLength + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerLength(): any; + getPointerLength(scaleIndex: number, pointerIndex: number): any; /** To get PointerNeedleType + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerNeedleType(): any; + getPointerNeedleType(scaleIndex: number, pointerIndex: number): any; /** To get PointerPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerPlacement(): any; + getPointerPlacement(scaleIndex: number, pointerIndex: number): any; /** To get PointerValue + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerValue(): any; + getPointerValue(scaleIndex: number, pointerIndex: number): any; /** To get PointerWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} pointerIndex value for the Gauge * @returns {any} */ - getPointerWidth(): any; + getPointerWidth(scaleIndex: number, pointerIndex: number): any; /** To get RangeBorderWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeBorderWidth(): any; + getRangeBorderWidth(scaleIndex: number, rangeIndex: number): any; /** To get RangeDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeDistanceFromScale(): any; + getRangeDistanceFromScale(scaleIndex: number, rangeIndex: number): any; /** To get RangeEndValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeEndValue(): any; + getRangeEndValue(scaleIndex: number, rangeIndex: number): any; /** To get RangePosition + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangePosition(): any; + getRangePosition(scaleIndex: number, rangeIndex: number): any; /** To get RangeSize + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeSize(): any; + getRangeSize(scaleIndex: number, rangeIndex: number): any; /** To get RangeStartValue + * @param {number} scaleIndex value for the Gauge + * @param {number} rangeIndex value for the Gauge * @returns {any} */ - getRangeStartValue(): any; + getRangeStartValue(scaleIndex: number, rangeIndex: number): any; /** To get ScaleBarSize + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBarSize(): any; + getScaleBarSize(scaleIndex: number): any; /** To get ScaleBorderWidth + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleBorderWidth(): any; + getScaleBorderWidth(scaleIndex: number): any; /** To get ScaleDirection + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleDirection(): any; + getScaleDirection(scaleIndex: number): any; /** To get ScaleRadius + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getScaleRadius(): any; + getScaleRadius(scaleIndex: number): any; /** To get StartAngle + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getStartAngle(): any; + getStartAngle(scaleIndex: number): any; /** To get SubGaugeLocation + * @param {number} scaleIndex value for the Gauge + * @param {number} GaugeIndex value for the Gauge * @returns {any} */ - getSubGaugeLocation(): any; + getSubGaugeLocation(scaleIndex: number, GaugeIndex: number): any; /** To get SweepAngle + * @param {number} scaleIndex value for the Gauge * @returns {any} */ - getSweepAngle(): any; + getSweepAngle(scaleIndex: number): any; /** To get TickAngle + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickAngle(): any; + getTickAngle(scaleIndex: number, tickIndex: number): any; /** To get TickDistanceFromScale + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickDistanceFromScale(): any; + getTickDistanceFromScale(scaleIndex: number, tickIndex: number): any; /** To get TickHeight + * @param {number} scaleIndex value for the Gauge + * @param {number} labelIndex value for the Gauge * @returns {any} */ - getTickHeight(): any; + getTickHeight(scaleIndex: number, labelIndex: number): any; /** To get TickPlacement + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickPlacement(): any; + getTickPlacement(scaleIndex: number, tickIndex: number): any; /** To get TickStyle + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickStyle(): any; + getTickStyle(scaleIndex: number, tickIndex: number): any; /** To get TickWidth + * @param {number} scaleIndex value for the Gauge + * @param {number} tickIndex value for the Gauge * @returns {any} */ - getTickWidth(): any; + getTickWidth(scaleIndex: number, tickIndex: number): any; /** To set includeFirstValue + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - includeFirstValue(): void; + includeFirstValue(scaleIndex: number, labelIndex: number, value: number): void; /** Switching the redraw option for the gauge + * @param {string} redraw value for the gauge * @returns {void} */ - redraw(): void; + redraw(value: string): void; /** To set BackNeedleLength + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setBackNeedleLength(): void; + setBackNeedleLength(scaleIndex: number, pointerIndex: number, value: number): void; /** To set CustomLabelAngle + * @param {number} scaleIndex value for the gauge + * @param {number} customLabelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setCustomLabelAngle(): void; + setCustomLabelAngle(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set CustomLabelValue + * @param {number} scaleIndex value for the gauge + * @param {number} customLabelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setCustomLabelValue(): void; + setCustomLabelValue(scaleIndex: number, customLabelIndex: number, value: number): void; /** To set LabelAngle + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} angle value for the gauge * @returns {void} */ - setLabelAngle(): void; + setLabelAngle(scaleIndex: number, labelIndex: number, angle: number): void; /** To set LabelDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelDistanceFromScale(): void; + setLabelDistanceFromScale(scaleIndex: number, labelIndex: number, value: number): void; /** To set LabelPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelPlacement(): void; + setLabelPlacement(scaleIndex: number, labelIndex: number, value: number): void; /** To set LabelStyle + * @param {number} scaleIndex value for the gauge + * @param {number} labelIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setLabelStyle(): void; + setLabelStyle(scaleIndex: number, labelIndex: number, value: number): void; /** To set MajorIntervalValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMajorIntervalValue(): void; + setMajorIntervalValue(scaleIndex: number, value: number): void; /** To set MarkerDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMarkerDistanceFromScale(): void; + setMarkerDistanceFromScale(scaleIndex: number, pointerIndex: number, value: number): void; /** To set MarkerStyle + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMarkerStyle(): void; + setMarkerStyle(scaleIndex: number, pointerIndex: number, value: number): void; /** To set MaximumValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMaximumValue(): void; + setMaximumValue(scaleIndex: number, value: number): void; /** To set MinimumValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMinimumValue(): void; + setMinimumValue(scaleIndex: number, value: number): void; /** To set MinorIntervalValue + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setMinorIntervalValue(): void; + setMinorIntervalValue(scaleIndex: number, value: number): void; /** To set NeedleStyle + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setNeedleStyle(): void; + setNeedleStyle(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerCapBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerCapBorderWidth(): void; + setPointerCapBorderWidth(scaleIndex: number, value: number): void; /** To set PointerCapRadius + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerCapRadius(): void; + setPointerCapRadius(scaleIndex: number, value: number): void; /** To set PointerLength + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerLength(): void; + setPointerLength(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerNeedleType + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerNeedleType(): void; + setPointerNeedleType(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerPlacement(): void; + setPointerPlacement(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerValue + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerValue(): void; + setPointerValue(scaleIndex: number, pointerIndex: number, value: number): void; /** To set PointerWidth + * @param {number} scaleIndex value for the gauge + * @param {number} pointerIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setPointerWidth(): void; + setPointerWidth(scaleIndex: number, pointerIndex: number, value: number): void; /** To set RangeBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeBorderWidth(): void; + setRangeBorderWidth(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeDistanceFromScale(): void; + setRangeDistanceFromScale(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeEndValue + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeEndValue(): void; + setRangeEndValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangePosition + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangePosition(): void; + setRangePosition(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeSize + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeSize(): void; + setRangeSize(scaleIndex: number, rangeIndex: number, value: number): void; /** To set RangeStartValue + * @param {number} scaleIndex value for the gauge + * @param {number} rangeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setRangeStartValue(): void; + setRangeStartValue(scaleIndex: number, rangeIndex: number, value: number): void; /** To set ScaleBarSize + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleBarSize(): void; + setScaleBarSize(scaleIndex: number, value: number): void; /** To set ScaleBorderWidth + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleBorderWidth(): void; + setScaleBorderWidth(scaleIndex: number, value: number): void; /** To set ScaleDirection + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleDirection(): void; + setScaleDirection(scaleIndex: number, value: number): void; /** To set ScaleRadius + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setScaleRadius(): void; + setScaleRadius(scaleIndex: number, value: number): void; /** To set StartAngle + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setStartAngle(): void; + setStartAngle(scaleIndex: number, value: number): void; /** To set SubGaugeLocation + * @param {number} scaleIndex value for the gauge + * @param {number} GaugeIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setSubGaugeLocation(): void; + setSubGaugeLocation(scaleIndex: number, GaugeIndex: number, value: number): void; /** To set SweepAngle + * @param {number} scaleIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setSweepAngle(): void; + setSweepAngle(scaleIndex: number, value: number): void; /** To set TickAngle + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickAngle(): void; + setTickAngle(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickDistanceFromScale + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickDistanceFromScale(): void; + setTickDistanceFromScale(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickHeight + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickHeight(): void; + setTickHeight(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickPlacement + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickPlacement(): void; + setTickPlacement(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickStyle + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickStyle(): void; + setTickStyle(scaleIndex: number, tickIndex: number, value: number): void; /** To set TickWidth + * @param {number} scaleIndex value for the gauge + * @param {number} tickIndex value for the gauge + * @param {number} value for the gauge * @returns {void} */ - setTickWidth(): void; + setTickWidth(scaleIndex: number, tickIndex: number, value: number): void; } export namespace CircularGauge { @@ -50694,7 +51396,7 @@ declare namespace ej.datavisualization { /** Options to customize the left, right, top and bottom margins of chart area. */ - Margin?: any; + margin?: Margin; /** Perspective angle of the 3D view. Chart appears closer when perspective angle is decreased, and distant when perspective angle is increased.This property is applicable only when * 3D view is enabled @@ -52245,6 +52947,11 @@ declare namespace ej.datavisualization { */ enableContrastColor?: boolean; + /** Displays the partially visible labels inside the chart Area + * @Default {false} + */ + showEdgeLabels?: boolean; + /** Options for customizing the border of the data label. */ border?: CommonSeriesOptionsMarkerDataLabelBorder; @@ -53790,6 +54497,29 @@ declare namespace ej.datavisualization { toggleSeriesVisibility?: boolean; } + export interface Margin { + + /** Spacing for the left margin of chart area. Setting positive value decreases the width of the chart area from left side. + * @Default {10} + */ + left?: number; + + /** Spacing for the right margin of chart area. Setting positive value decreases the width of the chart area from right side. + * @Default {10} + */ + right?: number; + + /** Spacing for the top margin of chart area. Setting positive value decreases the height of the chart area from the top. + * @Default {10} + */ + top?: number; + + /** Spacing for the bottom margin of the chart area. Setting positive value decreases the height of the chart area from the bottom. + * @Default {10} + */ + bottom?: number; + } + export interface PrimaryXAxisAlternateGridBandEven { /** Fill color for the even grid bands. @@ -56217,6 +56947,11 @@ declare namespace ej.datavisualization { */ enableContrastColor?: boolean; + /** Displays the partially visible data labels inside the chart Area. + * @Default {false} + */ + showEdgeLabels?: boolean; + /** Options for customizing the border of the data label. */ border?: SeriesMarkerDataLabelBorder; @@ -59604,14 +60339,18 @@ declare namespace ej.datavisualization { redraw(): void; /** To set the value for comparative measure in bullet graph. + * @param {number} value for the graph + * @param {number} value for the graph * @returns {void} */ - setComparativeMeasureSymbol(): void; + setComparativeMeasureSymbol(index: number, measure: number): void; /** To set the value for feature measure bar. + * @param {number} value for the graph + * @param {number} value for the graph * @returns {void} */ - setFeatureMeasureBarValue(): void; + setFeatureMeasureBarValue(index: number, measure: number): void; } export namespace BulletGraph { @@ -62830,6 +63569,13 @@ declare namespace ej.datavisualization { */ exportDiagram(options?: Diagram.Options): string; + /** The exportImage method is used to export the image passed through argument with different image format and exporting options as like exportDiagram method. + * @param {string} pass the base64String image to be exported. + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats. + * @returns {string} + */ + exportImage(image: string, options?: Diagram.Options): string; + /** Read a node/connector object by its name * @param {string} name of the node/connector that is to be identified * @returns {any} @@ -62844,6 +63590,18 @@ declare namespace ej.datavisualization { */ fitToPage(mode?: ej.datavisualization.Diagram.FitMode, region?: ej.datavisualization.Diagram.Region, margin?: any): void; + /** Get the diagram DOM element as a string along with dependent stylesheets. + * @param {any[]} If its specified, will get the diagram DOM element along with specified stylesheet references. Please note that you have to define absolute path for local CSS file. + * If not specified, will get the diagram content along with all stylesheets loaded in the document. + * @returns {void} + */ + getDiagramContent(styleSheets?: any[]): void; + + /** Get the bounds of the diagram. + * @returns {void} + */ + getDiagramBounds(): void; + /** Group the selected nodes and connectors * @returns {void} */ @@ -62888,9 +63646,17 @@ declare namespace ej.datavisualization { paste(object?: any, rename?: boolean): void; /** Print the diagram as image + * @param {Diagram.Options} options to print the desired region of diagram and print the diagram in multiple pages. * @returns {void} */ - print(): void; + print(options?: Diagram.Options): void; + + /** The printImage method is used to print the image passed through argument with desired region and multiple pages as like print method. + * @param {string} pass the base64String image to be printed. + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats. + * @returns {string} + */ + printImage(image: string, options?: Diagram.Options): string; /** Restore the last action that was reverted * @returns {void} @@ -63098,6 +63864,119 @@ declare namespace ej.datavisualization { /** to resize the diagram content to fill its allocated space. */ stretch?: ej.datavisualization.Diagram.Stretch; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while exporting the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while exporting the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** name of the file to be downloaded. + */ + fileName?: string; + + /** format of the exported file/data. + */ + format?: ej.datavisualization.Diagram.FileFormats; + + /** to set the region of the diagram to be exported. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to export any custom region of diagram. + */ + bounds?: any; + + /** to set margin to the exported data. + */ + margin?: any; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while exporting the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while exporting the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** to set the region of the diagram to be printed. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to print any custom region of diagram. + */ + bounds?: any; + + /** to resize the diagram content to fill its allocated space and printed. + */ + stretch?: ej.datavisualization.Diagram.Stretch; + + /** to print the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while printing the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while printing the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; + } + + export interface Options { + + /** to set the region of the diagram to be printed. + */ + region?: ej.datavisualization.Diagram.Region; + + /** to print any custom region of diagram. + */ + bounds?: any; + + /** to export the diagram into multiple pages + */ + multiplePage?: boolean; + + /** to set the page width of the diagram while printing the diagram into multiple pages. + */ + pageWidth?: number; + + /** to set the page height of the diagram while printing the diagram into multiple pages. + */ + pageHeight?: number; + + /** to sets the orientation of the page. + */ + pageOrientation?: ej.datavisualization.Diagram.PageOrientations; } export interface Zoom { @@ -63228,6 +64107,10 @@ declare namespace ej.datavisualization { */ showTooltip?: boolean; + /** Defines diagram serialization properties that would defines how the serialization content would be. + */ + serializationSettings?: SerializationSettings; + /** Defines the properties of the both the horizontal and vertical gauge to measure the diagram area. */ rulerSettings?: RulerSettings; @@ -63375,6 +64258,10 @@ declare namespace ej.datavisualization { /** Triggered when the diagram is rendered completely. */ create?(e: CreateEventArgs): void; + + /** Used to decide on the action on Diagramming elements at runtime. + */ + setTool?(e: SetToolEventArgs): void; } export interface AutoScrollChangeEventArgs { @@ -64144,6 +65031,17 @@ declare namespace ej.datavisualization { diagramId?: string; } + export interface SetToolEventArgs { + + /** Returns the port when mouse move over on it + */ + source?: any; + + /** Defines the tool to be activated. + */ + action?: ej.datavisualization.Diagram.ActiveTool; + } + export interface BackgroundImage { /** Defines how to align the background image over the diagram area. @@ -64266,6 +65164,11 @@ declare namespace ej.datavisualization { */ boundaryConstraints?: boolean; + /** Enables or disables the default behaviors of the label. + * @Default {ej.datavisualization.Diagram.LabelConstraints.None} + */ + constraints?: ej.datavisualization.Diagram.LabelConstraints|string; + /** Sets the fill color of the text area * @Default {transparent} */ @@ -64286,6 +65189,11 @@ declare namespace ej.datavisualization { */ fontSize?: number; + /** Sets the height of the label(the maximum value of label height and the connector height will be considered as label height) + * @Default {0} + */ + height?: number; + /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} */ @@ -65068,6 +65976,21 @@ declare namespace ej.datavisualization { * @Default {30} */ root?: string; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {100} + */ + springLength?: number; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {0.442} + */ + springFactor?: number; + + /** Defines how long edges should be, ideally. This will be the resting length for the springs. + * @Default {1000} + */ + maxIteration?: number; } export interface NodesAnnotation { @@ -65291,11 +66214,6 @@ declare namespace ej.datavisualization { */ stops?: any[]; - /** Defines the type of gradient - * @Default {linear} - */ - type?: string; - /** Defines the left most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ @@ -65319,11 +66237,6 @@ declare namespace ej.datavisualization { export interface NodesGradientRadialGradient { - /** Defines the type of gradient - * @Default {radial} - */ - type?: string; - /** Defines the position of the outermost circle * @Default {0} */ @@ -65438,6 +66351,11 @@ declare namespace ej.datavisualization { */ borderWidth?: number; + /** Enables or disables the default behaviors of the label. + * @Default {ej.datavisualization.Diagram.LabelConstraints.None} + */ + constraints?: ej.datavisualization.Diagram.LabelConstraints|string; + /** Sets the fill color of the text area * @Default {transparent} */ @@ -65458,6 +66376,11 @@ declare namespace ej.datavisualization { */ fontSize?: number; + /** Sets the height of the label(the maximum value of label height and the node height will be considered as label height) + * @Default {0} + */ + height?: number; + /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} */ @@ -65733,6 +66656,10 @@ declare namespace ej.datavisualization { * @Default {ej.datavisualization.Diagram.PortVisibility.Default} */ visibility?: ej.datavisualization.Diagram.PortVisibility|string; + + /** Sets the name of the node which contains this port. + */ + parent?: string; } export interface NodesShadow { @@ -65753,6 +66680,38 @@ declare namespace ej.datavisualization { opacity?: number; } + export interface NodesSubProcessEvent { + + /** Sets the type of the event by which the sub-process will be triggered + * @Default {ej.datavisualization.Diagram.BPMNEvents.Start} + */ + event?: ej.datavisualization.Diagram.BPMNEvents|string; + + /** Sets the fraction/ratio(relative to parent) that defines the position of the event shape + * @Default {ej.datavisualization.Diagram.Point(0.5, 0.5)} + */ + offset?: any; + + /** Sets the name of the BPMN event shape. + */ + name?: string; + + /** Defines the type of the event trigger + * @Default {ej.datavisualization.Diagram.BPMNTriggers.Message} + */ + trigger?: ej.datavisualization.Diagram.BPMNTriggers|string; + + /** An array of objects where each object represents a port + * @Default {[]} + */ + ports?: any[]; + + /** A collection of objects where each object represents a label + * @Default {[]} + */ + labels?: any[]; + } + export interface NodesSubProcess { /** Defines whether the BPMN sub process is without any prescribed order or not @@ -65782,7 +66741,7 @@ declare namespace ej.datavisualization { /** Defines the collection of events that need to be appended with BPMN Sub-Process */ - events?: any[]; + events?: NodesSubProcessEvent[]; /** Defines the loop type of a sub process. * @Default {ej.datavisualization.Diagram.BPMNLoops.None} @@ -65826,6 +66785,10 @@ declare namespace ej.datavisualization { * @Default {ej.datavisualization.Diagram.BPMNTasks.None} */ type?: ej.datavisualization.Diagram.BPMNTasks|string; + + /** Defines the collection of events that need to be appended with BPMN tasks + */ + events?: any[]; } export interface Node { @@ -66299,6 +67262,16 @@ declare namespace ej.datavisualization { export interface SelectedItemsUserHandle { + /** Sets the horizontal alignment of the user handle + * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} + */ + horizontalAlignment?: ej.datavisualization.Diagram.HorizontalAlignment|string; + + /** To set the margin of the user handle + * @Default {ej.datavisualization.Diagram.Margin()} + */ + margin?: any; + /** Defines the name of the user handle */ name?: string; @@ -66318,6 +67291,11 @@ declare namespace ej.datavisualization { */ enableMultiSelection?: boolean; + /** Sets the fraction/ratio(relative to node) that defines the position of the user handle + * @Default {ej.datavisualization.Diagram.point(0.5, 1)} + */ + offset?: any; + /** Sets the stroke color of the user handle * @Default {transparent} */ @@ -66341,6 +67319,11 @@ declare namespace ej.datavisualization { */ tool?: any; + /** Sets the vertical alignment of the user handle + * @Default {ej.datavisualization.Diagram.VerticalAlignment.Center} + */ + verticalAlignment?: ej.datavisualization.Diagram.VerticalAlignment|string; + /** Defines the visibility of the user handle * @Default {true} */ @@ -66400,6 +67383,14 @@ declare namespace ej.datavisualization { width?: number; } + export interface SerializationSettings { + + /** defines whether the default diagram properties can be serialized or not. + * @Default {false} + */ + preventDefaultValues?: boolean; + } + export interface RulerSettingsHorizontalRuler { /** Defines the number of intervals to be present on the each segment of the horizontal ruler. @@ -66776,6 +67767,8 @@ declare namespace ej.datavisualization { InheritCrispEdges, //Enables the contrast between clean edges of connector over rendering speed and geometric precision DragLimit, + //Enables or disables bridging over a connector, if bridging constraints disabled.. + BridgeObstacle, //Enables connector to be selected and dragged. Interaction, //Enables all constraints @@ -66802,6 +67795,22 @@ declare namespace ej.datavisualization { After, } } + namespace Diagram { + enum LabelConstraints { + //Disable all label Constraints + None, + //Enables label to be selected + Selectable, + //Enables label to be Dragged + Draggable, + //Enables label to be Resized + Resizable, + //Enables label to be Rotated + Rotatable, + //Enables all label constraints + All, + } + } namespace Diagram { enum LabelRelativeMode { //Sets the relativeMode as SegmentPath @@ -67645,6 +68654,16 @@ declare namespace ej.datavisualization { ZoomOut, } } + namespace Diagram { + enum ActiveTool { + //Set the default Tool + None, + //Activate the port tool to drag when the mouse is moved over the port + Drag, + //Activate the draw tool to draw when the mouse is moved over the port + Draw, + } + } class HeatMap extends ej.Widget { static fn: HeatMap; diff --git a/types/ejs-locals/index.d.ts b/types/ejs-locals/index.d.ts index 6398ee199f..5ddb36fea3 100644 --- a/types/ejs-locals/index.d.ts +++ b/types/ejs-locals/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/randometc/ejs-locals // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index 1be3f740bc..3043a1f473 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -1,6 +1,6 @@ -import elasticsearch = require("elasticsearch"); +import * as elasticsearch from "elasticsearch"; -var client = new elasticsearch.Client({ +let client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); @@ -10,26 +10,26 @@ client = new elasticsearch.Client({ 'box1.server.org', 'box2.server.org' ], - selector: function (hosts: any) { } + selector: (hosts: any) => { } }); client.ping({ requestTimeout: 30000 -}, function (error) { +}, (error) => { }); client.search({ q: 'pants' -}).then(function (body) { - var hits = body.hits.hits; -}, function (error) { +}).then((body) => { + const hits = body.hits.hits; +}, (error) => { }); client.indices.delete({ index: 'test_index', ignore: [404] -}).then(function (body) { -}, function (error) { +}).then((body) => { +}, (error) => { }); client.deleteByQuery({ @@ -39,8 +39,8 @@ client.deleteByQuery({ query: { } } -}).then(function (response) { -}, function (error) { +}).then((response) => { +}, (error) => { }); client.create({ @@ -103,7 +103,7 @@ client.cluster.stats({ client.count({ index: 'index_name' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -120,7 +120,7 @@ client.count({ } } } -}, function (err, response) { +}, (err, response) => { // ... }); @@ -132,7 +132,7 @@ client.explain({ // the query to score it against q: 'field:value' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -145,7 +145,7 @@ client.explain({ match: { title: 'test' } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -158,8 +158,7 @@ client.index({ tags: ['y', 'z'], published: true, } -}, function (error, response) { - +}, (error, response) => { }); client.mget({ @@ -170,7 +169,7 @@ client.mget({ { _index: 'indexC', _type: 'typeC', _id: '1' } ] } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -180,14 +179,14 @@ client.mget({ body: { ids: [1, 2, 3] } -}, function (error, response) { +}, (error, response) => { // ... }); client.search({ index: 'myindex', q: 'title:test' -}, function (error, response) { +}, (error, response) => { // ... }); @@ -207,7 +206,7 @@ client.search({ } } } -}, function (error, response) { +}, (error, response) => { // ... }); @@ -221,12 +220,11 @@ client.suggest({ } } } -}, function (error, response) { +}, (error, response) => { }); - // first we do a search, and specify a scroll timeout -var allTitles: string[] = []; +const allTitles: string[] = []; client.search({ index: 'myindex', // Set to 30 seconds because we are calling right back @@ -236,14 +234,14 @@ client.search({ q: 'title:test' }, function getMoreUntilDone(error, response) { // collect the title from each response - response.hits.hits.forEach(function (hit) { + response.hits.hits.forEach((hit) => { allTitles.push(hit.fields.title); }); if (response.hits.total !== allTitles.length) { // now we can call scroll over and over client.scroll({ - scrollId: response._scroll_id, + scrollId: response._scroll_id!, scroll: '30s' }, getMoreUntilDone); } else { @@ -258,8 +256,13 @@ client.indices.updateAliases({ { add: { index: 'logstash-2014.05', alias: 'logstash-current' } } ] } -}).then(function (response) { +}).then((response) => { // ... -}, function (error) { +}, (error) => { // ... }); + +// Errors +function testErrors() { + throw new elasticsearch.errors.AuthenticationException(); +} diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 1552652edd..8ab269768d 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -1,618 +1,624 @@ // Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski , Margus Lamp , Ahmad Ferdous Bin Alam +// Definitions by: Casper Skydt +// Blake Smith +// Dave Dunkin +// Jeffery Grajkowski +// Margus Lamp +// Ahmad Ferdous Bin Alam +// Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare module Elasticsearch { - export class Client { - constructor(params: ConfigOptions); - cat: Cat; - cluster: Cluster; - indices: Indices; - ingest: Ingest; - nodes: Nodes; - snapshot: Snapshot; - tasks: Tasks; - bulk(params: BulkIndexDocumentsParams): Promise; - bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; - clearScroll(params: ClearScrollParams): Promise; - count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; - count(params: CountParams): Promise; - create(params: CreateDocumentParams): Promise; - create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; - delete(params: DeleteDocumentParams): Promise; - delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; - deleteByQuery(params: DeleteDocumentByQueryParams): Promise; - deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; - deleteScript(params: DeleteScriptParams): Promise; - deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; - deleteTemplate(params: DeleteTemplateParams): Promise; - deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; - exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; - explain(params: ExplainParams): Promise; - explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; - fieldStats(params: FieldStatsParams): Promise; - fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; - get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; - get(params: GetParams): Promise>; - getScript(params: GetScriptParams): Promise; - getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; - getSource(params: GetSourceParams): Promise; - getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; - getTemplate(params: GetTemplateParams): Promise; - getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; - index(params: IndexDocumentParams): Promise; - index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - info(params: InfoParams): Promise; - info(params: InfoParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; - mget(params: MGetParams): Promise>; - msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; - msearch(params: MSearchParams): Promise>; - msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; - msearchTemplate(params: MSearchTemplateParams): Promise>; - mtermvectors(params: MTermVectorsParams): Promise; - mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; - ping(params: PingParams): Promise; - ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; - putScript(params: PutScriptParams): Promise; - putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; - putTemplate(params: PutTemplateParams): Promise; - putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; - reindex(params: ReindexParams): Promise; - reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; - reindexRethrottle(params: ReindexRethrottleParams): Promise; - reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; - renderSearchTemplate(params: RenderSearchTemplateParams): Promise; - renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; - scroll(params: ScrollParams): Promise>; - scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; - search(params: SearchParams): Promise>; - search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; - searchShards(params: SearchShardsParams): Promise; - searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; - searchTemplate(params: SearchTemplateParams): Promise; - searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; - suggest(params: SuggestParams): Promise; - suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; - termvectors(params: TermvectorsParams): Promise; - termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; - update(params: UpdateDocumentParams): Promise; - update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; - updateByQuery(params: UpdateDocumentByQueryParams): Promise; - updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; - close(): void; - } +export class Client { + constructor(params: ConfigOptions); + cat: Cat; + cluster: Cluster; + indices: Indices; + ingest: Ingest; + nodes: Nodes; + snapshot: Snapshot; + tasks: Tasks; + bulk(params: BulkIndexDocumentsParams): Promise; + bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams): Promise; + count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; + count(params: CountParams): Promise; + create(params: CreateDocumentParams): Promise; + create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; + delete(params: DeleteDocumentParams): Promise; + delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; + deleteByQuery(params: DeleteDocumentByQueryParams): Promise; + deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; + deleteScript(params: DeleteScriptParams): Promise; + deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; + deleteTemplate(params: DeleteTemplateParams): Promise; + deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; + exists(params: ExistsParams): Promise; + exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; + explain(params: ExplainParams): Promise; + explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; + fieldStats(params: FieldStatsParams): Promise; + fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; + get(params: GetParams): Promise>; + getScript(params: GetScriptParams): Promise; + getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; + getSource(params: GetSourceParams): Promise; + getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; + getTemplate(params: GetTemplateParams): Promise; + getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; + index(params: IndexDocumentParams): Promise; + index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): Promise; + info(params: InfoParams, callback: (error: any, response: any) => void): void; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): Promise>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): Promise>; + msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; + msearchTemplate(params: MSearchTemplateParams): Promise>; + mtermvectors(params: MTermVectorsParams): Promise; + mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; + ping(params: PingParams): Promise; + ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; + putScript(params: PutScriptParams): Promise; + putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; + putTemplate(params: PutTemplateParams): Promise; + putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; + reindex(params: ReindexParams): Promise; + reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; + reindexRethrottle(params: ReindexRethrottleParams): Promise; + reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; + renderSearchTemplate(params: RenderSearchTemplateParams): Promise; + renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; + scroll(params: ScrollParams): Promise>; + scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; + search(params: SearchParams): Promise>; + search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; + searchShards(params: SearchShardsParams): Promise; + searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; + searchTemplate(params: SearchTemplateParams): Promise; + searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; + suggest(params: SuggestParams): Promise; + suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; + termvectors(params: TermvectorsParams): Promise; + termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; + update(params: UpdateDocumentParams): Promise; + update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): Promise; + updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; + close(): void; +} - export interface ConfigOptions { - host?: any; - hosts?: any; - httpAuth?: string; - log?: any; - apiVersion?: string; - plugins?: any; - sniffOnStart?: boolean; - sniffInterval?: number; - sniffOnConnectionFault?: boolean; - maxRetries?: number; - requestTimeout?: number; - deadTimeout?: number; - pingTimeout?: number; - keepAlive?: boolean; - maxSockets?: number; - suggestCompression?: boolean; - connectionClass?: string; - sniffedNodesProtocol?: string; - ssl?: Object; - selector?: any; - defer?: () => void; - nodesToHostCallback?: any; - createNodeAgent?: any; - } +export interface ConfigOptions { + host?: any; + hosts?: any; + httpAuth?: string; + log?: any; + apiVersion?: string; + plugins?: any; + sniffOnStart?: boolean; + sniffInterval?: number; + sniffOnConnectionFault?: boolean; + maxRetries?: number; + requestTimeout?: number; + deadTimeout?: number; + pingTimeout?: number; + keepAlive?: boolean; + maxSockets?: number; + suggestCompression?: boolean; + connectionClass?: string; + sniffedNodesProtocol?: string; + ssl?: object; + selector?: any; + defer?: () => void; + nodesToHostCallback?: any; + createNodeAgent?: any; +} - export interface Explanation { - value: number; - description: string; - details: Explanation[]; - } +export interface Explanation { + value: number; + description: string; + details: Explanation[]; +} - export interface GenericParams { - requestTimeout?: number; - maxRetries?: number; - method?: string; - body?: any; - ignore?: number | number[]; - filterPath?: string | string[]; - } +export interface GenericParams { + requestTimeout?: number; + maxRetries?: number; + method?: string; + body?: any; + ignore?: number | number[]; + filterPath?: string | string[]; +} - export interface ShardsResponse { - total: number; - successful: number; - failed: number; - skipped: number; - } +export interface ShardsResponse { + total: number; + successful: number; + failed: number; + skipped: number; +} - /** - * A string of a number and a time unit. A time unit is one of - * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. - * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. - */ - export type TimeSpan = string; +/** + * A string of a number and a time unit. A time unit is one of + * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. + * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. + */ +export type TimeSpan = string; - export type NameList = string | string[] | boolean; - export type Refresh = boolean | "true" | "false" | "wait_for" | ""; - export type VersionType = "internal" | "external" | "external_gte" | "force"; - export type ExpandWildcards = "open" | "closed" | "none" | "all"; - export type DefaultOperator = "AND" | "OR"; - export type Conflicts = "abort" | "proceed"; +export type NameList = string | string[] | boolean; +export type Refresh = boolean | "true" | "false" | "wait_for" | ""; +export type VersionType = "internal" | "external" | "external_gte" | "force"; +export type ExpandWildcards = "open" | "closed" | "none" | "all"; +export type DefaultOperator = "AND" | "OR"; +export type Conflicts = "abort" | "proceed"; - export interface BulkIndexDocumentsParams extends GenericParams { - waitForActiveShards?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - type?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - pipeline?: string; - index?: string; - } +export interface BulkIndexDocumentsParams extends GenericParams { + waitForActiveShards?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + type?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + pipeline?: string; + index?: string; +} - export interface ClearScrollParams extends GenericParams { - scrollId: NameList; - } +export interface ClearScrollParams extends GenericParams { + scrollId: NameList; +} - export interface CountParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - minScore?: number; - preference?: string; - routing?: string; - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - index?: NameList; - type?: NameList; - } +export interface CountParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + minScore?: number; + preference?: string; + routing?: string; + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + index?: NameList; + type?: NameList; +} - export interface CountResponse { - count: number; - _shards: ShardsResponse; - } +export interface CountResponse { + count: number; + _shards: ShardsResponse; +} - export interface CreateDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - } +export interface CreateDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; +} - export interface CreateDocumentResponse { - _shards: ShardsResponse; - _index: string; - _type: string; - _id: string; - _version: number; - created: boolean; - result: string; - } +export interface CreateDocumentResponse { + _shards: ShardsResponse; + _index: string; + _type: string; + _id: string; + _version: number; + created: boolean; + result: string; +} - export interface DeleteDocumentParams extends GenericParams { - waitForActiveShards?: string; - parent?: string; - refresh?: Refresh; - routing?: string; - timeout?: TimeSpan; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id: string; - } +export interface DeleteDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + routing?: string; + timeout?: TimeSpan; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id: string; +} - export interface DeleteDocumentResponse { - _shards: ShardsResponse; - found: boolean; - _index: string; - _type: string; - _id: string; - _version: number; - result: string; - } +export interface DeleteDocumentResponse { + _shards: ShardsResponse; + found: boolean; + _index: string; + _type: string; + _id: string; + _version: number; + result: string; +} - export interface DeleteDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: string | string[] | boolean; - scroll?: string; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: string | string[] | boolean; - version?: number; - requestCache?: boolean; - refresh?: Refresh; - timeout?: TimeSpan; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index?: string; - type?: string; - } +export interface DeleteDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: string | string[] | boolean; + scroll?: string; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: string | string[] | boolean; + version?: number; + requestCache?: boolean; + refresh?: Refresh; + timeout?: TimeSpan; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index?: string; + type?: string; +} - export interface DeleteDocumentByQueryResponse { - took: number; - timed_out: boolean; - deleted: number; - batches: number; - version_conflicts: number; - noops: number; - retries: { - bulk: number; - search: number; - }; - throttled_millis: number; - requests_per_second: number; - throttled_until_millis: number; - total: number; - failures: any[]; - } +export interface DeleteDocumentByQueryResponse { + took: number; + timed_out: boolean; + deleted: number; + batches: number; + version_conflicts: number; + noops: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + requests_per_second: number; + throttled_until_millis: number; + total: number; + failures: any[]; +} - export interface DeleteScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface DeleteScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface DeleteTemplateParams extends GenericParams { - id: string; - } +export interface DeleteTemplateParams extends GenericParams { + id: string; +} - export interface ExistsParams extends GenericParams { - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - id: string; - index: string; - type: string; - } +export interface ExistsParams extends GenericParams { + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + id: string; + index: string; + type: string; +} - export interface ExplainParams extends GenericParams { - analyzeWildcard?: boolean; - analyzer?: string; - defaultOperator?: DefaultOperator; - df?: string; - storedFields?: NameList; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - parent?: string; - preference?: string; - q?: string; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - id?: string; - index?: string; - type?: string; - } +export interface ExplainParams extends GenericParams { + analyzeWildcard?: boolean; + analyzer?: string; + defaultOperator?: DefaultOperator; + df?: string; + storedFields?: NameList; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + parent?: string; + preference?: string; + q?: string; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + id?: string; + index?: string; + type?: string; +} - export interface ExplainResponse { - _index: string; - _type: string; - _id: string; - matched: boolean; - explanation: ExplainResponseDetails; - } +export interface ExplainResponse { + _index: string; + _type: string; + _id: string; + matched: boolean; + explanation: ExplainResponseDetails; +} - export interface ExplainResponseDetails { - value: number; - description: string; - details: ExplainResponseDetails[]; - } +export interface ExplainResponseDetails { + value: number; + description: string; + details: ExplainResponseDetails[]; +} - export interface FieldStatsParams extends GenericParams { - fields?: NameList; - level?: "indices" | "cluster"; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } +export interface FieldStatsParams extends GenericParams { + fields?: NameList; + level?: "indices" | "cluster"; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} - export interface FieldStatsResponse { - _shards: ShardsResponse; - indices: { [indexName: string]: FieldStatsResponseIndex }; - conflicts?: { [fieldName: string]: string }; - } +export interface FieldStatsResponse { + _shards: ShardsResponse; + indices: { [indexName: string]: FieldStatsResponseIndex }; + conflicts?: { [fieldName: string]: string }; +} - export interface FieldStatsResponseIndex { - fields: { [fieldName: string]: FieldStatsResponseField }; - } +export interface FieldStatsResponseIndex { + fields: { [fieldName: string]: FieldStatsResponseField }; +} - export interface FieldStatsResponseField { - max_doc: number; - doc_count: number; - density: number; - sum_doc_freq: number; - sum_total_term_freq: number; - min_value: any; - max_value: any; - is_searchable: string; - is_aggregatable: string; - } +export interface FieldStatsResponseField { + max_doc: number; + doc_count: number; + density: number; + sum_doc_freq: number; + sum_total_term_freq: number; + min_value: any; + max_value: any; + is_searchable: string; + is_aggregatable: string; +} - export interface GetParams extends GenericParams { - storedFields?: NameList; - parent?: string; - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetParams extends GenericParams { + storedFields?: NameList; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetResponse { - _index: string; - _type: string; - _id: string; - _version: number; - found: boolean; - _source: T; - } +export interface GetResponse { + _index: string; + _type: string; + _id: string; + _version: number; + found: boolean; + _source: T; +} - export interface GetScriptParams extends GenericParams { - id: string; - lang: string; - } +export interface GetScriptParams extends GenericParams { + id: string; + lang: string; +} - export interface GetSourceParams extends GenericParams { - preference?: string; - realtime?: boolean; - refresh?: boolean; - routing?: string; - _source: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - version?: number; - versionType?: VersionType; - id: string; - index: string; - type: string; - } +export interface GetSourceParams extends GenericParams { + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; + type: string; +} - export interface GetTemplateParams extends GenericParams { - id: string; - } +export interface GetTemplateParams extends GenericParams { + id: string; +} - export interface IndexDocumentParams extends GenericParams { - waitForActiveShards?: string; - opType?: "index" | "create"; - parent?: string; - refresh?: string; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: VersionType; - pipeline?: string; - id?: string; - index: string; - type: string; - body: T; - } +export interface IndexDocumentParams extends GenericParams { + waitForActiveShards?: string; + opType?: "index" | "create"; + parent?: string; + refresh?: string; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; + index: string; + type: string; + body: T; +} - export interface InfoParams extends GenericParams { - } +export interface InfoParams extends GenericParams { +} - export interface MGetParams extends GenericParams { - storedFields?: NameList; - preference?: string; - realtime?: Boolean; - refresh?: Boolean; - source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - index?: string; - type?: string; - } +export interface MGetParams extends GenericParams { + storedFields?: NameList; + preference?: string; + realtime?: boolean; + refresh?: boolean; + source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + index?: string; + type?: string; +} - export interface MGetResponse { - docs?: GetResponse[]; - } +export interface MGetResponse { + docs?: Array>; +} - export interface MSearchParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - maxConcurrentSearches?: number; - index?: NameList; - type?: NameList; - } +export interface MSearchParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + maxConcurrentSearches?: number; + index?: NameList; + type?: NameList; +} - export interface MSearchResponse { - responses?: SearchResponse[]; - } +export interface MSearchResponse { + responses?: Array>; +} - export interface MSearchTemplateParams extends GenericParams { - search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index?: NameList; - type?: NameList; - } +export interface MSearchTemplateParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index?: NameList; + type?: NameList; +} - export interface MTermVectorsParams extends GenericParams { - ids?: NameList; - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - } +export interface MTermVectorsParams extends GenericParams { + ids?: NameList; + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; +} - export interface PingParams extends GenericParams { - } +export interface PingParams extends GenericParams { +} - export interface PutScriptParams extends GenericParams { - id: string; - lang: string; - body: any; - } +export interface PutScriptParams extends GenericParams { + id: string; + lang: string; + body: any; +} - export interface PutTemplateParams extends GenericParams { - id: string; - body: any; - } +export interface PutTemplateParams extends GenericParams { + id: string; + body: any; +} - export interface ReindexParams extends GenericParams { - refresh?: boolean; - timeout?: TimeSpan; - waitForActiveShards?: string; - waitForCompletion?: boolean; - requestsPerSecond?: number; - body: { - conflicts?: string; - source: { - index: string | string[]; - type?: string | string[]; - query?: any; - sort?: any; - size?: number; - remote?: { - host: string; - username?: string; - password?: string; - } - }; - dest: { - index: string; - version_type?: string; - op_type?: string; - routing?: string; - pipeline?: string; - }; - script?: { - inline: string; - lang: string; +export interface ReindexParams extends GenericParams { + refresh?: boolean; + timeout?: TimeSpan; + waitForActiveShards?: string; + waitForCompletion?: boolean; + requestsPerSecond?: number; + body: { + conflicts?: string; + source: { + index: string | string[]; + type?: string | string[]; + query?: any; + sort?: any; + size?: number; + remote?: { + host: string; + username?: string; + password?: string; } }; - } - - export interface ReindexResponse { - took: number; - updated: number; - created: number; - batches: number; - version_conflicts: number; - retries: { - bulk: number; - search: number; + dest: { + index: string; + version_type?: string; + op_type?: string; + routing?: string; + pipeline?: string; }; - throttled_millis: number; - failures: any[]; - } + script?: { + inline: string; + lang: string; + } + }; +} - export interface ReindexRethrottleParams extends GenericParams { - requestsPerSecond: number; - taskId: string; - } +export interface ReindexResponse { + took: number; + updated: number; + created: number; + batches: number; + version_conflicts: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + failures: any[]; +} - export interface RenderSearchTemplateParams extends GenericParams { - id: string; - } +export interface ReindexRethrottleParams extends GenericParams { + requestsPerSecond: number; + taskId: string; +} - export interface ScrollParams extends GenericParams { - scroll: TimeSpan; - scrollId: string; - } +export interface RenderSearchTemplateParams extends GenericParams { + id: string; +} - export interface SearchParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - requestCache?: boolean; - index?: NameList; - type?: NameList; - } +export interface ScrollParams extends GenericParams { + scroll: TimeSpan; + scrollId: string; +} + +export interface SearchParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + requestCache?: boolean; + index?: NameList; + type?: NameList; +} export interface SearchResponse { took: number; @@ -622,7 +628,7 @@ declare module Elasticsearch { hits: { total: number; max_score: number; - hits: { + hits: Array<{ _index: string; _type: string; _id: string; @@ -634,977 +640,1022 @@ declare module Elasticsearch { highlight?: any; inner_hits?: any; sort?: string[]; - }[]; + }>; }; aggregations?: any; } - export interface SearchShardsParams extends GenericParams { - preference?: string; - routing?: string; - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - type: NameList; - } +export interface SearchShardsParams extends GenericParams { + preference?: string; + routing?: string; + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + type: NameList; +} - export interface SearchShardsResponse { - nodes: any; - shards: SearchShardsResponseShard[][]; - } +export interface SearchShardsResponse { + nodes: any; + shards: SearchShardsResponseShard[][]; +} - export interface SearchShardsResponseShard { - index: string; - node: string; - primary: boolean; - share: number; - state: string; - allocation_id: { - id: string; - }; - relocating_node: any; - } - - export interface SearchTemplateParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; - index: NameList; - type: NameList; - } - - export interface SuggestParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - preference?: string; - routing?: string; - index: NameList; - } - - export interface TermvectorsParams extends GenericParams { - termStatistics?: boolean; - fieldStatistics?: boolean; - fields?: NameList; - offsets?: boolean; - positions?: boolean; - payloads?: boolean; - preference?: string; - routing?: string; - parent?: string; - realtime?: boolean; - version?: number; - versionType?: VersionType; - index: string; - type: string; - id?: string; - } - - export interface UpdateDocumentParams extends GenericParams { - waitForActiveShards?: string; - fields?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - lang?: string; - parent?: string; - refresh?: Refresh; - retryOnConflict?: number; - routing?: string; - timeout?: TimeSpan; - timestamp?: Date | number; - ttl?: TimeSpan; - version?: number; - versionType?: "internal" | "force"; +export interface SearchShardsResponseShard { + index: string; + node: string; + primary: boolean; + share: number; + state: string; + allocation_id: { id: string; - index: string; - type: string; - } + }; + relocating_node: any; +} - export interface UpdateDocumentByQueryParams extends GenericParams { - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - explain?: boolean; - storedFields?: NameList; - docvalueFields?: NameList; - fielddataFields?: NameList; - from?: number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - conflicts?: Conflicts; - expandWildcards?: ExpandWildcards; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - pipeline?: string; - preference?: string; - q?: string; - routing?: NameList; - scroll?: TimeSpan; - searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: TimeSpan; - size?: number; - sort?: NameList; - _source?: NameList; - _sourceExclude?: NameList; - _sourceInclude?: NameList; - terminateAfter?: number; - stats?: NameList; - suggestField?: string; - suggestMode?: "missing" | "popular" | "always"; - suggestSize?: number; - suggestText?: string; - timeout?: TimeSpan; - trackScores?: boolean; - version?: boolean; - versionType?: boolean; - requestCache?: boolean; - refresh?: boolean; - waitForActiveShards?: string; - scrollSize?: number; - waitForCompletion?: boolean; - requestsPerSecond?: number; - index: NameList; - type: NameList; - } +export interface SearchTemplateParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index: NameList; + type: NameList; +} - export interface Cat { - aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; - aliases(params: CatAliasesParams): Promise; - allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; - allocation(params: CatAllocationParams): Promise; - count(params: CatCountParams, callback: (error: any, response: any) => void): void; - count(params: CatAllocationParams): Promise; - fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; - fielddata(params: CatFielddataParams): Promise; - health(params: CatHealthParams, callback: (error: any, response: any) => void): void; - health(params: CatHealthParams): Promise; - help(params: CatHelpParams, callback: (error: any, response: any) => void): void; - help(params: CatHelpParams): Promise; - indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; - indices(params: CatIndicesParams): Promise; - master(params: CatCommonParams, callback: (error: any, response: any) => void): void; - master(params: CatCommonParams): Promise; - nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodeattrs(params: CatCommonParams): Promise; - nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; - nodes(params: CatCommonParams): Promise; - pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: CatCommonParams): Promise; - plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; - plugins(params: CatCommonParams): Promise; - recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: CatRecoveryParams): Promise; - repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; - repositories(params: CatCommonParams): Promise; - segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: CatSegmentsParams): Promise; - shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; - shards(params: CatShardsParams): Promise; - snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; - snapshots(params: CatSnapshotsParams): Promise; - tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; - tasks(params: CatTasksParams): Promise; - threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; - threadPool(params: CatThreadPoolParams): Promise; - } +export interface SuggestParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: string; + index: NameList; +} - export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; +export interface TermvectorsParams extends GenericParams { + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id?: string; +} - export interface CatCommonParams extends GenericParams { - format: string; - local?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } +export interface UpdateDocumentParams extends GenericParams { + waitForActiveShards?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + lang?: string; + parent?: string; + refresh?: Refresh; + retryOnConflict?: number; + routing?: string; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; + version?: number; + versionType?: "internal" | "force"; + id: string; + index: string; + type: string; +} - export interface CatAliasesParams extends CatCommonParams { - name?: NameList; - } +export interface UpdateDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: Conflicts; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + pipeline?: string; + preference?: string; + q?: string; + routing?: NameList; + scroll?: TimeSpan; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: TimeSpan; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: TimeSpan; + trackScores?: boolean; + version?: boolean; + versionType?: boolean; + requestCache?: boolean; + refresh?: boolean; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index: NameList; + type: NameList; +} - export interface CatAllocationParams extends CatCommonParams { - bytes?: CatBytes; - nodeId?: NameList; - } +export interface Cat { + aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; + aliases(params: CatAliasesParams): Promise; + allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; + allocation(params: CatAllocationParams): Promise; + count(params: CatCountParams, callback: (error: any, response: any) => void): void; + count(params: CatAllocationParams): Promise; + fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; + fielddata(params: CatFielddataParams): Promise; + health(params: CatHealthParams, callback: (error: any, response: any) => void): void; + health(params: CatHealthParams): Promise; + help(params: CatHelpParams, callback: (error: any, response: any) => void): void; + help(params: CatHelpParams): Promise; + indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; + indices(params: CatIndicesParams): Promise; + master(params: CatCommonParams, callback: (error: any, response: any) => void): void; + master(params: CatCommonParams): Promise; + nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodeattrs(params: CatCommonParams): Promise; + nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodes(params: CatCommonParams): Promise; + pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: CatCommonParams): Promise; + plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; + plugins(params: CatCommonParams): Promise; + recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: CatRecoveryParams): Promise; + repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; + repositories(params: CatCommonParams): Promise; + segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: CatSegmentsParams): Promise; + shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; + shards(params: CatShardsParams): Promise; + snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; + snapshots(params: CatSnapshotsParams): Promise; + tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; + tasks(params: CatTasksParams): Promise; + threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; + threadPool(params: CatThreadPoolParams): Promise; +} - export interface CatCountParams extends CatCommonParams { - index?: NameList; - } +export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; - export interface CatFielddataParams extends CatCommonParams { - bytes?: CatBytes; - fields?: NameList; - } +export interface CatCommonParams extends GenericParams { + format: string; + local?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} - export interface CatHealthParams extends CatCommonParams { - ts?: boolean; - } +export interface CatAliasesParams extends CatCommonParams { + name?: NameList; +} - export interface CatHelpParams extends GenericParams { - help?: boolean; - } +export interface CatAllocationParams extends CatCommonParams { + bytes?: CatBytes; + nodeId?: NameList; +} - export interface CatIndicesParams extends CatCommonParams { - bytes?: CatBytes; - health?: "green" | "yellow" | "red"; - pri?: boolean; - index?: NameList; - } +export interface CatCountParams extends CatCommonParams { + index?: NameList; +} - export interface CatRecoveryParams extends GenericParams { - format: string; - bytes?: CatBytes; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - } +export interface CatFielddataParams extends CatCommonParams { + bytes?: CatBytes; + fields?: NameList; +} - export interface CatSegmentsParams extends GenericParams { - format: string; - h?: NameList; - help?: boolean; - v?: boolean; - index?: NameList; - } +export interface CatHealthParams extends CatCommonParams { + ts?: boolean; +} - export interface CatShardsParams extends CatCommonParams { - index?: NameList; - } +export interface CatHelpParams extends GenericParams { + help?: boolean; +} - export interface CatSnapshotsParams extends GenericParams { - format: string; - ignoreUnavailable?: boolean; - masterTimeout?: TimeSpan; - h?: NameList; - help?: boolean; - v?: boolean; - repository?: NameList; - } +export interface CatIndicesParams extends CatCommonParams { + bytes?: CatBytes; + health?: "green" | "yellow" | "red"; + pri?: boolean; + index?: NameList; +} - export interface CatTasksParams extends GenericParams { - format: string; - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: number; - h?: NameList; - help?: boolean; - v?: boolean; - } +export interface CatRecoveryParams extends GenericParams { + format: string; + bytes?: CatBytes; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; +} - export interface CatThreadPoolParams extends CatCommonParams { - size?: "" | "k" | "m" | "g" | "t" | "p"; - threadPoolPatterns?: NameList; - } +export interface CatSegmentsParams extends GenericParams { + format: string; + h?: NameList; + help?: boolean; + v?: boolean; + index?: NameList; +} - export interface Cluster { - allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; - allocationExplain(params: ClusterAllocationExplainParams): Promise; - getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; - getSettings(params: ClusterGetSettingsParams): Promise; - health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; - health(params: ClusterHealthParams): Promise; - pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; - pendingTasks(params: ClusterPendingTasksParams): Promise; - putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; - putSettings(params: ClusterPutSettingsParams): Promise; - reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; - reroute(params: ClusterRerouteParams): Promise; - state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; - state(params: ClusterStateParams): Promise; - stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; - stats(params: ClusterStatsParams): Promise; - } +export interface CatShardsParams extends CatCommonParams { + index?: NameList; +} - export interface ClusterAllocationExplainParams extends GenericParams { - includeYesDecisions?: boolean; - includeDiskInfo?: boolean; - } +export interface CatSnapshotsParams extends GenericParams { + format: string; + ignoreUnavailable?: boolean; + masterTimeout?: TimeSpan; + h?: NameList; + help?: boolean; + v?: boolean; + repository?: NameList; +} - export interface ClusterGetSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - includeDefaults?: boolean; - } +export interface CatTasksParams extends GenericParams { + format: string; + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: number; + h?: NameList; + help?: boolean; + v?: boolean; +} - export interface ClusterHealthParams extends GenericParams { - level?: "cluster" | "indices" | "shards"; - local?: boolean; - masterTimeout?: TimeSpan; - waitForActiveShards?: string; - waitForNodes?: string; - waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; - waitForRelocatingShards?: boolean; - waitForStatus?: "green" | "yellow" | "red"; - index?: NameList; - } +export interface CatThreadPoolParams extends CatCommonParams { + size?: "" | "k" | "m" | "g" | "t" | "p"; + threadPoolPatterns?: NameList; +} - export interface ClusterPendingTasksParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - } +export interface Cluster { + allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; + allocationExplain(params: ClusterAllocationExplainParams): Promise; + getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsParams): Promise; + health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthParams): Promise; + pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksParams): Promise; + putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsParams): Promise; + reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteParams): Promise; + state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; + state(params: ClusterStateParams): Promise; + stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsParams): Promise; +} - export interface ClusterPutSettingsParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } +export interface ClusterAllocationExplainParams extends GenericParams { + includeYesDecisions?: boolean; + includeDiskInfo?: boolean; +} - export interface ClusterRerouteParams extends GenericParams { - dryRun?: boolean; - explain?: boolean; - retryFailed?: boolean; - metric?: NameList; - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - } +export interface ClusterGetSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + includeDefaults?: boolean; +} - export interface ClusterStateParams extends GenericParams { - local?: boolean; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - metric?: NameList; - } +export interface ClusterHealthParams extends GenericParams { + level?: "cluster" | "indices" | "shards"; + local?: boolean; + masterTimeout?: TimeSpan; + waitForActiveShards?: string; + waitForNodes?: string; + waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; + waitForRelocatingShards?: boolean; + waitForStatus?: "green" | "yellow" | "red"; + index?: NameList; +} - export interface ClusterStatsParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId?: NameList; - } +export interface ClusterPendingTasksParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; +} - export class Indices { - analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; - analyze(params: IndicesAnalyzeParams): Promise; - clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; - clearCache(params: IndicesClearCacheParams): Promise; - close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; - close(params: IndicesCloseParams): Promise; - create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: IndicesCreateParams): Promise; - delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: IndicesDeleteParams): Promise; - deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; - deleteAlias(params: IndicesDeleteAliasParams): Promise; - deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; - deleteTemplate(params: IndicesDeleteTemplateParams): Promise; - exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; - exists(params: IndicesExistsParams): Promise; - existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; - existsAlias(params: IndicesExistsAliasParams): Promise; - existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; - existsTemplate(params: IndicesExistsTemplateParams): Promise; - existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; - existsType(params: IndicesExistsTypeParams): Promise; - flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; - flush(params: IndicesFlushParams): Promise; - flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; - flushSynced(params: IndicesFlushSyncedParams): Promise; - forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; - forcemerge(params: IndicesForcemergeParams): Promise; - get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: IndicesGetParams): Promise; - getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; - getAlias(params: IndicesGetAliasParams): Promise; - getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; - getFieldMapping(params: IndicesGetFieldMappingParams): Promise; - getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; - getMapping(params: IndicesGetMappingParams): Promise; - getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; - getSettings(params: IndicesGetSettingsParams): Promise; - getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; - getTemplate(params: IndicesGetTemplateParams): Promise; - getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; - getUpgrade(params: IndicesGetUpgradeParams): Promise; - open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; - open(params: IndicesOpenParams): Promise; - putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; - putAlias(params: IndicesPutAliasParams): Promise; - putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; - putMapping(params: IndicesPutMappingParams): Promise; - putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; - putSettings(params: IndicesPutSettingsParams): Promise; - putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; - putTemplate(params: IndicesPutTemplateParams): Promise; - recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; - recovery(params: IndicesRecoveryParams): Promise; - refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; - refresh(params: IndicesRefreshParams): Promise; - rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; - rollover(params: IndicesRolloverParams): Promise; - segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; - segments(params: IndicesSegmentsParams): Promise; - shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; - shardStores(params: IndicesShardStoresParams): Promise; - shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; - shrink(params: IndicesShrinkParams): Promise; - stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; - stats(params: IndicesStatsParams): Promise; - updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; - updateAliases(params: IndicesUpdateAliasesParams): Promise; - upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; - upgrade(params: IndicesUpgradeParams): Promise; - validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; - validateQuery(params: IndicesValidateQueryParams): Promise; - } +export interface ClusterPutSettingsParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} - export interface IndicesAnalyzeParams extends GenericParams { - analyzer?: string; - charFilter?: NameList; - field?: string; - filter?: NameList; +export interface ClusterRerouteParams extends GenericParams { + dryRun?: boolean; + explain?: boolean; + retryFailed?: boolean; + metric?: NameList; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; +} + +export interface ClusterStateParams extends GenericParams { + local?: boolean; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + metric?: NameList; +} + +export interface ClusterStatsParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId?: NameList; +} + +export class Indices { + analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; + analyze(params: IndicesAnalyzeParams): Promise; + clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; + clearCache(params: IndicesClearCacheParams): Promise; + close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; + close(params: IndicesCloseParams): Promise; + create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: IndicesCreateParams): Promise; + delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: IndicesDeleteParams): Promise; + deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; + deleteAlias(params: IndicesDeleteAliasParams): Promise; + deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; + deleteTemplate(params: IndicesDeleteTemplateParams): Promise; + exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; + exists(params: IndicesExistsParams): Promise; + existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; + existsAlias(params: IndicesExistsAliasParams): Promise; + existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; + existsTemplate(params: IndicesExistsTemplateParams): Promise; + existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesExistsTypeParams): Promise; + flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; + flush(params: IndicesFlushParams): Promise; + flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; + flushSynced(params: IndicesFlushSyncedParams): Promise; + forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; + forcemerge(params: IndicesForcemergeParams): Promise; + get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: IndicesGetParams): Promise; + getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; + getAlias(params: IndicesGetAliasParams): Promise; + getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; + getFieldMapping(params: IndicesGetFieldMappingParams): Promise; + getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; + getMapping(params: IndicesGetMappingParams): Promise; + getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; + getSettings(params: IndicesGetSettingsParams): Promise; + getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; + getTemplate(params: IndicesGetTemplateParams): Promise; + getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; + getUpgrade(params: IndicesGetUpgradeParams): Promise; + open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; + open(params: IndicesOpenParams): Promise; + putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; + putAlias(params: IndicesPutAliasParams): Promise; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; + putMapping(params: IndicesPutMappingParams): Promise; + putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; + putSettings(params: IndicesPutSettingsParams): Promise; + putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; + putTemplate(params: IndicesPutTemplateParams): Promise; + recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: IndicesRecoveryParams): Promise; + refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; + refresh(params: IndicesRefreshParams): Promise; + rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; + rollover(params: IndicesRolloverParams): Promise; + segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: IndicesSegmentsParams): Promise; + shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; + shardStores(params: IndicesShardStoresParams): Promise; + shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; + shrink(params: IndicesShrinkParams): Promise; + stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; + stats(params: IndicesStatsParams): Promise; + updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; + updateAliases(params: IndicesUpdateAliasesParams): Promise; + upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; + upgrade(params: IndicesUpgradeParams): Promise; + validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; + validateQuery(params: IndicesValidateQueryParams): Promise; +} + +export interface IndicesAnalyzeParams extends GenericParams { + analyzer?: string; + charFilter?: NameList; + field?: string; + filter?: NameList; + index?: string; + perferLocal?: boolean; + text?: NameList; + tokenizer?: string; + explain?: boolean; + attributes?: NameList; + format?: ""; +} + +export interface IndicesClearCacheParams extends GenericParams { + fieldData?: boolean; + fielddata?: boolean; // yes the docs really have both + fields?: NameList; + query?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + recycler?: boolean; + request?: boolean; +} + +export interface IndicesCloseParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesCreateParams extends GenericParams { + waitForActiveShards?: string; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + updateAllTypes?: boolean; + index: string; +} + +export interface IndicesDeleteParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; +} + +export interface IndicesDeleteAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index: NameList; + name: NameList; +} + +export interface IndicesDeleteTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: string; +} + +export interface IndicesExistsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index: NameList; +} + +export interface IndicesExistsAliasParams extends IndicesExistsParams { + name: NameList; +} + +export interface IndicesExistsTemplateParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + name: NameList; +} + +export interface IndicesExistsTypeParams extends IndicesExistsParams { + type: NameList; +} + +export interface IndicesFlushParams extends GenericParams { + force?: boolean; + waitIfOngoing?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesFlushSyncedParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; +} + +export interface IndicesForcemergeParams extends GenericParams { + flush?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + maxNumSegments?: number; + onlyExpungeDeletes?: boolean; + operationThreading?: any; // even the docs don't know what this does + waitForMerge?: boolean; + index: NameList; +} + +export interface IndicesGetParams extends GenericParams { + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + feature?: NameList; +} + +export interface IndicesGetAliasParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetFieldMappingParams extends GenericParams { + includeDefaults?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; + fields?: NameList; +} + +export interface IndicesGetMappingParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; +} + +export interface IndicesGetSettingsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + local?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + name?: NameList; +} + +export interface IndicesGetTemplateParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: TimeSpan; + local?: boolean; + name?: NameList; +} + +export interface IndicesGetUpgradeParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + index?: NameList; +} + +export interface IndicesOpenParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; +} + +export interface IndicesPutAliasParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + index?: NameList; + name: NameList; +} + +export interface IndicesPutMappingParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + updateAllTypes?: boolean; + index: NameList; + type: string; + body: any; +} + +export interface IndicesPutSettingsParams extends GenericParams { + masterTimeout?: TimeSpan; + preserveExisting?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + index: NameList; + body: any; +} + +export interface IndicesPutTemplateParams extends GenericParams { + order?: number; + create?: boolean; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + flatSettings?: boolean; + name: string; + body: any; +} + +export interface IndicesRecoveryParams extends GenericParams { + detailed?: boolean; + activeOnly?: boolean; + human?: boolean; + index: NameList; +} + +export interface IndicesRefreshParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + force?: boolean; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesRolloverParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: number | string; + alias?: string; + newIndex?: string; +} + +export interface IndicesRolloverResponse { + acknowledged: boolean; + shards_acknowledged: boolean; + old_index: string; + new_index: string; + rolled_over: boolean; + dry_run: boolean; + conditions: { [condition: string]: boolean }; +} + +export interface IndicesSegmentsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + operationThreading?: any; // even the docs don't know what this does + verbose?: boolean; + index: NameList; +} + +export interface IndicesShardStoresParams extends GenericParams { + status?: NameList; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + index: NameList; +} + +export interface IndicesShrinkParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + waitForActiveShards?: string | number; + index: string; + target: string; +} + +export interface IndicesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: NameList; + human?: boolean; + level?: "cluster" | "indices" | "shards"; + types?: NameList; + index: NameList; + metric?: NameList; +} + +export interface IndicesUpdateAliasesParams extends GenericParams { + timeout?: TimeSpan; + masterTimeout?: TimeSpan; + body: { + actions: IndicesUpdateAliasesParamsAction[]; + }; +} + +export interface IndicesUpdateAliasesParamsAction { + add?: { index?: string; - perferLocal?: boolean; - text?: NameList; - tokenizer?: string; - explain?: boolean; - attributes?: NameList; - format?: ""; - } - - export interface IndicesClearCacheParams extends GenericParams { - fieldData?: boolean; - fielddata?: boolean; // yes the docs really have both - fields?: NameList; - query?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - recycler?: boolean; - request?: boolean; - } - - export interface IndicesCloseParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesCreateParams extends GenericParams { - waitForActiveShards?: string; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - updateAllTypes?: boolean; + indices?: string[]; + alias: string; + }; + remove?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove_index?: { index: string; - } - - export interface IndicesDeleteParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - } - - export interface IndicesDeleteAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index: NameList; - name: NameList; - } - - export interface IndicesDeleteTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: string; - } - - export interface IndicesExistsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index: NameList; - } - - export interface IndicesExistsAliasParams extends IndicesExistsParams { - name: NameList; - } - - export interface IndicesExistsTemplateParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - name: NameList; - } - - export interface IndicesExistsTypeParams extends IndicesExistsParams { - type: NameList; - } - - export interface IndicesFlushParams extends GenericParams { - force?: boolean; - waitIfOngoing?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesFlushSyncedParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index: NameList; - } - - export interface IndicesForcemergeParams extends GenericParams { - flush?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - maxNumSegments?: number; - onlyExpungeDeletes?: boolean; - operationThreading?: any; // even the docs don't know what this does - waitForMerge?: boolean; - index: NameList; - } - - export interface IndicesGetParams extends GenericParams { - local?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - feature?: NameList; - } - - export interface IndicesGetAliasParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetFieldMappingParams extends GenericParams { - includeDefaults?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - fields?: NameList; - } - - export interface IndicesGetMappingParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - local?: boolean; - index?: NameList; - type?: NameList; - } - - export interface IndicesGetSettingsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - local?: boolean; - human?: boolean; - includeDefaults?: boolean; - index?: NameList; - name?: NameList; - } - - export interface IndicesGetTemplateParams extends GenericParams { - flatSettings?: boolean; - masterTimeout?: TimeSpan; - local?: boolean; - name?: NameList; - } - - export interface IndicesGetUpgradeParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - index?: NameList; - } - - export interface IndicesOpenParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - index?: NameList; - } - - export interface IndicesPutAliasParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - index?: NameList; - name: NameList; - } - - export interface IndicesPutMappingParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - updateAllTypes?: boolean; - index: NameList; - type: string; - body: any; - } - - export interface IndicesPutSettingsParams extends GenericParams { - masterTimeout?: TimeSpan; - preserveExisting?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - flatSettings?: boolean; - index: NameList; - body: any; - } - - export interface IndicesPutTemplateParams extends GenericParams { - order?: number; - create?: boolean; - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - flatSettings?: boolean; - name: string; - body: any; - } - - export interface IndicesRecoveryParams extends GenericParams { - detailed?: boolean; - activeOnly?: boolean; - human?: boolean; - index: NameList; - } - - export interface IndicesRefreshParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - force?: boolean; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesRolloverParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: number | string; - alias?: string; - newIndex?: string; - } - - export interface IndicesRolloverResponse { - acknowledged: boolean; - shards_acknowledged: boolean; - old_index: string; - new_index: string; - rolled_over: boolean; - dry_run: boolean; - conditions: { [condition: string]: boolean }; - } - - export interface IndicesSegmentsParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - human?: boolean; - operationThreading?: any; // even the docs don't know what this does - verbose?: boolean; - index: NameList; - } - - export interface IndicesShardStoresParams extends GenericParams { - status?: NameList; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - index: NameList; - } - - export interface IndicesShrinkParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - waitForActiveShards?: string | number; - index: string; - target: string; - } - - export interface IndicesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: NameList; - human?: boolean; - level?: "cluster" | "indices" | "shards"; - types?: NameList; - index: NameList; - metric?: NameList; - } - - export interface IndicesUpdateAliasesParams extends GenericParams { - timeout?: TimeSpan; - masterTimeout?: TimeSpan; - body: { - actions: IndicesUpdateAliasesParamsAction[]; - }; - } - - export interface IndicesUpdateAliasesParamsAction { - add?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove?: { - index?: string; - indices?: string[]; - alias: string; - }; - remove_index?: { - index: string; - }; - } - - export interface IndicesUpgradeParams extends GenericParams { - expandWildcards?: ExpandWildcards; - ignoreUnavailable?: boolean; - waitForCompletion?: boolean; - onlyAncientSegments?: boolean; - index: NameList; - } - - export interface IndicesValidateQueryParams extends GenericParams { - explain?: boolean; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: ExpandWildcards; - operationThreading?: any; // even the docs don't know what this does - q?: string; - analyzer?: string; - analyzeWildcard?: boolean; - defaultOperator?: DefaultOperator; - df?: string; - lenient?: boolean; - lowercaseExpandedTerms?: boolean; - rewrite?: boolean; - index: NameList; - type?: NameList; - } - - export class Ingest { - deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; - deletePipeline(params: IngestDeletePipelineParams): Promise; - getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; - getPipeline(params: IngestGetPipelineParams): Promise; - putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; - putPipeline(params: IngestPutPipelineParams): Promise; - simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; - simulate(params: IngestSimulateParams): Promise; - } - - export interface IngestDeletePipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - } - - export interface IngestGetPipelineParams extends GenericParams { - masterTimeout?: number; - id: string; - } - - export interface IngestPutPipelineParams extends GenericParams { - masterTimeout?: number; - timeout?: number; - id: string; - body: any; - } - - export interface IngestSimulateParams extends GenericParams { - verbose?: boolean; - id: string; - } - - export class Nodes { - hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; - hotThreads(params: NodesHotThreadsParams): Promise; - info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; - info(params: NodesInfoParams): Promise; - stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; - stats(params: NodesStatsParams): Promise; - } - - export interface NodesHotThreadsParams extends GenericParams { - interval?: TimeSpan; - snapshots?: number; - threads?: number; - ignoreIdleThreads?: boolean; - type?: "cpu" | "wait" | "blocked"; - timeout?: TimeSpan; - nodeId: NameList; - } - - export interface NodesInfoParams extends GenericParams { - flatSettings?: boolean; - human?: boolean; - timeout?: TimeSpan; - nodeId: NameList; - metric?: NameList; - } - - export interface NodesStatsParams extends GenericParams { - completionFields?: NameList; - fielddataFields?: NameList; - fields?: NameList; - groups?: boolean; - human?: boolean; - level?: "indices" | "node" | "shards"; - types?: NameList; - timeout?: TimeSpan; - metric?: NameList; - indexMetric?: NameList; - nodeId?: NameList; - } - - export class Snapshot { - create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: SnapshotCreateParams): Promise; - createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - createRepository(params: SnapshotCreateRepositoryParams): Promise; - delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: SnapshotDeleteParams): Promise; - deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; - get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: SnapshotGetParams): Promise; - getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - getRepository(params: SnapshotGetRepositoryParams): Promise; - restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; - restore(params: SnapshotRestoreParams): Promise; - status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; - status(params: SnapshotStatusParams): Promise; - verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; - verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; - } - - export interface SnapshotCreateParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotCreateRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - verify?: boolean; - repository: string; - } - - export interface SnapshotDeleteParams extends GenericParams { - masterTimeout?: TimeSpan; - repository: string; - snapshot: string; - } - - export interface SnapshotDeleteRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export interface SnapshotGetParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotGetRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - local?: boolean; - repository: NameList; - } - - export interface SnapshotRestoreParams extends GenericParams { - masterTimeout?: TimeSpan; - waitForCompletion?: boolean; - repository: string; - snapshot: string; - } - - export interface SnapshotStatusParams extends GenericParams { - masterTimeout?: TimeSpan; - ignoreUnavailable?: boolean; - repository: string; - snapshot: NameList; - } - - export interface SnapshotVerifyRepositoryParams extends GenericParams { - masterTimeout?: TimeSpan; - timeout?: TimeSpan; - repository: string; - } - - export class Tasks { - cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; - cancel(params: TasksCancelParams): Promise; - get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: TasksGetParams): Promise; - list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; - list(params: TasksListParams): Promise; - } - - export interface TasksCancelParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - parentNode?: string; - parentTask?: string; - taskId?: string; - } - - export interface TasksGetParams extends GenericParams { - waitForCompletion?: boolean; - taskId?: string; - } - - export interface TasksListParams extends GenericParams { - nodeId?: NameList; - actions?: NameList; - detailed?: boolean; - parentNode?: string; - parentTask?: string; - waitForCompletion?: boolean; - groupBy?: "nodes" | "parents"; - } + }; } -declare module "elasticsearch" { - export = Elasticsearch; +export interface IndicesUpgradeParams extends GenericParams { + expandWildcards?: ExpandWildcards; + ignoreUnavailable?: boolean; + waitForCompletion?: boolean; + onlyAncientSegments?: boolean; + index: NameList; +} + +export interface IndicesValidateQueryParams extends GenericParams { + explain?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + rewrite?: boolean; + index: NameList; + type?: NameList; +} + +export class Ingest { + deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; + deletePipeline(params: IngestDeletePipelineParams): Promise; + getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; + getPipeline(params: IngestGetPipelineParams): Promise; + putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; + putPipeline(params: IngestPutPipelineParams): Promise; + simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; + simulate(params: IngestSimulateParams): Promise; +} + +export interface IngestDeletePipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; +} + +export interface IngestGetPipelineParams extends GenericParams { + masterTimeout?: number; + id: string; +} + +export interface IngestPutPipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; + body: any; +} + +export interface IngestSimulateParams extends GenericParams { + verbose?: boolean; + id: string; +} + +export class Nodes { + hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; + hotThreads(params: NodesHotThreadsParams): Promise; + info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; + info(params: NodesInfoParams): Promise; + stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; + stats(params: NodesStatsParams): Promise; +} + +export interface NodesHotThreadsParams extends GenericParams { + interval?: TimeSpan; + snapshots?: number; + threads?: number; + ignoreIdleThreads?: boolean; + type?: "cpu" | "wait" | "blocked"; + timeout?: TimeSpan; + nodeId: NameList; +} + +export interface NodesInfoParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: TimeSpan; + nodeId: NameList; + metric?: NameList; +} + +export interface NodesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: boolean; + human?: boolean; + level?: "indices" | "node" | "shards"; + types?: NameList; + timeout?: TimeSpan; + metric?: NameList; + indexMetric?: NameList; + nodeId?: NameList; +} + +export class Snapshot { + create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: SnapshotCreateParams): Promise; + createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + createRepository(params: SnapshotCreateRepositoryParams): Promise; + delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: SnapshotDeleteParams): Promise; + deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + deleteRepository(params: SnapshotDeleteRepositoryParams): Promise; + get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: SnapshotGetParams): Promise; + getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + getRepository(params: SnapshotGetRepositoryParams): Promise; + restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; + restore(params: SnapshotRestoreParams): Promise; + status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; + status(params: SnapshotStatusParams): Promise; + verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + verifyRepository(params: SnapshotVerifyRepositoryParams): Promise; +} + +export interface SnapshotCreateParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotCreateRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + verify?: boolean; + repository: string; +} + +export interface SnapshotDeleteParams extends GenericParams { + masterTimeout?: TimeSpan; + repository: string; + snapshot: string; +} + +export interface SnapshotDeleteRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export interface SnapshotGetParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotGetRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + local?: boolean; + repository: NameList; +} + +export interface SnapshotRestoreParams extends GenericParams { + masterTimeout?: TimeSpan; + waitForCompletion?: boolean; + repository: string; + snapshot: string; +} + +export interface SnapshotStatusParams extends GenericParams { + masterTimeout?: TimeSpan; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; +} + +export interface SnapshotVerifyRepositoryParams extends GenericParams { + masterTimeout?: TimeSpan; + timeout?: TimeSpan; + repository: string; +} + +export class Tasks { + cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; + cancel(params: TasksCancelParams): Promise; + get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: TasksGetParams): Promise; + list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; + list(params: TasksListParams): Promise; +} + +export interface TasksCancelParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + parentNode?: string; + parentTask?: string; + taskId?: string; +} + +export interface TasksGetParams extends GenericParams { + waitForCompletion?: boolean; + taskId?: string; +} + +export interface TasksListParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: string; + waitForCompletion?: boolean; + groupBy?: "nodes" | "parents"; +} + +export namespace errors { + class _Abstract extends Error {} + class Generic extends _Abstract {} + class ConnectionFault extends _Abstract {} + class NoConnections extends _Abstract {} + class Serialization extends _Abstract {} + class RequestTypeError extends _Abstract {} + + class AuthenticationException extends _Abstract {} + class AuthorizationException extends _Abstract {} + class BadGateway extends _Abstract {} + class BadRequest extends _Abstract {} + class BlockedByWindowsParentalControls extends _Abstract {} + class ClientClosedRequest extends _Abstract {} + class Conflict extends _Abstract {} + class ExpectationFailed extends _Abstract {} + class GatewayTimeout extends _Abstract {} + class HTTPToHTTPS extends _Abstract {} + class HTTPVersionNotSupported extends _Abstract {} + class ImATeapot extends _Abstract {} + class InternalServerError extends _Abstract {} + class LengthRequired extends _Abstract {} + class MethodNotAllowed extends _Abstract {} + class MovedPermanently extends _Abstract {} + class MultipleChoices extends _Abstract {} + class NotAcceptable extends _Abstract {} + class NotExtended extends _Abstract {} + class NotFound extends _Abstract {} + class NotImplemented extends _Abstract {} + class NotModified extends _Abstract {} + class PaymentRequired extends _Abstract {} + class PermanentRedirect extends _Abstract {} + class PreconditionFailed extends _Abstract {} + class ProxyAuthenticationRequired extends _Abstract {} + class RequestedRangeNotSatisfiable extends _Abstract {} + class RequestEntityTooLarge extends _Abstract {} + class RequestHeaderTooLarge extends _Abstract {} + class RequestTimeout extends _Abstract {} + class RequestURITooLong extends _Abstract {} + class SeeOther extends _Abstract {} + class ServiceUnavailable extends _Abstract {} + class TemporaryRedirect extends _Abstract {} + class TooManyConnectionsFromThisIP extends _Abstract {} + class TooManyRequests extends _Abstract {} + class UnsupportedMediaType extends _Abstract {} + class UpgradeRequired extends _Abstract {} + class UseProxy extends _Abstract {} + class VariantAlsoNegotiates extends _Abstract {} } diff --git a/types/elasticsearch/tsconfig.json b/types/elasticsearch/tsconfig.json index 2d62eac43d..21ac20d7e9 100644 --- a/types/elasticsearch/tsconfig.json +++ b/types/elasticsearch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "elasticsearch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/elasticsearch/tslint.json b/types/elasticsearch/tslint.json index a41bf5d19a..e9003e412b 100644 --- a/types/elasticsearch/tslint.json +++ b/types/elasticsearch/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "no-empty-interface": false } } diff --git a/types/electron-json-storage/electron-json-storage-tests.ts b/types/electron-json-storage/electron-json-storage-tests.ts index 07d8461bed..2429f6a95f 100644 --- a/types/electron-json-storage/electron-json-storage-tests.ts +++ b/types/electron-json-storage/electron-json-storage-tests.ts @@ -2,8 +2,9 @@ import electron = require('electron'); import storage = require('electron-json-storage'); const DATA_PATH = '~/Downloads'; +const NEW_DATA_PATH = `${DATA_PATH}/new-data-path`; -console.log(storage.DEFAULT_DATA_PATH.length); +console.log(storage.getDefaultDataPath().length); storage.setDataPath(DATA_PATH); console.log(DATA_PATH.length); @@ -12,31 +13,59 @@ console.log(storage.getDataPath().length); storage.set('foo', { foo: 'bar' }, (err: any) => { }); storage.set('bar', { foo: 'bar' }, (err: any) => { }); +storage.set('baz', { foo: 'bar' }, {dataPath: NEW_DATA_PATH}, (err: any) => { }); storage.get('foo', (err: any, data: object) => { console.log(JSON.stringify(data)); }); +storage.get('baz', {dataPath: NEW_DATA_PATH}, (err: any, data: object) => { + console.log(JSON.stringify(data)); +}); + storage.getMany(['foo', 'bar'], (err: any, data: object) => { console.log(JSON.stringify(data)); }); +storage.getMany(['baz'], {dataPath: NEW_DATA_PATH}, (err: any, data: object) => { + console.log(JSON.stringify(data)); +}); storage.getAll((err: any, data: object) => { console.log(JSON.stringify(data)); }); +storage.getAll({dataPath: NEW_DATA_PATH}, (err: any, data: object) => { + console.log(JSON.stringify(data)); +}); + storage.has('foo', (err: any, hasKey: boolean) => { console.log("hasKey?: %s", hasKey); }); +storage.has('baz', {dataPath: NEW_DATA_PATH}, (err: any, hasKey: boolean) => { + console.log("hasKey?: %s", hasKey); +}); + storage.keys((err: any, keys: string[]) => { console.log(keys); }); +storage.keys({dataPath: NEW_DATA_PATH}, (err: any, keys: string[]) => { + console.log(keys); +}); + storage.remove("foo", (err: any) => { console.log(err); }); +storage.remove("baz", {dataPath: NEW_DATA_PATH}, (err: any) => { + console.log(err); +}); + storage.clear((err: any) => { console.log(err); }); + +storage.clear({dataPath: NEW_DATA_PATH}, (err: any) => { + console.log(err); +}); diff --git a/types/electron-json-storage/index.d.ts b/types/electron-json-storage/index.d.ts index cafa6c4171..75d6cf3983 100644 --- a/types/electron-json-storage/index.d.ts +++ b/types/electron-json-storage/index.d.ts @@ -1,18 +1,28 @@ -// Type definitions for electron-json-storage 3.1 +// Type definitions for electron-json-storage 4.0 // Project: https://github.com/electron-userland/electron-json-storage // Definitions by: Sam Saint-Pettersen , -// nrlquaker +// nrlquaker , +// John Woodruff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export const DEFAULT_DATA_PATH: string; -export function setDataPath(directory: string): void; +export interface DataOptions { dataPath: string; } +export function getDefaultDataPath(): string; +export function setDataPath(directory?: string): void; export function getDataPath(): string; export function get(key: string, callback: (error: any, data: object) => void): void; +export function get(key: string, options: DataOptions, callback: (error: any, data: object) => void): void; export function getMany(keys: ReadonlyArray, callback: (error: any, data: object) => void): void; +export function getMany(keys: ReadonlyArray, options: DataOptions, callback: (error: any, data: object) => void): void; export function getAll(callback: (error: any, data: object) => void): void; +export function getAll(options: DataOptions, callback: (error: any, data: object) => void): void; export function set(key: string, json: object, callback: (error: any) => void): void; +export function set(key: string, json: object, options: DataOptions, callback: (error: any) => void): void; export function has(key: string, callback: (error: any, hasKey: boolean) => void): void; +export function has(key: string, options: DataOptions, callback: (error: any, hasKey: boolean) => void): void; export function keys(callback: (error: any, keys: string[]) => void): void; +export function keys(options: DataOptions, callback: (error: any, keys: string[]) => void): void; export function remove(key: string, callback: (error: any) => void): void; +export function remove(key: string, options: DataOptions, callback: (error: any) => void): void; export function clear(callback: (error: any) => void): void; +export function clear(options: DataOptions, callback: (error: any) => void): void; diff --git a/types/electron-settings/electron-settings-tests.ts b/types/electron-settings/electron-settings-tests.ts index a1fad17f10..0ff969eb42 100644 --- a/types/electron-settings/electron-settings-tests.ts +++ b/types/electron-settings/electron-settings-tests.ts @@ -12,6 +12,7 @@ settings.setAll({foo: {bar: 'test'}}, {prettify: true}); // $ExpectType Settings settings.get('foo.bar'); // $ExpectType JsonValue settings.get('foo.bar', 'test'); // $ExpectType JsonValue +settings.get('foo.bar', 'test', {prettify: true}); // $ExpectType JsonValue settings.getAll(); // $ExpectType JsonValue @@ -24,3 +25,6 @@ settings.deleteAll({prettify: true}); // $ExpectType Settings settings.watch('foo.bar', () => {}); // $ExpectType SettingsObserver settings.file(); // $ExpectType string + +settings.setPath('~/Documents'); // $ExpectType Settings +settings.clearPath(); // $ExpectType Settings diff --git a/types/electron-settings/index.d.ts b/types/electron-settings/index.d.ts index 21bc1fb446..8ee10bf1f7 100644 --- a/types/electron-settings/index.d.ts +++ b/types/electron-settings/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for electron-settings 3.0 +// Type definitions for electron-settings 3.1 // Project: https://github.com/nathanbuchar/electron-settings#readme -// Definitions by: Ian Copp +// Definitions by: Ian Copp , +// nrlquaker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -56,7 +57,7 @@ interface Settings extends NodeJS.EventEmitter { * exist. * @see #getAll */ - get(keyPath: string, defaultValue?: any): JsonValue; + get(keyPath: string, defaultValue?: any, options?: SettingsOptions): JsonValue; /** * Returns all settings. @@ -109,6 +110,25 @@ interface Settings extends NodeJS.EventEmitter { * cause unintended consequences. */ file(): string; + + /** + * Sets a custom settings file path. By default, the settings file is + * stored in your app's user data directory in a file called Settings, + * but this method allows you to change this. + * + * Note: This method should be used cautiously, as it may have unintended + * consequences. In general, this method should only be used for + * debug purposes, and not in production apps. + * @param filePath An absolute path to the settings file where the + * user data will be saved. + */ + setPath(filePath: string): Settings; + + /** + * Clears the custom settings file path, if it exists. + * @see #setPath + */ + clearPath(): Settings; } interface SettingsObserver { diff --git a/types/email-templates/email-templates-tests.ts b/types/email-templates/email-templates-tests.ts index 3c4493402c..a3311d6e81 100644 --- a/types/email-templates/email-templates-tests.ts +++ b/types/email-templates/email-templates-tests.ts @@ -1,29 +1,14 @@ import EmailTemplates = require('email-templates'); -const EmailTemplate = EmailTemplates.EmailTemplate; -const template = new EmailTemplate("./"); -const templateWithOptions = new EmailTemplate('./', {disableJuice: true, sassOptions: {}, juiceOptions: {}}); -const users = [ - { - email: 'pappa.pizza@spaghetti.com', - name: { - first: 'Pappa', - last: 'Pizza' - } +const email = new EmailTemplates({ + message: { + from: 'Test@tesitng.com' }, - { - email: 'mister.geppetto@spaghetti.com', - name: { - first: 'Mister', - last: 'Geppetto' - } - } -]; + transport: { + jsonTransport: true + }} +); -const templates = users.map((user) => { - return template.render(user) - .then((results) => { - const {html, subject, text} = results; - return html; - }); -}); +email.juiceResources('

bob

'); +email.render('mars/html.pug', {name: 'elon'}); +email.send({template: 'mars', message: {to: 'elon@spacex.com'}, locals: {name: 'Elon'}}); diff --git a/types/email-templates/index.d.ts b/types/email-templates/index.d.ts index 754a06877d..12dceb181d 100644 --- a/types/email-templates/index.d.ts +++ b/types/email-templates/index.d.ts @@ -1,113 +1,104 @@ -// Type definitions for node-email-templates 2.6 +// Type definitions for node-email-templates 3.1 // Project: https://github.com/niftylettuce/node-email-templates // Definitions by: Cyril Schumacher // Matus Gura +// Jacob Copeland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export interface EmailTemplateResults { - html: string; - text: string; - subject: string; +interface EmailConfig { + /** + * The message + */ + message: any; + /** + * The nodemailer Transport created via nodemailer.createTransport + */ + transport: any; + /** + * The email template directory and engine information + */ + views?: any; + /** + * Do you really want to send, false for test or development + */ + send?: boolean; + /** + * Preview the email + */ + preview?: boolean; + /** + * Set to object to configure and Enable + */ + i18n?: any; + /** + * Pass a custom render function if necessary + */ + render?: { view: string, locals: any }; + /** + * + */ + htmlToText?: any; + /** + * + */ + juice?: boolean; + /** + * + */ + juiceResources?: any; } -export type EmailTemplateCallback = (err: any, results: EmailTemplateResults) => void; - -export interface EmailTemplateOptions { - disableJuice?: boolean; - juiceOptions?: any; - sassOptions?: any; +interface EmailOptions { + /** + * The template name + */ + template: string; + /** + * Nodemailer Message + */ + message: any; + /** + * The Template Variables + */ + locals: any; } -export class EmailTemplate { +declare class EmailTemplate { + constructor(config: EmailConfig); /** - * @param templateDir The template directory. + * shorthand use of `juiceResources` with the config + * mainly for custom renders like from a database). */ - constructor(templateDir: string, options?: EmailTemplateOptions); - + juiceResources(html: string): Promise ; /** - * Render a single template. - * @param locals The template variables. - * @param locale The language code. + * + * @param view The Html pug to render + * @param locals The template Variables */ - render(locals: any, locale?: string): Promise; - + render(view: string, locals: any): Promise; /** - * Render a single template. + * Send the Email */ - render(callback: EmailTemplateCallback): void; - - /** - * Render a single template. - * @param locals The template variables. - */ - render(locals: any, callback: EmailTemplateCallback): void; - - /** - * Render a single template. - * @param locals The template variables. - * @param locale The language code. - */ - render(locals: any, locale: string, callback: EmailTemplateCallback): void; - - /** - * Render text - * @param locals The template variables. - * @param locale The language code. - */ - renderText(locals: any, locale?: string): Promise; - - /** - * Render text - * @param locals The template variables. - * @param callback The language code. - */ - renderText(locals: any, callback: EmailTemplateCallback): void; - - /** - * Render text - * @param locals The template variables. - * @param locale The language code. - * @param callback The language code. - */ - renderText(locals: any, locale: string, callback: EmailTemplateCallback): void; - - /** - * Render subject - * @param locals The template variables. - * @param locale The language code. - */ - renderSubject(locals: any, locale?: string): Promise; - - /** - * Render subject - * @param locals The template variables. - */ - renderSubject(locals: any, callback: EmailTemplateCallback): void; - - /** - * Render subject - * @param locals The template variables. - * @param locale The language code. - */ - renderSubject(locals: any, locale: string, callback: EmailTemplateCallback): void; - - /** - * Render HTML - * @param locals The template variables. - * @param locale The language code. - */ - renderHtml(locals: any, locale?: string): Promise; - - /** - * Render HTML - * @param locals The template variables. - */ - renderHtml(locals: any, callback: EmailTemplateCallback): void; - - /** - * Render HTML - * @param locals The template variables. - * @param locale The language code. - */ - renderHtml(locals: any, locale: string, callback: EmailTemplateCallback): void; + send(options: EmailOptions): any; } + +declare namespace EmailTemplate { + /** + * shorthand use of `juiceResources` with the config + * mainly for custom renders like from a database). + */ + function juiceResources(html: string): Promise ; + + /** + * + * @param view The Html pug to render + * @param locals The template Variables + */ + function render(view: string, locals: any): Promise; + + /** + * Send the Email + */ + function send(options: EmailOptions): any; +} +export = EmailTemplate; diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts new file mode 100644 index 0000000000..0e0678e7d7 --- /dev/null +++ b/types/ember-data/index.d.ts @@ -0,0 +1,1693 @@ +// Type definitions for ember-data 2.14 +// Project: https://github.com/emberjs/data +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +declare namespace DS { + /** + * Convert an hash of errors into an array with errors in JSON-API format. + */ + function errorsHashToArray(errors: {}): any[]; + /** + * Convert an array of errors in JSON-API format into an object. + */ + function errorsArrayToHash(errors: any[]): {}; + /** + * `DS.belongsTo` is used to define One-To-One and One-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function belongsTo(modelName: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty; + function belongsTo(modelName: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * `DS.hasMany` is used to define One-To-Many and Many-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function hasMany(type: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + function hasMany(type: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * This method normalizes a modelName into the format Ember Data uses + * internally. + */ + function normalizeModelName(modelName: string): string; + const VERSION: string; + + interface AttrOptions { + defaultValue?: T | (() => T); + } + + /** + * `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). + * By default, attributes are passed through as-is, however you can specify an + * optional type to have the value automatically transformed. + * Ember Data ships with four basic transform types: `string`, `number`, + * `boolean` and `date`. You can define your own transforms by subclassing + * [DS.Transform](/api/data/classes/DS.Transform.html). + */ + function attr(type: 'string', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'boolean', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'number', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'date', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: string, options?: AttrOptions): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; + /** + * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 + * ## Using BuildURLMixin + * To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. + * The default behaviour is designed for RESTAdapter. + * ### Example + * ```javascript + * export default DS.Adapter.extend(BuildURLMixin, { + * findRecord: function(store, type, id, snapshot) { + * var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); + * return this.ajax(url, 'GET'); + * } + * }); + * ``` + * ### Attributes + * The `host` and `namespace` attributes will be used if defined, and are optional. + */ + class BuildURLMixin { + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * A `DS.AdapterError` is used by an adapter to signal that an error occurred + * during a request to an external API. It indicates a generic error, and + * subclasses are used to indicate specific error states. The following + * subclasses are provided: + */ + class AdapterError { + } + /** + * A `DS.InvalidError` is used by an adapter to signal the external API + * was unable to process a request because the content was not + * semantically correct or meaningful per the API. Usually this means a + * record failed some form of server side validation. When a promise + * from an adapter is rejected with a `DS.InvalidError` the record will + * transition to the `invalid` state and the errors will be set to the + * `errors` property on the record. + */ + class InvalidError { + } + /** + * A `DS.TimeoutError` is used by an adapter to signal that a request + * to the external API has timed out. I.e. no response was received from + * the external API within an allowed time period. + */ + class TimeoutError { + } + /** + * A `DS.AbortError` is used by an adapter to signal that a request to + * the external API was aborted. For example, this can occur if the user + * navigates away from the current page after a request to the external API + * has been initiated but before a response has been received. + */ + class AbortError { + } + /** + * A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response + * status. It is used by an adapter to signal that a request to the external + * API was rejected because authorization is required and has failed or has not + * yet been provided. + */ + class UnauthorizedError { + } + /** + * A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. + * It is used by an adapter to signal that a request to the external API was + * valid but the server is refusing to respond to it. If authorization was + * provided and is valid, then the authenticated user does not have the + * necessary permissions for the request. + */ + class ForbiddenError { + } + /** + * A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. + * It is used by an adapter to signal that a request to the external API + * was rejected because the resource could not be found on the API. + */ + class NotFoundError { + } + /** + * A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. + * It is used by an adapter to indicate that the request could not be processed + * because of a conflict in the request. An example scenario would be when + * creating a record with a client generated id but that id is already known + * to the external API. + */ + class ConflictError { + } + /** + * A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response + * status. It is used by the adapter to indicate that a request has failed + * because of an error in the external API. + */ + class ServerError { + } + /** + * Holds validation errors for a given record, organized by attribute names. + */ + interface Errors extends Ember.Enumerable, Ember.Evented {} + class Errors extends Ember.Object { + /** + * DEPRECATED: + * Register with target handler + */ + registerHandlers(target: {}, becameInvalid: Function, becameValid: Function): any; + /** + * Returns errors for a given attribute + */ + errorsFor(attribute: string): any[]; + /** + * An array containing all of the error messages for this + * record. This is useful for displaying all errors to the user. + */ + messages: Ember.ComputedProperty; + /** + * Total number of errors. + */ + length: Ember.ComputedProperty; + isEmpty: Ember.ComputedProperty; + /** + * DEPRECATED: + * Adds error messages to a given attribute and sends + * `becameInvalid` event to the record. + */ + add(attribute: string, messages: any[]|string): any; + /** + * DEPRECATED: + * Removes all error messages from the given attribute and sends + * `becameValid` event to the record if there no more errors left. + */ + remove(attribute: string): any; + /** + * DEPRECATED: + * Removes all error messages and sends `becameValid` event + * to the record. + */ + clear(): any; + /** + * Checks if there is error messages for the given attribute. + */ + has(attribute: string): boolean; + } + /** + * The model class that all Ember Data records descend from. + * This is the public API of Ember Data models. If you are using Ember Data + * in your application, this is the class you should use. + * If you are working on Ember Data internals, you most likely want to be dealing + * with `InternalModel` + */ + class Model extends Ember.Object { + /** + * If this property is `true` the record is in the `empty` + * state. Empty is the first state all records enter after they have + * been created. Most records created by the store will quickly + * transition to the `loading` state if data needs to be fetched from + * the server or the `created` state if the record is created on the + * client. A record can also enter the empty state if the adapter is + * unable to locate the record. + */ + isEmpty: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loading` state. A + * record enters this state when the store asks the adapter for its + * data. It remains in this state until the adapter provides the + * requested data. + */ + isLoading: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loaded` state. A + * record enters this state when its data is populated. Most of a + * record's lifecycle is spent inside substates of the `loaded` + * state. + */ + isLoaded: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `dirty` state. The + * record has local changes that have not yet been saved by the + * adapter. This includes records that have been created (but not yet + * saved) or deleted. + */ + hasDirtyAttributes: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `saving` state. A + * record enters the saving state when `save` is called, but the + * adapter has not yet acknowledged that the changes have been + * persisted to the backend. + */ + isSaving: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `deleted` state + * and has been marked for deletion. When `isDeleted` is true and + * `hasDirtyAttributes` is true, the record is deleted locally but the deletion + * was not yet persisted. When `isSaving` is true, the change is + * in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the + * change has persisted. + */ + isDeleted: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `new` state. A + * record will be in the `new` state when it has been created on the + * client and the adapter has not yet report that it was successfully + * saved. + */ + isNew: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `valid` state. + */ + isValid: Ember.ComputedProperty; + /** + * If the record is in the dirty state this property will report what + * kind of change has caused it to move into the dirty + * state. Possible values are: + */ + dirtyType: Ember.ComputedProperty; + /** + * If `true` the adapter reported that it was unable to save local + * changes to the backend for any reason other than a server-side + * validation error. + */ + isError: boolean; + /** + * If `true` the store is attempting to reload the record from the adapter. + */ + isReloading: boolean; + /** + * All ember models have an id property. This is an identifier + * managed by an external source. These are always coerced to be + * strings before being used internally. Note when declaring the + * attributes for a model it is an error to declare an id + * attribute. + */ + id: string; + /** + * When the record is in the `invalid` state this object will contain + * any errors returned by the adapter. When present the errors hash + * contains keys corresponding to the invalid property names + * and values which are arrays of Javascript objects with two keys: + */ + errors: Ember.ComputedProperty; + /** + * This property holds the `DS.AdapterError` object with which + * last adapter operation was rejected. + */ + adapterError: AdapterError; + /** + * Create a JSON representation of the record, using the serialization + * strategy of the store's adapter. + */ + serialize(options: {}): {}; + /** + * Use [DS.JSONSerializer](DS.JSONSerializer.html) to + * get the JSON representation of a record. + */ + toJSON(options: {}): {}; + /** + * Fired when the record is ready to be interacted with, + * that is either loaded from the server or created locally. + */ + ready(): void; + /** + * Fired when the record is loaded from the server. + */ + didLoad(): void; + /** + * Fired when the record is updated. + */ + didUpdate(): void; + /** + * Fired when a new record is commited to the server. + */ + didCreate(): void; + /** + * Fired when the record is deleted. + */ + didDelete(): void; + /** + * Fired when the record becomes invalid. + */ + becameInvalid(): void; + /** + * Fired when the record enters the error state. + */ + becameError(): void; + /** + * Fired when the record is rolled back. + */ + rolledBack(): void; + /** + * Marks the record as deleted but does not save it. You must call + * `save` afterwards if you want to persist it. You might use this + * method if you want to allow the user to still `rollbackAttributes()` + * after a delete was made. + */ + deleteRecord(): any; + /** + * Same as `deleteRecord`, but saves the record immediately. + */ + destroyRecord(options: {}): Promise; + /** + * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(): any; + /** + * Returns an object, whose keys are changed properties, and value is + * an [oldProp, newProp] array. + */ + changedAttributes(): {}; + /** + * If the model `hasDirtyAttributes` this function will discard any unsaved + * changes. If the model `isNew` it will be removed from the store. + */ + rollbackAttributes(): any; + /** + * Save the record and persist any changes to the record to an + * external source via the adapter. + */ + save(options?: {}): Promise; + /** + * Reload the record from the adapter. + */ + reload(): Promise; + /** + * Get the reference for the specified belongsTo relationship. + */ + belongsTo(name: string): BelongsToReference; + /** + * Get the reference for the specified hasMany relationship. + */ + hasMany(name: string): HasManyReference; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + eachRelationship(callback: Function, binding: any): any; + /** + * Represents the model's class name as a string. This can be used to look up the model's class name through + * `DS.Store`'s modelFor method. + */ + static modelName: string; + /** + * For a given relationship name, returns the model type of the relationship. + */ + static typeForRelationship(name: string, store: Store): Model; + /** + * Find the relationship which is the inverse of the one asked for. + */ + static inverseFor(name: string, store: Store): {}; + /** + * The model's relationships as a map, keyed on the type of the + * relationship. The value of each entry is an array containing a descriptor + * for each relationship with that type, describing the name of the relationship + * as well as the type. + */ + static relationships: Ember.ComputedProperty; + /** + * A hash containing lists of the model's relationships, grouped + * by the relationship kind. For example, given a model with this + * definition: + */ + static relationshipNames: Ember.ComputedProperty<{}>; + /** + * An array of types directly related to a model. Each type will be + * included once, regardless of the number of relationships it has with + * the model. + */ + static relatedTypes: Ember.ComputedProperty>; + /** + * A map whose keys are the relationships of a model and whose values are + * relationship descriptors. + */ + static relationshipsByName: Ember.ComputedProperty; + /** + * A map whose keys are the fields of the model and whose values are strings + * describing the kind of the field. A model's fields are the union of all of its + * attributes and relationships. + */ + static fields: Ember.ComputedProperty; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + static eachRelationship(callback: Function, binding: any): any; + /** + * Given a callback, iterates over each of the types related to a model, + * invoking the callback with the related type's class. Each type will be + * returned just once, regardless of how many different relationships it has + * with a model. + */ + static eachRelatedType(callback: Function, binding: any): any; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are the meta object for the + * property. + */ + static attributes: Ember.ComputedProperty; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are type of transformation + * applied to each attribute. This map does not include any + * attributes that do not have an transformation type. + */ + static transformedAttributes: Ember.ComputedProperty; + /** + * Iterates through the attributes of the model, calling the passed function on each + * attribute. + */ + static eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through the transformedAttributes of the model, calling + * the passed function on each attribute. Note the callback will not be + * called for any attributes that do not have an transformation type. + */ + static eachTransformedAttribute(callback: Function, binding: {}): any; + /** + * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. + */ + rollbackAttribute(): any; + /** + * This Ember.js hook allows an object to be notified when a property + * is defined. + */ + didDefineProperty(proto: {}, key: string, value: Ember.ComputedProperty): any; + } + /** + * ### State + */ + class RootState { + } + /** + * Represents an ordered list of records whose order and membership is + * determined by the adapter. For example, a query sent to the adapter + * may trigger a search on the server, whose results would be loaded + * into an instance of the `AdapterPopulatedRecordArray`. + */ + class AdapterPopulatedRecordArray extends RecordArray { + } + /** + * Represents a list of records whose membership is determined by the + * store. As records are created, loaded, or modified, the store + * evaluates them to determine if they should be part of the record + * array. + */ + class FilteredRecordArray extends RecordArray { + /** + * The filterFunction is a function used to test records from the store to + * determine if they should be part of the record array. + */ + filterFunction(record: Model): boolean; + } + /** + * A record array is an array that contains records of a certain modelName. The record + * array materializes records as needed when they are retrieved for the first + * time. You should not create record arrays yourself. Instead, an instance of + * `DS.RecordArray` or its subclasses will be returned by your application's store + * in response to queries. + */ + interface RecordArray extends Ember.ArrayProxy, Ember.Evented {} + class RecordArray { + /** + * The flag to signal a `RecordArray` is finished loading data. + */ + isLoaded: boolean; + /** + * The flag to signal a `RecordArray` is currently loading data. + */ + isUpdating: boolean; + /** + * The modelClass represented by this record array. + */ + type: Ember.ComputedProperty; + /** + * Used to get the latest version of all of the records in this array + * from the adapter. + */ + update(): any; + /** + * Saves all of the records in the `RecordArray`. + */ + save(): PromiseArray; + } + /** + * A BelongsToReference is a low level API that allows users and + * addon author to perform meta-operations on a belongs-to + * relationship. + */ + class BelongsToReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The `id` of the record that this reference refers to. Together, the + * `type()` and `id()` methods form a composite key for the identity + * map. This can be used to access the id of an async relationship + * without triggering a fetch that would normally happen if you + * attempted to use `record.get('relationship.id')`. + */ + id(): string; + /** + * The link Ember Data will use to fetch or reload this belongs-to + * relationship. + */ + link(): string; + /** + * The meta data for the belongs-to relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the conanical value of this + * relationship on the backend. + */ + push(objectOrPromise: {}|Promise): Promise; + /** + * `value()` synchronously returns the current value of the belongs-to + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(objectOrPromise: {}|Promise): Model; + /** + * Loads a record in a belongs to relationship if it is not already + * loaded. If the relationship is already loaded this method does not + * trigger a new load. + */ + load(): Promise; + /** + * Triggers a reload of the value in this relationship. If the + * remoteType is `"link"` Ember Data will use the relationship link to + * reload the relationship. Otherwise it will reload the record by its + * id. + */ + reload(): Promise; + } + /** + * A HasManyReference is a low level API that allows users and addon + * author to perform meta-operations on a has-many relationship. + */ + class HasManyReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The link Ember Data will use to fetch or reload this has-many + * relationship. + */ + link(): string; + /** + * `ids()` returns an array of the record ids in this relationship. + */ + ids(): any[]; + /** + * The meta data for the has-many relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the canonical value of this + * relationship on the backend. + */ + push(objectOrPromise: T[] | Promise): ManyArray; + /** + * `value()` synchronously returns the current value of the has-many + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(): ManyArray; + /** + * Loads the relationship if it is not already loaded. If the + * relationship is already loaded this method does not trigger a new + * load. + */ + load(): Promise; + /** + * Reloads this has-many relationship. + */ + reload(): Promise; + } + /** + * An RecordReference is a low level API that allows users and + * addon author to perform meta-operations on a record. + */ + class RecordReference { + /** + * The `id` of the record that this reference refers to. + */ + id(): string; + /** + * How the reference will be looked up when it is loaded: Currently + * this always return `identity` to signifying that a record will be + * loaded by the `type` and `id`. + */ + remoteType(): string; + /** + * This API allows you to provide a reference with new data. The + * simplest usage of this API is similar to `store.push`: you provide a + * normalized hash of data and the object represented by the reference + * will update. + */ + push(payload: Promise|{}): PromiseObject & T; + /** + * If the entity referred to by the reference is already loaded, it is + * present as `reference.value`. Otherwise the value returned by this function + * is `null`. + */ + value(): T | null; + /** + * Triggers a fetch for the backing entity based on its `remoteType` + * (see `remoteType` definitions per reference type). + */ + load(): PromiseObject & T; + /** + * Reloads the record if it is already loaded. If the record is not + * loaded it will load the record via `store.findRecord` + */ + reload(): PromiseObject & T; + } + /** + * A `ManyArray` is a `MutableArray` that represents the contents of a has-many + * relationship. + */ + interface ManyArray extends Ember.MutableArray {} + class ManyArray extends Ember.Object.extend(Ember.MutableArray as {}, Ember.Evented) { + /** + * The loading state of this array + */ + isLoaded: boolean; + /** + * Metadata associated with the request for async hasMany relationships. + */ + meta: {}; + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseArray; + /** + * Saves all of the records in the `ManyArray`. + */ + save(): PromiseArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + /** + * A `PromiseArray` is an object that acts like both an `Ember.Array` + * and a promise. When the promise is resolved the resulting value + * will be set to the `PromiseArray`'s `content` property. This makes + * it easy to create data bindings with the `PromiseArray` that will be + * updated when the promise resolves. + */ + interface PromiseArray extends Ember.ArrayProxy, Ember.PromiseProxyMixin> {} + class PromiseArray { + } + /** + * A `PromiseObject` is an object that acts like both an `Ember.Object` + * and a promise. When the promise is resolved, then the resulting value + * will be set to the `PromiseObject`'s `content` property. This makes + * it easy to create data bindings with the `PromiseObject` that will + * be updated when the promise resolves. + */ + interface PromiseObject extends Ember.ObjectProxy, Ember.PromiseProxyMixin> {} + class PromiseObject { + } + /** + * A PromiseManyArray is a PromiseArray that also proxies certain method calls + * to the underlying manyArray. + * Right now we proxy: + */ + class PromiseManyArray extends PromiseArray { + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseManyArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + class SnapshotRecordArray { + /** + * Number of records in the array + */ + length: number; + /** + * Meta objects for the record array. + */ + meta: {}; + /** + * A hash of adapter options passed into the store method for this request. + */ + adapterOptions: {}; + /** + * The relationships to include for this request. + */ + include: string|any[]; + /** + * The type of the underlying records for the snapshots in the array, as a DS.Model + */ + type: Model; + /** + * Get snapshots of the underlying record array + */ + snapshots(): any[]; + } + class Snapshot { + /** + * The underlying record for this snapshot. Can be used to access methods and + * properties defined on the record. + */ + record: Model; + /** + * The id of the snapshot's underlying record + */ + id: string; + /** + * A hash of adapter options + */ + adapterOptions: {}; + /** + * The name of the type of the underlying record for this snapshot, as a string. + */ + modelName: string; + /** + * The type of the underlying record for this snapshot, as a DS.Model. + */ + type: Model; + /** + * Returns the value of an attribute. + */ + attr(keyName: string): {}; + /** + * Returns all attributes and their corresponding values. + */ + attributes(): {}; + /** + * Returns all changed attributes and their old and new values. + */ + changedAttributes(): {}; + /** + * Returns the current value of a belongsTo relationship. + */ + belongsTo(keyName: string, options: {}): Snapshot|string|null|undefined; + /** + * Returns the current value of a hasMany relationship. + */ + hasMany(keyName: string, options: {}): any[]|undefined; + /** + * Iterates through all the attributes of the model, calling the passed + * function on each attribute. + */ + eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through all the relationships of the model, calling the passed + * function on each relationship. + */ + eachRelationship(callback: Function, binding: {}): any; + /** + * Serializes the snapshot using the serializer for the model. + */ + serialize(options: {}): {}; + } + /** + * The store contains all of the data for records loaded from the server. + * It is also responsible for creating instances of `DS.Model` that wrap + * the individual data for a record, so that they can be bound to in your + * Handlebars templates. + */ + class Store { + /** + * The default adapter to use to communicate to a backend server or + * other persistence layer. This will be overridden by an application + * adapter if present. + */ + adapter: string; + /** + * Create a new record in the current store. The properties passed + * to this method are set on the newly created record. + */ + createRecord(modelName: string, inputProperties?: {}): T; + /** + * For symmetry, a record can be deleted via the store. + */ + deleteRecord(record: Model): void; + /** + * For symmetry, a record can be unloaded via the store. + * This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(record: Model): void; + /** + * This method returns a record for a given type and id combination. + */ + findRecord(modelName: string, id: string|number, options?: {}): PromiseObject & T; + /** + * Get the reference for the specified record. + */ + getReference(modelName: string, id: string|number): RecordReference; + /** + * Get a record by a given type and ID without triggering a fetch. + */ + peekRecord(modelName: string, id: string|number): T|null; + /** + * This method returns true if a record for a given modelName and id is already + * loaded in the store. Use this function to know beforehand if a findRecord() + * will result in a request or that it will be a cache hit. + */ + hasRecordForId(modelName: string, id: string|number): boolean; + /** + * This method delegates a query to the adapter. This is the one place where + * adapter-level semantics are exposed to the application. + */ + query(modelName: string, query: any): AdapterPopulatedRecordArray & PromiseArray; + /** + * This method makes a request for one record, where the `id` is not known + * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) + * instead). + */ + queryRecord(modelName: string, query: any): Promise; + /** + * `findAll` asks the adapter's `findAll` method to find the records for the + * given type, and returns a promise which will resolve with all records of + * this type present in the store, even if the adapter only returns a subset + * of them. + */ + findAll(modelName: string, options?: { + reload?: boolean, + backgroundReload?: boolean, + include?: string, + adapterOptions?: any + }): PromiseArray; + /** + * This method returns a filtered array that contains all of the + * known records for a given type in the store. + */ + peekAll(modelName: string): RecordArray; + /** + * This method unloads all records in the store. + * It schedules unloading to happen during the next run loop. + */ + unloadAll(modelName: string): void; + /** + * DEPRECATED: + * This method has been deprecated and is an alias for store.hasRecordForId, which should + * be used instead. + */ + recordIsLoaded(modelName: string, id: string): boolean; + /** + * Returns the model class for the particular `modelName`. + */ + modelFor(modelName: string): Model; + /** + * Push some data for a given type into the store. + */ + push(data: {}): Model|any[]; + /** + * Push some raw data into the store. + */ + pushPayload(modelName: string, inputPayload: {}): any; + pushPayload(inputPayload: {}): any; + /** + * `normalize` converts a json payload into the normalized form that + * [push](#method_push) expects. + */ + normalize(modelName: string, payload: {}): {}; + /** + * Returns an instance of the adapter for a given type. For + * example, `adapterFor('person')` will return an instance of + * `App.PersonAdapter`. + */ + adapterFor(modelName: string): Adapter; + /** + * Returns an instance of the serializer for a given type. For + * example, `serializerFor('person')` will return an instance of + * `App.PersonSerializer`. + */ + serializerFor(modelName: string): Serializer; + } + /** + * The `JSONAPIAdapter` is the default adapter used by Ember Data. It + * is responsible for transforming the store's requests into HTTP + * requests that follow the [JSON API](http://jsonapi.org/format/) + * format. + */ + class JSONAPIAdapter extends RESTAdapter { + /** + * By default the JSONAPIAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + } + /** + * The REST adapter allows your store to communicate with an HTTP server by + * transmitting JSON via XHR. Most Ember.js apps that consume a JSON API + * should use the REST adapter. + */ + class RESTAdapter extends Adapter implements BuildURLMixin { + /** + * Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. + */ + ajax(url: string, type: string, options?: object): Promise; + /** + * Generate ajax options + */ + ajaxOptions(url: string, type: string, options?: object): object; + /** + * By default, the RESTAdapter will send the query params sorted alphabetically to the + * server. + */ + sortQueryParams(obj: {}): {}; + /** + * By default the RESTAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + /** + * Endpoint paths can be prefixed with a `namespace` by setting the namespace + * property on the adapter: + */ + namespace: string; + /** + * An adapter can target other hosts by setting the `host` property. + */ + host: string; + /** + * Some APIs require HTTP headers, e.g. to provide an API + * key. Arbitrary headers can be set as key/value pairs on the + * `RESTAdapter`'s `headers` object and Ember Data will send them + * along with each ajax request. For dynamic headers see [headers + * customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). + */ + headers: {}; + /** + * Called by the store in order to fetch the JSON for a given + * type and ID. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * Called by the store in order to fetch a JSON array for all + * of the records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the records that match a particular query. + */ + query(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch a JSON object for + * the record that matches a particular query. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch several records together if `coalesceFindRequests` is true + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the unloaded records in a has-many relationship that were originally + * specified as a URL (inside of `links`). + */ + findHasMany(store: Store, snapshot: Snapshot, url: string, relationship: {}): Promise; + /** + * Called by the store in order to fetch the JSON for the unloaded record in a + * belongs-to relationship that was originally specified as a URL (inside of + * `links`). + */ + findBelongsTo(store: Store, snapshot: Snapshot, url: string): Promise; + /** + * Called by the store when a newly created record is + * saved via the `save` method on a model record instance. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when an existing record is saved + * via the `save` method on a model record instance. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when a record is deleted. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * Takes an ajax response, and returns the json payload or an error. + */ + handleResponse(status: number, headers: {}, payload: {}, requestData: {}): {}; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is a success. + */ + isSuccess(status: number, headers: {}, payload: {}): boolean; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is an invalid error. + */ + isInvalid(status: number, headers: {}, payload: {}): boolean; + /** + * Get the data (body or query params) for a request. + */ + dataForRequest(params: {}): {}; + /** + * Get the HTTP method for a request. + */ + methodForRequest(params: {}): string; + /** + * Get the URL for a request. + */ + urlForRequest(params: {}): string; + /** + * Get the headers for a request. + */ + headersForRequest(params: {}): {}; + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * ## Using Embedded Records + */ + class EmbeddedRecordsMixin { + /** + * Normalize the record and recursively normalize/extract all the embedded records + * while pushing them into the store as they are encountered + */ + normalize(typeClass: Model, hash: {}, prop: string): {}; + /** + * Serialize `belongsTo` relationship when it is configured as an embedded object. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * Serializes `hasMany` relationships when it is configured as embedded objects. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * When serializing an embedded record, modify the property (in the json payload) + * that refers to the parent record (foreign key for relationship). + */ + removeEmbeddedForeignKey(snapshot: Snapshot, embeddedSnapshot: Snapshot, relationship: {}, json: {}): any; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONAPISerializer extends JSONSerializer { + pushPayload(store: Store, payload: {}): any; + /** + * Dasherizes and singularizes the model name in the payload to match + * the format Ember Data uses internally for the model name. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Converts the model name to a pluralized version of the model name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as the word separator in the JSON + * attribute keys. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as word separators in + * relationship properties. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelname: string): string; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONSerializer extends Serializer { + /** + * The `primaryKey` is used when serializing and deserializing + * data. Ember Data always uses the `id` property to store the id of + * the record. The external source may not always follow this + * convention. In these cases it is useful to override the + * `primaryKey` property to match the `primaryKey` of your external + * store. + */ + primaryKey: string; + /** + * The `attrs` object can be used to declare a simple mapping between + * property names on `DS.Model` records and payload keys in the + * serialized JSON object representing the record. An object with the + * property `key` can also be used to designate the attribute's key on + * the response payload. + */ + attrs: {}; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindAllResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindBelongsToResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindHasManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeCreateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeDeleteRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeUpdateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSaveResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSingleResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeArrayResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(typeClass: Model, hash: {}): {}; + /** + * Returns the resource's ID. + */ + extractId(modelClass: {}, resourceHash: {}): string; + /** + * Returns the resource's attributes formatted as a JSON-API "attributes object". + */ + extractAttributes(modelClass: {}, resourceHash: {}): {}; + /** + * Returns a relationship formatted as a JSON-API "relationship object". + */ + extractRelationship(relationshipModelName: {}, relationshipHash: {}): {}; + /** + * Returns a polymorphic relationship formatted as a JSON-API "relationship object". + */ + extractPolymorphicRelationship(relationshipModelName: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * Returns the resource's relationships formatted as a JSON-API "relationships object". + */ + extractRelationships(modelClass: {}, resourceHash: {}): {}; + modelNameFromPayloadKey(key: string): string; + /** + * Check if the given hasMany relationship should be serialized + */ + shouldSerializeHasMany(snapshot: Snapshot, key: string, relationshipType: string): boolean; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize how a serialized record is added to the complete + * JSON hash to be sent to the server. By default the JSON Serializer does not namespace + * the payload and just sends the raw serialized JSON object. + * If your server expects namespaced keys, you should consider using the RESTSerializer. + * Otherwise you can override this method to customize how the record is added to the hash. + * The hash property should be modified by reference. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * `serializeAttribute` can be used to customize how `DS.attr` + * properties are serialized + */ + serializeAttribute(snapshot: Snapshot, json: {}, key: string, attribute: {}): any; + /** + * `serializeBelongsTo` can be used to customize how `DS.belongsTo` + * properties are serialized. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `serializeHasMany` can be used to customize how `DS.hasMany` + * properties are serialized. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how polymorphic objects are + * serialized. Objects are considered to be polymorphic if + * `{ polymorphic: true }` is pass as the second argument to the + * `DS.belongsTo` function. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `extractMeta` is used to deserialize any meta information in the + * adapter payload. By default Ember Data expects meta information to + * be located on the `meta` property of the payload object. + */ + extractMeta(store: Store, modelClass: Model, payload: {}): any; + /** + * `extractErrors` is used to extract model errors when a call + * to `DS.Model#save` fails with an `InvalidError`. By default + * Ember Data expects error information to be located on the `errors` + * property of the payload object. + */ + extractErrors(store: Store, typeClass: Model, payload: {}, id: string|number): {}; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. By default + * `JSONSerializer` does not provide an implementation of this method. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `keyForLink` can be used to define a custom key when deserializing link + * properties. + */ + keyForLink(key: string, kind: string): string; + modelNameFromPayloadType(type: string): string; + /** + * serializeId can be used to customize how id is serialized + * For example, your server may expect integer datatype of id + */ + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + } + /** + * Normally, applications will use the `RESTSerializer` by implementing + * the `normalize` method. + */ + class RESTSerializer extends JSONSerializer { + /** + * `keyForPolymorphicType` can be used to define a custom key when + * serializing and deserializing a polymorphic type. By default, the + * returned key is `${key}Type`. + */ + keyForPolymorphicType(key: string, typeClass: string, method: string): string; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(modelClass: Model, resourceHash: {}, prop?: string): {}; + /** + * This method allows you to push a payload containing top-level + * collections of records organized per type. + */ + pushPayload(store: Store, payload: {}): any; + /** + * This method is used to convert each JSON root key in the payload + * into a modelName that it can use to look up the appropriate model for + * that part of the payload. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize the root keys serialized into the JSON. + * The hash property should be modified by reference (possibly using something like _.extend) + * By default the REST Serializer sends the modelName of a model, which is a camelized + * version of the name. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * You can use `payloadKeyFromModelName` to override the root key for an outgoing + * request. By default, the RESTSerializer returns a camelized version of the + * model's name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * You can use this method to customize how polymorphic objects are serialized. + * By default the REST Serializer creates the key by appending `Type` to + * the attribute and value from the model's camelcased model name. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how a polymorphic relationship should + * be extracted. + */ + extractPolymorphicRelationship(relationshipType: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: string): string; + } + /** + * The `DS.BooleanTransform` class is used to serialize and deserialize + * boolean attributes on Ember Data record objects. This transform is + * used when `boolean` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class BooleanTransform extends Transform { + } + /** + * The `DS.DateTransform` class is used to serialize and deserialize + * date attributes on Ember Data record objects. This transform is used + * when `date` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) + * standard. + */ + class DateTransform extends Transform { + } + /** + * The `DS.NumberTransform` class is used to serialize and deserialize + * numeric attributes on Ember Data record objects. This transform is + * used when `number` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class NumberTransform extends Transform { + } + /** + * The `DS.StringTransform` class is used to serialize and deserialize + * string attributes on Ember Data record objects. This transform is + * used when `string` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class StringTransform extends Transform { + } + /** + * The `DS.Transform` class is used to serialize and deserialize model + * attributes when they are saved or loaded from an + * adapter. Subclassing `DS.Transform` is useful for creating custom + * attributes. All subclasses of `DS.Transform` must implement a + * `serialize` and a `deserialize` method. + */ + class Transform extends Ember.Object { + /** + * When given a deserialized value from a record attribute this + * method must return the serialized value. + */ + serialize(deserialized: any, options: AttrOptions): any; + /** + * When given a serialize value from a JSON object this method must + * return the deserialized value for the record attribute. + */ + deserialize(serialized: any, options: AttrOptions): any; + } + /** + * An adapter is an object that receives requests from a store and + * translates them into the appropriate action to take against your + * persistence layer. The persistence layer is usually an HTTP API, but + * may be anything, such as the browser's local storage. Typically the + * adapter is not invoked directly instead its functionality is accessed + * through the `store`. + */ + class Adapter extends Ember.Object { + /** + * If you would like your adapter to use a custom serializer you can + * set the `defaultSerializer` property to be the name of the custom + * serializer. + */ + defaultSerializer: string; + /** + * The `findRecord()` method is invoked when the store is asked for a record that + * has not previously been loaded. In response to `findRecord()` being called, you + * should query your persistence layer for a record with the given ID. The `findRecord` + * method should return a promise that will resolve to a JavaScript object that will be + * normalized by the serializer. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * The `findAll()` method is used to retrieve all records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * This method is called when you call `query` on the store. + */ + query(store: Store, type: Model, query: {}, recordArray: AdapterPopulatedRecordArray): Promise; + /** + * The `queryRecord()` method is invoked when the store is asked for a single + * record through a query object. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * If the globally unique IDs for your records should be generated on the client, + * implement the `generateIdForRecord()` method. This method will be invoked + * each time you create a new record, and the value returned from it will be + * assigned to the record's `primaryKey`. + */ + generateIdForRecord(store: Store, type: Model, inputProperties: {}): string|number; + /** + * Proxies to the serializer's `serialize` method. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * Implement this method in a subclass to handle the creation of + * new records. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the updating of + * a record. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the deletion of + * a record. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * By default the store will try to coalesce all `fetchRecord` calls within the same runloop + * into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. + * You can opt out of this behaviour by either not implementing the findMany hook or by setting + * coalesceFindRequests to false. + */ + coalesceFindRequests: boolean; + /** + * The store will call `findMany` instead of multiple `findRecord` + * requests to find multiple records at once if coalesceFindRequests + * is true. + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * This method is used by the store to determine if the store should + * reload a record from the adapter when a record is requested by + * `store.findRecord`. + */ + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload all records from the adapter when records are requested by + * `store.findAll`. + */ + shouldReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record after the `store.findRecord` method resolves a + * cached record. + */ + shouldBackgroundReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record array after the `store.findAll` method resolves + * with a cached record array. + */ + shouldBackgroundReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + } + /** + * `DS.Serializer` is an abstract base class that you should override in your + * application to customize it for your backend. The minimum set of methods + * that you should implement is: + */ + class Serializer extends Ember.Object { + /** + * The `store` property is the application's `store` that contains + * all records. It can be used to look up serializers for other model + * types that may be nested inside the payload response. + */ + store: Store; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * The `serialize` method is used when a record is saved in order to convert + * the record into the form that your external data source expects. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * The `normalize` method is used to convert a payload received from your + * external data source into the normalized form `store.push()` expects. You + * should override this method, munge the hash and return the normalized + * payload. + */ + normalize(typeClass: Model, hash: {}): {}; + } +} +export default DS; + +declare module 'ember' { + namespace Ember { + /* + * The store is automatically injected into these objects + * + * https://github.com/emberjs/data/blob/05e95280e11c411177f2fbcb65fd83488d6a9d89/addon/setup-container.js#L71-L78 + */ + interface Route { + store: DS.Store; + } + interface Controller { + store: DS.Store; + } + interface DataAdapter { + store: DS.Store; + } + } +} diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts new file mode 100644 index 0000000000..5d9d45fd4b --- /dev/null +++ b/types/ember-data/test/adapter.ts @@ -0,0 +1,56 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPIAdapter.extend({ + // Application specific overrides go here +}); + +const Customized = DS.JSONAPIAdapter.extend({ + host: 'https://api.example.com', + namespace: 'api/v1', + headers: { + 'API_KEY': 'secret key', + 'ANOTHER_HEADER': 'Some header value' + } +}); + +const AuthTokenHeader = DS.JSONAPIAdapter.extend({ + session: Ember.inject.service('session'), + headers: Ember.computed('session.authToken', function() { + return { + 'API_KEY': this.get('session.authToken'), + 'ANOTHER_HEADER': 'Some header value' + }; + }) +}); + +const UseAjax = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + return this.ajax(url, 'POST', { + param: 'foo' + }); + } +}); + +const UseAjaxOptions = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE', { + foo: 'bar' + }); + return Ember.$.ajax(url, { + ...options + }); + } +}); + +const UseAjaxOptionsWithOptionalThirdParams = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE'); + return Ember.$.ajax(url, { + ...options + }); + } +}); diff --git a/types/ember-data/test/belongs-to.ts b/types/ember-data/test/belongs-to.ts new file mode 100644 index 0000000000..9e59aa6128 --- /dev/null +++ b/types/ember-data/test/belongs-to.ts @@ -0,0 +1,16 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Folder extends DS.Model { + name = DS.attr('string'); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +const folder = Folder.create(); +assertType(folder.get('parent')); +assertType(folder.get('parent').get('name')); +folder.get('parent').then(parent => { + assertType(parent); + assertType(parent.get('name')); +}); diff --git a/types/ember-data/test/has-many.ts b/types/ember-data/test/has-many.ts new file mode 100644 index 0000000000..7fb586ff4a --- /dev/null +++ b/types/ember-data/test/has-many.ts @@ -0,0 +1,43 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Comment extends DS.Model { + text = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + commentsAsync = DS.hasMany('comment'); + commentsSync = DS.hasMany('comment', { async: false }); +} + +const post = BlogPost.create(); + +assertType>(post.get('commentsSync').reload()); +assertType(post.get('commentsSync').createRecord()); + +const comment = post.get('commentsSync').get('firstObject'); +assertType(comment); +if (comment) { + assertType(comment.get('text')); +} + +assertType>(post.get('commentsAsync').reload()); +assertType(post.get('commentsAsync').createRecord()); +assertType(post.get('commentsAsync').get('firstObject')); + +const commentAsync = post.get('commentsAsync').get('firstObject'); +assertType(commentAsync); +if (commentAsync) { + assertType(commentAsync.get('text')); +} +assertType(post.get('commentsAsync').get('isFulfilled')); + +post.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); + assertType(comments.get('firstObject')!.get('text')); +}); + +class Polymorphic extends DS.Model { + paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); +} diff --git a/types/ember-data/test/injections.ts b/types/ember-data/test/injections.ts new file mode 100644 index 0000000000..4c0a6e4e6b --- /dev/null +++ b/types/ember-data/test/injections.ts @@ -0,0 +1,22 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +Ember.Route.extend({ + model(): any { + return this.store.findAll('my-model'); + } +}); + +Ember.Controller.extend({ + actions: { + create(): any { + return this.store.createRecord('my-model'); + } + } +}); + +Ember.DataAdapter.extend({ + test() { + this.store.findRecord('my-model', 123); + } +}); diff --git a/types/ember-data/test/lib/assert.ts b/types/ember-data/test/lib/assert.ts new file mode 100644 index 0000000000..10094b9616 --- /dev/null +++ b/types/ember-data/test/lib/assert.ts @@ -0,0 +1,2 @@ +/** Static assertion that `value` has type `T` */ +export declare function assertType(value: T): void; diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts new file mode 100644 index 0000000000..b3fa04e086 --- /dev/null +++ b/types/ember-data/test/model.ts @@ -0,0 +1,29 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +const Person = DS.Model.extend({ + firstName: DS.attr(), + lastName: DS.attr(), + title: DS.attr({ defaultValue: "The default" }), + title2: DS.attr({ defaultValue: () => "The default" }), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }) +}); + +const User = DS.Model.extend({ + username: DS.attr('string'), + email: DS.attr('string'), + verified: DS.attr('boolean', { defaultValue: false }), + createdAt: DS.attr('date', { + defaultValue() { return new Date(); } + }) +}); + +const user = User.create({ username: 'dwickern' }); +assertType(user.get('id')); +assertType(user.get('username')); +assertType(user.get('verified')); +assertType(user.get('createdAt')); diff --git a/types/ember-data/test/record-reference.ts b/types/ember-data/test/record-reference.ts new file mode 100644 index 0000000000..bb4fda42d4 --- /dev/null +++ b/types/ember-data/test/record-reference.ts @@ -0,0 +1,38 @@ +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class User extends DS.Model { + username = DS.attr('string'); +} + +let userRef = store.getReference('user', 1); + +// get the record of the reference (null if not yet available) +let user = userRef.value(); +if (user !== null) { + assertType(user); +} + +// get the identifier of the reference +if (userRef.remoteType() === 'id') { + let id = userRef.id(); + assertType(id); +} + +// load user (via store.find) +userRef.load().then(user => { + assertType(user); +}); + +// or trigger a reload +userRef.reload().then(user => { + assertType(user); +}); + +// provide data for reference +userRef.push({ id: 1, username: '@user' }).then(function(user) { + assertType(user); + userRef.value() === user; +}); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts new file mode 100644 index 0000000000..a878428bc4 --- /dev/null +++ b/types/ember-data/test/relationships.ts @@ -0,0 +1,30 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +declare const store: DS.Store; + +const Person = DS.Model.extend({ + children: DS.hasMany('folder', { inverse: 'parent' }), + parent: DS.belongsTo('folder', { inverse: 'children' }) +}); + +const Polymorphic = DS.Model.extend({ + paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) +}); + +class Comment extends DS.Model { + author = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + tag = DS.attr('string'); + comments = DS.hasMany('comment', { async: true }); + relatedPosts = DS.hasMany('post'); +} + +let blogPost = store.peekRecord('blog-post', 1); +blogPost!.get('comments').then((comments) => { + // now we can work with the comments + let author: string = comments.get('firstObject')!.get('author'); +}); diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts new file mode 100644 index 0000000000..986020144f --- /dev/null +++ b/types/ember-data/test/serializer.ts @@ -0,0 +1,38 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPISerializer.extend({}); + +const Customized = DS.JSONAPISerializer.extend({ + serialize(snapshot: DS.Snapshot, options: {}) { + let json: any = this._super(...Array.from(arguments)); + + json.data.attributes.cost = { + amount: json.data.attributes.amount, + currency: json.data.attributes.currency + }; + + return json; + }, + normalizeResponse(store: DS.Store, primaryModelClass: DS.Model, payload: any, id: string|number, requestType: string) { + payload.data.attributes.amount = payload.data.attributes.cost.amount; + payload.data.attributes.currency = payload.data.attributes.cost.currency; + + delete payload.data.attributes.cost; + + return this._super(...Array.from(arguments)); + } +}); + +const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { + attrs: { + author: { + serialize: false, + deserialize: 'records' + }, + comments: { + deserialize: 'records', + serialize: 'ids' + } + } +}); diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts new file mode 100644 index 0000000000..f7560a231f --- /dev/null +++ b/types/ember-data/test/store.ts @@ -0,0 +1,119 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class Post extends DS.Model { + title = DS.attr('string'); +} + +let post = store.createRecord('post', { + title: 'Rails is Omakase', + body: 'Lorem ipsum' +}); + +post.save(); // => POST to '/posts' +post.save().then((saved) => { + assertType(saved); +}); + +store.findRecord('post', 1).then(function(post) { + post.get('title'); // => "Rails is Omakase" + post.set('title', 'A new post'); + post.save(); // => PATCH to '/posts/1' +}); + +class User extends DS.Model { + username = DS.attr('string'); +} + +store.queryRecord('user', {}).then(function(user) { + let username = user.get('username'); + console.log(`Currently logged in as ${username}`); +}); + +store.findAll('blog-post'); // => GET /blog-posts +store.findAll('author', { reload: true }).then(function(authors) { + authors.getEach('id'); // ['first', 'second'] +}); +store.findAll('post', { + adapterOptions: { subscribe: false } +}); +store.findAll('post', { include: 'comments,comments.author' }); + +store.peekAll('blog-post'); // => no network request + +if (store.hasRecordForId('post', 1)) { + let maybePost = store.peekRecord('post', 1); + if (maybePost) { + maybePost.get('id'); // 1 + } +} + +class Message extends DS.Model { + hasBeenSeen = DS.attr('boolean'); +} + +const messages = store.peekAll('message'); +messages.forEach(function(message) { + message.set('hasBeenSeen', true); +}); +messages.save(); + +const people = store.peekAll('person'); +people.get('isUpdating'); // false +people.update().then(function() { + people.get('isUpdating'); // false +}); +people.get('isUpdating'); // true + +const MyRoute = Ember.Route.extend({ + model(params: any): any { + return this.store.findRecord('post', params.post_id, {include: 'comments,comments.author'}); + } +}); + +// GET to /users?filter[email]=tomster@example.com +const tom = store.query('user', { + filter: { + email: 'tomster@example.com' + } +}).then(function(users) { + return users.get("firstObject"); +}); + +// GET /users?isAdmin=true +const admins = store.query('user', { isAdmin: true }); +admins.then(function() { + console.log(admins.get("length")); // 42 +}); +admins.update().then(function() { + admins.get('isUpdating'); // false + console.log(admins.get("length")); // 123 +}); + +store.push({ + data: [{ + id: 1, + type: 'album', + attributes: { + title: 'Fewer Moving Parts', + artist: 'David Bazan', + songCount: 10 + }, + relationships: {} + }, { + id: 2, + type: 'album', + attributes: { + title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time', + artist: 'Bon Iver', + songCount: 2 + }, + relationships: {} + }] +}); + +assertType(store.adapterFor('person')); +assertType(store.serializerFor('person')); diff --git a/types/ember-data/test/transform.ts b/types/ember-data/test/transform.ts new file mode 100644 index 0000000000..b76d40a73f --- /dev/null +++ b/types/ember-data/test/transform.ts @@ -0,0 +1,16 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Point extends Ember.Object { + x: number; + y: number; +} + +const PointTransform = DS.Transform.extend({ + serialize(value: Point): number[] { + return [value.get('x'), value.get('y')]; + }, + deserialize(value: [ number, number ]): Point { + return Point.create({ x: value[0], y: value[1] }); + } +}); diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json new file mode 100644 index 0000000000..155515ac6b --- /dev/null +++ b/types/ember-data/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/lib/assert.ts", + "test/model.ts", + "test/adapter.ts", + "test/serializer.ts", + "test/transform.ts", + "test/relationships.ts", + "test/store.ts", + "test/has-many.ts", + "test/belongs-to.ts", + "test/record-reference.ts", + "test/injections.ts" + ] +} diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json new file mode 100644 index 0000000000..dd3a7f529c --- /dev/null +++ b/types/ember-data/tslint.json @@ -0,0 +1,16 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + // not sure what this means + "no-single-declare-module": false, + "object-literal-key-quotes": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "prefer-const": false, + "no-unnecessary-generics": false + } +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index bb6cce8b36..adef4e70c2 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -558,6 +558,8 @@ declare module 'ember' { **/ interface ArrayProxy extends MutableArray {} class ArrayProxy extends Object.extend(MutableArray as {}) { + content: NativeArray; + /** * Should actually retrieve the object at the specified index from the * content. You can override this method in subclasses to transform the @@ -1837,7 +1839,7 @@ declare module 'ember' { * A hook you can implement to convert the URL into the model for * this route. */ - model(params: {}, transition: Transition): T | Rsvp.Promise; + model(params: {}, transition: Transition): any; /** * Returns the model of a parent (or any ancestor) route diff --git a/types/ember/test/array-proxy.ts b/types/ember/test/array-proxy.ts old mode 100755 new mode 100644 index 280ab52ded..dceea7b847 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,6 +21,6 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x: MyNewProxy = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy; assertType(x.get('firstObject')); assertType(x.isNew); diff --git a/types/emoji-mart/dist-es/components/category.d.ts b/types/emoji-mart/dist-es/components/category.d.ts new file mode 100644 index 0000000000..8cd4ceefbb --- /dev/null +++ b/types/emoji-mart/dist-es/components/category.d.ts @@ -0,0 +1,20 @@ +import React = require('react'); + +import { EmojiData } from '..'; + +import { Emoji, EmojiProps, I18n } from '.'; + +export interface Props { + emojis?: Array; + hasStickyPosition?: boolean; + name: string; + native: boolean; + perLine: number; + emojiProps: EmojiProps; + recent?: string[]; + i18n: I18n; +} + +export default class Category extends React.Component { + // all methods and properties inside this are most likely intended to be private +} diff --git a/types/emoji-mart/dist-es/components/emoji.d.ts b/types/emoji-mart/dist-es/components/emoji.d.ts new file mode 100644 index 0000000000..030ff7ce12 --- /dev/null +++ b/types/emoji-mart/dist-es/components/emoji.d.ts @@ -0,0 +1,31 @@ +import React = require('react'); + +import { EmojiData, EmojiSkin } from '..'; + +export type BackgroundImageFn = (set: EmojiSet, sheetSize: EmojiSheetSize) => string; +export type EmojiSet = 'apple'|'google'|'twitter'|'emojione'|'messenger'|'facebook'; +export type EmojiSheetSize = 16|20|32|64; + +export interface Props { + onOver?(emoji: EmojiData, e: React.MouseEvent): void; + onLeave?(emoji: EmojiData, e: React.MouseEvent): void; + onClick?(emoji: EmojiData, e: React.MouseEvent): void; + /** defaults to returning a png from unpkg.com-hosted emoji-datasource-${set} */ + backgroundImageFn?: BackgroundImageFn; + native?: boolean; + forceSize?: boolean; + tooltip?: boolean; + /** defaults to 1 */ + skin?: EmojiSkin; + /** defaults to 64 */ + sheetSize?: EmojiSheetSize; + /** defaults to 'apple' */ + set?: EmojiSet; + size: number; + emoji: string|EmojiData; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const Emoji: React.SFC; + +export { Emoji as default }; diff --git a/types/emoji-mart/dist-es/components/index.d.ts b/types/emoji-mart/dist-es/components/index.d.ts new file mode 100644 index 0000000000..6fc29ecd54 --- /dev/null +++ b/types/emoji-mart/dist-es/components/index.d.ts @@ -0,0 +1,4 @@ +// The other exports on the components folder are not public API +export { default as Category, Props as CategoryProps } from './category'; +export { default as Emoji, Props as EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from './emoji'; +export { default as Picker, Props as PickerProps, I18n, PartialI18n, CustomEmoji } from './picker'; diff --git a/types/emoji-mart/dist-es/components/picker.d.ts b/types/emoji-mart/dist-es/components/picker.d.ts new file mode 100644 index 0000000000..9f9132df05 --- /dev/null +++ b/types/emoji-mart/dist-es/components/picker.d.ts @@ -0,0 +1,54 @@ +import React = require('react'); + +import { EmojiData, EmojiSkin } from '..'; + +import { Category, Emoji, EmojiProps, BackgroundImageFn, EmojiSet, EmojiSheetSize } from '.'; + +// tslint:disable-next-line interface-name +export interface I18n { + search: string; + categories: Record<'search'|'recent'|'people'|'nature'|'foods'|'activity'|'places'|'objects'|'symbols'|'flags'|'custom', string>; + notfound: string; +} + +export type PartialI18n = Partial & { categories: Partial}>; + +export interface CustomEmoji { + // id is overridden by short_names[0] + name: string; + /** Must contain at least one name. The first name is used as the unique id. */ + short_names: string[]; + emoticons?: string[]; + keywords?: string[]; + imageUrl: string; +} + +export interface Props { + /** NOTE: default is not preventable */ + onClick?(emoji: EmojiData, e: React.MouseEvent): void; + perLine?: number; + emojiSize?: number; + i18n?: PartialI18n; + style?: React.CSSProperties; + title?: string; + emoji?: string; + color?: string; + set?: EmojiSet; + skin?: EmojiSkin; + native?: boolean; + backgroundImageFn?: BackgroundImageFn; + sheetSize?: EmojiSheetSize; + emojisToShowFilter?(emoji: EmojiData): boolean; + showPreview?: boolean; + emojiTooltip?: boolean; + include?: string[]; + exclude?: string[]; + recent?: string[]; + autoFocus?: boolean; + /** NOTE: custom emoji are copied into a singleton object on every new mount */ + custom: CustomEmoji[]; +} + +export default class Picker extends React.PureComponent { + // everything inside it is supposed to be private +} diff --git a/types/emoji-mart/dist-es/index.d.ts b/types/emoji-mart/dist-es/index.d.ts new file mode 100644 index 0000000000..e49d37fcf6 --- /dev/null +++ b/types/emoji-mart/dist-es/index.d.ts @@ -0,0 +1,15 @@ +export { default as emojiIndex, EmojiData, EmojiSkin } from './utils/emoji-index'; +export { default as store, StoreHandlers } from './utils/store'; +export { default as frequently } from './utils/frequently'; + +export { + Picker, + PickerProps, + I18n, + PartialI18n, + CustomEmoji, + Emoji, + EmojiProps, + Category, + CategoryProps +} from './components'; diff --git a/types/emoji-mart/dist-es/utils/emoji-index.d.ts b/types/emoji-mart/dist-es/utils/emoji-index.d.ts new file mode 100644 index 0000000000..c6499e663c --- /dev/null +++ b/types/emoji-mart/dist-es/utils/emoji-index.d.ts @@ -0,0 +1,25 @@ +export type EmojiSkin = 1|2|3|4|5|6; + +export interface EmojiData { + id: string; + name: string; + colons: string; + /** Reverse mapping to keyof emoticons */ + emoticons: string[]; + unified: string; + skin: EmojiSkin|null; + native: string; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + search(query: ''): null + search(query: string): EmojiData|null + + emojis: { [emoji: string]: EmojiData } + + /** Mapping of string to keyof emojis */ + emoticons: { [emoticon: string]: string } +}; + +export { _default as default }; diff --git a/types/emoji-mart/dist-es/utils/frequently.d.ts b/types/emoji-mart/dist-es/utils/frequently.d.ts new file mode 100644 index 0000000000..d2f318de5f --- /dev/null +++ b/types/emoji-mart/dist-es/utils/frequently.d.ts @@ -0,0 +1,9 @@ +import { EmojiData } from '..'; + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + add(emoji: Pick): void + get(perLine: number): string[] +}; + +export { _default as default }; diff --git a/types/emoji-mart/dist-es/utils/store.d.ts b/types/emoji-mart/dist-es/utils/store.d.ts new file mode 100644 index 0000000000..009284bd7b --- /dev/null +++ b/types/emoji-mart/dist-es/utils/store.d.ts @@ -0,0 +1,15 @@ +export interface StoreHandlers { + getter?(key: string): any; + setter?(key: string, value: any): void; +} + +// tslint:disable-next-line strict-export-declare-modifiers +declare const _default: { + setHandlers(handlers?: StoreHandlers): void + setNamespace(namespace: string): void + update(state: {[key: string]: any}): void + set(key: string, value: any): void + get(key: string): any +}; + +export { _default as default }; diff --git a/types/emoji-mart/emoji-mart-tests.tsx b/types/emoji-mart/emoji-mart-tests.tsx new file mode 100644 index 0000000000..7b7b8d0471 --- /dev/null +++ b/types/emoji-mart/emoji-mart-tests.tsx @@ -0,0 +1,93 @@ +// Port of https://github.com/missive/emoji-mart/blob/master/src/components/emoji.js + +import React = require('react'); + +import { Picker, Emoji, EmojiProps, CustomEmoji } from 'emoji-mart'; + +declare var console: { log(...args: any[]): void; }; + +const CUSTOM_EMOJIS: CustomEmoji[] = [ + { + name: 'Party Parrot', + short_names: ['parrot'], + keywords: ['party'], + imageUrl: 'http://cultofthepartyparrot.com/parrots/hd/parrot.gif' + }, + { + name: 'Octocat', + short_names: ['octocat'], + keywords: ['github'], + imageUrl: 'https://assets-cdn.github.com/images/icons/emoji/octocat.png?v7' + }, + { + name: 'Squirrel', + short_names: ['shipit', 'squirrel'], + keywords: ['github'], + imageUrl: 'https://assets-cdn.github.com/images/icons/emoji/shipit.png?v7' + }, +]; + +interface State { + native: boolean; + set: EmojiProps['set']|'native'; + emoji: string; + title: string; + custom: CustomEmoji[]; +} + +class Example extends React.Component<{}, State> { + readonly state: Readonly = { + native: true, + set: 'apple', + emoji: 'point_up', + title: 'Pick your emoji…', + custom: CUSTOM_EMOJIS + }; + render() { + return ( +
+
+

Emoji Mart 🏬

+
+ +
+ {(['native', 'apple', 'google', 'twitter', 'emojione', 'messenger', 'facebook'] as Array).map((set) => { + const props = { disabled: !this.state.native && set === this.state.set }; + + if (set === 'native' && this.state.native) { + props.disabled = true; + } + + return ( + + ); + })} +
+ +
+ +
+
+ ); + } +} diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts new file mode 100644 index 0000000000..1116d6eb6f --- /dev/null +++ b/types/emoji-mart/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for emoji-mart 2.2 +// Project: https://github.com/missive/emoji-mart +// Definitions by: Diogo Franco +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// These definitions should work with 2.3, but the tests doesn't pass on 2.3. + +export * from './dist-es'; diff --git a/types/emoji-mart/tsconfig.json b/types/emoji-mart/tsconfig.json new file mode 100644 index 0000000000..fb776e9a21 --- /dev/null +++ b/types/emoji-mart/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "dist-es/components/category.d.ts", + "dist-es/components/emoji.d.ts", + "dist-es/components/index.d.ts", + "dist-es/components/picker.d.ts", + "dist-es/utils/emoji-index.d.ts", + "dist-es/utils/frequently.d.ts", + "dist-es/utils/store.d.ts", + "dist-es/index.d.ts", + "emoji-mart-tests.tsx" + ] +} diff --git a/types/emoji-mart/tslint.json b/types/emoji-mart/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/emoji-mart/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/emscripten/emscripten-tests.ts b/types/emscripten/emscripten-tests.ts index 153ea6b5de..627efba590 100644 --- a/types/emscripten/emscripten-tests.ts +++ b/types/emscripten/emscripten-tests.ts @@ -18,6 +18,7 @@ function ModuleTest(): void { Module.print = function(text) { alert('stdout: ' + text) }; var int_sqrt = Module.cwrap('int_sqrt', 'number', ['number']) + int_sqrt = Module.cwrap('int_sqrt', null, ['number']) int_sqrt(12) int_sqrt(28) @@ -27,6 +28,7 @@ function ModuleTest(): void { var x = Module.getValue(buf, 'i32') + 123; Module.HEAPU8.set(myTypedArray, buf); Module.ccall('my_function', 'number', ['number'], [buf]); + Module.ccall('my_function', null, ['number'], [buf]); Module._free(buf); Module.destroy({}); } diff --git a/types/emscripten/index.d.ts b/types/emscripten/index.d.ts index 14260dd9d4..4db8ac4925 100644 --- a/types/emscripten/index.d.ts +++ b/types/emscripten/index.d.ts @@ -40,8 +40,8 @@ declare namespace Module { var Runtime: any; - function ccall(ident: string, returnType: string, argTypes: string[], args: any[]): any; - function cwrap(ident: string, returnType: string, argTypes: string[]): any; + function ccall(ident: string, returnType: string | null, argTypes: string[], args: any[]): any; + function cwrap(ident: string, returnType: string | null, argTypes: string[]): any; function setValue(ptr: number, value: any, type: string, noSafe?: boolean): void; function getValue(ptr: number, type: string, noSafe?: boolean): number; diff --git a/types/engine.io-client/index.d.ts b/types/engine.io-client/index.d.ts index 2f1d69a1d6..0abb98eb79 100644 --- a/types/engine.io-client/index.d.ts +++ b/types/engine.io-client/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/socketio/engine.io-client // Definitions by: KentarouTakeda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/enigma.js/enigma.js-tests.ts b/types/enigma.js/enigma.js-tests.ts new file mode 100644 index 0000000000..10f6aae226 --- /dev/null +++ b/types/enigma.js/enigma.js-tests.ts @@ -0,0 +1,10 @@ +import * as enigma from "enigma.js"; +// import enigma = require("enigma.js"); + +const config: enigmaJS.IConfig = { + url: "http://127.0.0.1:4848/", + schema: {} + }; +enigma.create(config).open().then((global) => { + console.log("connect fine"); +}); diff --git a/types/enigma.js/index.d.ts b/types/enigma.js/index.d.ts new file mode 100644 index 0000000000..38fc18da16 --- /dev/null +++ b/types/enigma.js/index.d.ts @@ -0,0 +1,194 @@ +// Type definitions for enigma.js 2.2 +// Project: https://github.com/qlik-oss/enigma.js/ +// Definitions by: Konrad Mattheis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare module "enigma.js" { + const e: IEnigmaClass; + export = e; +} + +// declare const enigmaJS: IEnigmaClass; +// export = enigmaJS; +// export as namespace enigmaJS; + +interface IEnigmaClass { + /** + * Create a session object. + * @returns - Returns a session. + * Note: See Configuration for the configuration options. + */ + create(config: enigmaJS.IConfig): enigmaJS.ISession; +} + +declare namespace enigmaJS { + type MixinType = "Doc"| "GenericObject"| "GenericBookmark" | string; + + interface IMixin { + /** + * QIX Engine types like for example GenericObject, Doc, GenericBookmark, are supported but also custom GenericObject + * types such as barchart, story and myCustomType. + * An API will get both their generic type as well as custom type mixins applied. + */ + types: MixinType[]; + + init(args: {config: any, api: IGeneratedAPI}): void; + + /** + * mixin.extend is an object containing methods to extend the generated API with. These method names cannot already exist or enigma.js will throw an error. + */ + extend?: [any]; + + /** + * mixin.override is an object containing methods that overrides existing API methods. + * These method names needs to exist already* or engima.js will throw an error. + * Be careful when overriding, you may break expected behaviors in other mixins or your application. + * base is a reference to the previous mixin method, can be used to invoke the mixin chain before this mixin method. + */ + override?: [any]; + } + + interface IProtocol { + // Set to false to disable the use of the bandwidth-reducing delta protocol. + delta?: boolean; + } + + /** + * This section describes the configuration object that is sent into enigma.create(config). + */ + interface IConfig { + /** + * Object containing the specification for the API to generate. Corresponds to a specific version of the QIX Engine API. + */ + schema: object; + /** + * String containing a proper websocket URL to QIX Engine. + */ + url: string; + /** + * A function to use when instantiating the WebSocket, mandatory for Node.js. + */ + createSocket?: any; + /** + * ES6-compatible Promise library. + */ + Promise?: any; + /** + * Set to true if the session should be suspended instead of closed when the websocket is closed. + */ + suspendOnClose?: boolean; + /** + * Mixins to extend/augment the QIX Engine API. + * See Mixins section for more information how each entry in this array should look like. + * Mixins are applied in the array order. + */ + mixins?: [any]; + /** + * Interceptors for augmenting responses before they are passed into mixins and end-users. + * See Interceptors section for more information how each entry in this array should look like. + * Interceptors are applied in the array order. + */ + interceptors?: [any]; + /** + * An object containing additional JSON-RPC request parameters. + * protocol.delta : Set to false to disable the use of the bandwidth-reducing delta protocol. + */ + protocol?: any; + } + + interface ISession { + /** + * Establishes the websocket against the configured URL. Eventually resolved with the QIX global interface when the connection has been established. + * @return Promise. + */ + open(): Promise; + + /** + * Closes the websocket and cleans up internal caches, also triggers the closed event on all generated APIs. + * Eventually resolved when the websocket has been closed. + * + * Note: you need to manually invoke this when you want to close a session and config.suspendOnClose is true. + * @return Promise. + */ + close(): Promise; + + /** + * Suspends the enigma.js session by closing the websocket and rejecting all method calls until it has been resumed again. + * @return Promise. + */ + suspend(): Promise; + + /** + * Resume a previously suspended enigma.js session by re-creating the websocket and, if possible, re-open the document + * as well as refreshing the internal caches. If successful, changed events will be triggered on all generated APIs, + * and on the ones it was unable to restore, the closed event will be triggered. + * @param onlyIfAttached onlyIfAttached can be used to only allow resuming if the QIX Engine session was reattached properly. + * @return Promise. + * Note: Eventually resolved when the websocket (and potentially the previously opened document, and generated APIs) has been restored, + * rejected when it fails any of those steps, or when onlyIfAttached is true and a new QIX Engine session was created. + */ + resume(onlyIfAttached?: boolean): Promise; + + /** + * Handle opened state. This event is triggered whenever the websocket is connected and ready for communication. + * + * Handle closed state. This event is triggered when the underlying websocket is closed and config.suspendOnClose is false. + * + * Handle suspended state. This event is triggered in two cases (listed below). It is useful in scenarios where you for example + * want to block interaction in your application until you are resumed again. + * If config.suspendOnClose is true and there was a network disconnect (socked closed) + * If you ran session.suspend() + * The evt.initiator value is a string indicating what triggered the suspended state. Possible values: network, manual. + * + * Handle resumed state. This event is triggered when the session was properly resumed. + * It is useful in scenarios where you for example can close blocking modal dialogs and allow the user to interact with your application again. + * + * notification:* + * @param event - Event that triggers the function + * @param func - Called function + */ + on(event: "opened" | "close" | "suspended" | "resumed" | string, func: any): void; + } + + interface IGeneratedAPI { + /** + * This property contains the unique identifier for this API. + */ + id: string; + + /** + * This property contains the schema class name for this API. + */ + type: string; + + /** + * Despite the name, this property corresponds to the qInfo.qType property on your generic object's properties object. + */ + genericType: string; + + /** + * This property contains a reference to the session that this API belongs to. + */ + session: ISession; + + /** + * This property contains the handle QIX Engine assigned to the API. + * Used internally in enigma.js for caches and JSON-RPC + */ + handle: number; + + /** + * register a function for events + * @param event - function called if this event occures + * @param func - function that is called + */ + on(event: "changed" | "closed", func: () => void): void; + + /** + * manual emit an events + * @param event - event that occures + */ + emit(event: "changed" | "closed"): void; + } +} diff --git a/types/enigma.js/tsconfig.json b/types/enigma.js/tsconfig.json new file mode 100644 index 0000000000..b3b93456f0 --- /dev/null +++ b/types/enigma.js/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "enigma.js-tests.ts" + ] +} \ No newline at end of file diff --git a/types/enigma.js/tslint.json b/types/enigma.js/tslint.json new file mode 100644 index 0000000000..84cbb5f289 --- /dev/null +++ b/types/enigma.js/tslint.json @@ -0,0 +1,13 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "ban-types": false, + "no-empty-interface": false, + "no-mergeable-namespace": false, + "no-unnecessary-generics": false, + "no-single-declare-module": false, + "no-declare-current-package": false, + "interface-name": false + } +} diff --git a/types/enzyme-adapter-react-15/index.d.ts b/types/enzyme-adapter-react-15/index.d.ts index b0b289d08d..01307da953 100644 --- a/types/enzyme-adapter-react-15/index.d.ts +++ b/types/enzyme-adapter-react-15/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/airbnb/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-adapter-react-16/index.d.ts b/types/enzyme-adapter-react-16/index.d.ts index 39aa6c03a6..82927b03e5 100644 --- a/types/enzyme-adapter-react-16/index.d.ts +++ b/types/enzyme-adapter-react-16/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/airbnb/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 63e716c50b..c48c050357 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,5 +1,14 @@ import * as React from "react"; -import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { + shallow, + mount, + render, + ShallowWrapper, + ReactWrapper, + configure, + EnzymeAdapter, + ShallowRendererProps, +} from "enzyme"; import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces @@ -24,6 +33,18 @@ class MyComponent extends Component { const MyStatelessComponent = (props: StatelessProps) => ; +// Enzyme.configure +function configureTest() { + const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; + configure(configureAdapter); + + const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick = { + adapter: {}, + disableLifecycleMethods: true, + }; + configure(configureAdapterAndDisableLifecycle); +} + // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = @@ -50,7 +71,8 @@ function ShallowWrapperTest() { context: { test: "a", }, - lifecycleExperimental: true + lifecycleExperimental: true, + disableLifecycleMethods: true }); } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 101215462f..3a8ea149f9 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -54,22 +54,22 @@ export interface CommonWrapper

{ /** * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. */ - contains(node: ReactElement | string): boolean; + contains(node: ReactElement | Array> | string): boolean; /** * Returns whether or not a given react element exists in the shallow render tree. */ - containsMatchingElement(node: ReactElement): boolean; + containsMatchingElement(node: ReactElement | Array>): boolean; /** * Returns whether or not all the given react elements exists in the shallow render tree */ - containsAllMatchingElements(nodes: Array>): boolean; + containsAllMatchingElements(nodes: Array> | Array>>): boolean; /** * Returns whether or not one of the given react elements exists in the shallow render tree. */ - containsAnyMatchingElements(nodes: Array>): boolean; + containsAnyMatchingElements(nodes: Array> | Array>>): boolean; /** * Returns whether or not the current render tree is equal to the given node, based on the expected value. @@ -353,6 +353,7 @@ export interface CommonWrapper

{ length: number; } +// tslint:disable-next-line no-empty-interface export interface ShallowWrapper

extends CommonWrapper {} export class ShallowWrapper

{ constructor(nodes: JSX.Element[] | JSX.Element, root?: ShallowWrapper, options?: ShallowRendererProps); @@ -437,6 +438,7 @@ export class ShallowWrapper

{ parent(): ShallowWrapper; } +// tslint:disable-next-line no-empty-interface export interface ReactWrapper

extends CommonWrapper {} export class ReactWrapper

{ constructor(nodes: JSX.Element | JSX.Element[], root?: ReactWrapper, options?: MountRendererProps); @@ -549,6 +551,12 @@ export class ReactWrapper

{ } export interface ShallowRendererProps { + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/api/shallow.md#arguments + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; /** * Enable experimental support for full react lifecycle methods */ @@ -600,4 +608,14 @@ export class EnzymeAdapter { * Configure enzyme to use the correct adapter for the react verstion * This is enabling the Enzyme configuration with adapters in TS */ -export function configure(options: { adapter: EnzymeAdapter }): void; +export function configure(options: { + adapter: EnzymeAdapter, + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/guides/migration-from-2-to-3.md#lifecycle-methods + // Actually, `{adapter:} & Pick` is more precise. However, + // in that case jsdoc won't be shown + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; +}): void; diff --git a/types/epilogue/epilogue-tests.ts b/types/epilogue/epilogue-tests.ts new file mode 100644 index 0000000000..0cf40fd1e9 --- /dev/null +++ b/types/epilogue/epilogue-tests.ts @@ -0,0 +1,33 @@ +import * as epilogue from 'epilogue'; +import * as express from 'express'; +import * as Sequelize from 'sequelize'; + +const database = new Sequelize({ }); + +epilogue.initialize({ + app: express(), + sequelize: database +}); + +epilogue.initialize({ + app: express(), + sequelize: database, + base: '' +}); + +epilogue.initialize({ + app: express(), + sequelize: database, + base: '', + updateMethod: '' +}); + +const User = database.define('User', { + username: Sequelize.STRING, + birthday: Sequelize.DATE +}); + +epilogue.resource({ + model: User, + endpoints: ['/users', '/users/:id'] +}); diff --git a/types/epilogue/index.d.ts b/types/epilogue/index.d.ts new file mode 100644 index 0000000000..3fe56b9e9f --- /dev/null +++ b/types/epilogue/index.d.ts @@ -0,0 +1,199 @@ +// Type definitions for epilogue 0.7 +// Project: https://github.com/dchester/epilogue +// Definitions by: Satana Charuwichitratana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { + Sequelize, + AssociationOptions, + DataTypeAbstract, + DataTypeString, + DataTypeChar, + DataTypeText, + DataTypeNumber, + DataTypeInteger, + DataTypeBigInt, + DataTypeFloat, + DataTypeTime, + DataTypeDate, + DataTypeDateOnly, + DataTypeBoolean, + DataTypeNow, + DataTypeBlob, + DataTypeDecimal, + DataTypeUUID, + DataTypeUUIDv1, + DataTypeUUIDv4, + DataTypeHStore, + DataTypeJSONType, + DataTypeJSONB, + DataTypeVirtual, + DataTypeArray, + DataTypeEnum, + DataTypeRange, + DataTypeReal, + DataTypeDouble, + DataTypeGeometry +} from 'sequelize'; + +import { Express, Request, Response } from 'express'; + +export class Endpoint { + constructor(endpoint: string); + string: string; + attributes: string[]; +} + +export class Resource { + constructor(options: ResourceOptions); + app: Express; + sequelize: Sequelize; + model: any; + include: Array<{ model: any } | string>; + associationOptions: ResourceAssociationOptions; + readOnlyAttributes: string[]; + excludeAttributes: string[]; + attributes: string[]; + actions: string[]; + endpoints: { + singular: string; + plural: string; + }; + updateMethod: string; + pagination: boolean; + search: ResourceSearchOption; + sort: ResourceSortOption; + reloadInstances: boolean; + controllers: Controllers; +} + +export interface Controllers { + base: BaseController; + create: CreateController; + read: ReadController; + update: UpdateController; + delete: DeleteController; + list: ListController; +} + +export namespace Errors { + class EpilogueError extends Error { + constructor(status: number | EpilogueError, message?: string, errors?: string[], cause?: Error); + + name: string; + message: string; + errors: string[]; + status: number | EpilogueError; + cause: Error; + } + + class NotFoundError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class BadRequestError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class ForbiddenError extends EpilogueError { + constructor(message?: string, errors?: string[], cause?: Error); + } + + class RequestCompleted extends Error { + constructor(); + } +} + +export interface ResourceAssociationOptions extends AssociationOptions { + removeForeignKeys: boolean; +} + +export interface ResourceSearchOption { + param: string; + operator: string; + attributes: string[]; +} + +export interface ResourceSortOption { + param: string; + default: string; +} + +export interface InitializeOptions { + app: Express; + sequelize: Sequelize; + base?: string; + updateMethod?: string; +} + +export interface BaseContollerOptions { + endpoint: string; + model: any; + app: Express; + resource: Resource; + include: Array<{ model: any } | string>; +} + +export interface Context { + instance: Resource; + criteria: any; + attributes: any; + options: any; + continue: () => void; + skip: () => void; + stop: () => void; + error: (status: number | Errors.EpilogueError, message?: string, errorList?: string[], cause?: Error) => void; +} + +export class BaseController { + constructor(options: BaseContollerOptions); + endpoint: Endpoint; + model: any; +} + +export class CreateController extends BaseController { + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class ReadController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class UpdateController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class DeleteController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + write: (req: Request, res: Response, context: Context) => Promise<() => void>; +} + +export class ListController extends BaseController { + fetch: (req: Request, res: Response, context: Context) => Promise<() => void>; + _safeishParse: (value: any, type: DataTypeAbstract | DataTypeString | DataTypeChar | DataTypeText | DataTypeNumber | + DataTypeInteger | DataTypeBigInt | DataTypeFloat | DataTypeTime | DataTypeDate | DataTypeDateOnly | + DataTypeBoolean | DataTypeNow | DataTypeBlob | DataTypeDecimal | DataTypeUUID | DataTypeUUIDv1 | + DataTypeUUIDv4 | DataTypeHStore | DataTypeJSONType | DataTypeJSONB | DataTypeVirtual | + DataTypeArray | DataTypeEnum | DataTypeRange | DataTypeReal | DataTypeDouble | DataTypeGeometry, + sequelize: Sequelize) => any; +} + +export interface ResourceOptions { + model: any; + endpoints: string[]; + actions?: string[]; + include?: Array<{ model: any } | string>; + pagination?: boolean; + search?: ResourceSearchOption; + sort?: ResourceSortOption; + reloadInstances?: boolean; + associations?: AssociationOptions; + excludeAttributes?: string[]; + readOnlyAttributes?: string[]; + updateMethod?: string; +} + +export function initialize(options?: InitializeOptions): void; +export function resource(options?: ResourceOptions): Resource; diff --git a/types/epilogue/tsconfig.json b/types/epilogue/tsconfig.json new file mode 100644 index 0000000000..593077c6bc --- /dev/null +++ b/types/epilogue/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "epilogue-tests.ts" + ] +} diff --git a/types/epilogue/tslint.json b/types/epilogue/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/epilogue/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/error-stack-parser/error-stack-parser-tests.ts b/types/error-stack-parser/error-stack-parser-tests.ts deleted file mode 100644 index c8b9198261..0000000000 --- a/types/error-stack-parser/error-stack-parser-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ - - -ErrorStackParser.parse(new Error('Boom')); diff --git a/types/error-stack-parser/index.d.ts b/types/error-stack-parser/index.d.ts deleted file mode 100644 index ad722b0f2b..0000000000 --- a/types/error-stack-parser/index.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for ErrorStackParser v1.3.3 -// Project: https://github.com/stacktracejs/error-stack-parser -// Definitions by: Eric Wendelin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module ErrorStackParser { - export interface StackFrame { - constructor(functionName: string, args: any, fileName: string, lineNumber: number, columnNumber: number, source: string): StackFrame; - - functionName?: string; - args?: any[]; - fileName?: string; - lineNumber?: number; - columnNumber?: number; - source?: string; - toString(): string; - } - - /** - * Given an Error object, extract the most information from it. - * - * @param {Error} error object - * @return {Array} of StackFrames - */ - export function parse(error: Error): StackFrame[]; -} diff --git a/types/error-stack-parser/tslint.json b/types/error-stack-parser/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/error-stack-parser/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/escape-string-regexp/index.d.ts b/types/escape-string-regexp/index.d.ts index 1ef18aedb1..7a52a312b1 100644 --- a/types/escape-string-regexp/index.d.ts +++ b/types/escape-string-regexp/index.d.ts @@ -1,10 +1,11 @@ // Type definitions for escape-string-regexp // Project: https://github.com/sindresorhus/escape-string-regexp // Definitions by: kruncher +// faergeek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function escapeStringRegexp(str: string): string; +declare const escapeStringRegexp: (str: string) => string; export = escapeStringRegexp; diff --git a/types/event-kit/README.md b/types/event-kit/README.md deleted file mode 100644 index 961b53f4a9..0000000000 --- a/types/event-kit/README.md +++ /dev/null @@ -1,38 +0,0 @@ -## Event Kit Type Definitions - -TypeScript type definitions for [event-kit](https://github.com/atom/event-kit), which is published [under the same name](https://www.npmjs.com/package/event-kit) on NPM. - -### Usage Notes - -#### Exports - -The three classes exported from this module are: [CompositeDisposable](https://github.com/atom/event-kit/blob/master/src/composite-disposable.coffee), [Disposable](https://github.com/atom/event-kit/blob/master/src/disposable.coffee), and [Emitter](https://github.com/atom/event-kit/blob/master/src/emitter.coffee). - -```ts -import { CompositeDisposable, Disposable, Emitter } from "event-kit"; -let subscriptions = new CompositeDisposable(); -``` - -#### The EventKit Namespace - -All types used by "event-kit" can be referenced from the EventKit namespace. - -```ts -function example(disposable: EventKit.DisposableLike) {} -``` - -### Exposing Private Methods and Properties - -[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within Event Kit. As an example, if we wanted to reveal the private ```getEventNames``` method within the Emitter class, then we would create a file with the following contents: - -```ts -// <>.d.ts - -declare namespace EventKit { - interface Emitter { - getEventNames(): string[]; - } -} -``` - -Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the Emitter class without TypeScript reporting errors. diff --git a/types/event-kit/event-kit-tests.ts b/types/event-kit/event-kit-tests.ts index 9507290244..8ff96d66e8 100644 --- a/types/event-kit/event-kit-tests.ts +++ b/types/event-kit/event-kit-tests.ts @@ -1,13 +1,13 @@ import { Disposable, CompositeDisposable, Emitter } from "event-kit"; declare let bool: boolean; -declare let subscription: EventKit.Disposable; -declare let subscriptions: EventKit.CompositeDisposable; -declare let emitter: EventKit.Emitter; +declare let subscription: Disposable; +declare let subscriptions: CompositeDisposable; +declare let emitter: Emitter; // NPM Usage Tests ============================================================ class User { - private readonly emitter: EventKit.Emitter; + private readonly emitter: Emitter; name: string; constructor() { @@ -81,3 +81,8 @@ subscription = emitter.preempt("test-event", value => {}); // Event Emission emitter.emit("test-event"); emitter.emit("test-event", 42); + +async function testEmitAsync() { + await emitter.emitAsync("test-event"); + await emitter.emitAsync("test-event", 42); +} diff --git a/types/event-kit/index.d.ts b/types/event-kit/index.d.ts index 467332e3d9..01b68e8f26 100644 --- a/types/event-kit/index.d.ts +++ b/types/event-kit/index.d.ts @@ -4,121 +4,119 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -declare global { - namespace EventKit { - interface DisposableLike { - dispose(): void; - } - - /** A handle to a resource that can be disposed. */ - interface Disposable extends DisposableLike { - disposed: boolean; - - /** A callback which will be called within dispose(). */ - disposalAction?(): void; - - /** Perform the disposal action, indicating that the resource associated - * with this disposable is no longer needed. - */ - dispose(): void; - } - - interface DisposableStatic { - /** Ensure that Object correctly implements the Disposable contract. */ - isDisposable(object: object): boolean; - - /** Construct a Disposable. */ - new (disposableAction?: () => void): Disposable; - } - - /** An object that aggregates multiple Disposable instances together into a - * single disposable, so they can all be disposed as a group. - */ - interface CompositeDisposable extends DisposableLike { - disposed: boolean; - - /** Dispose all disposables added to this composite disposable. - * If this object has already been disposed, this method has no effect. - */ - dispose(): void; - - // Managing Disposables - /** Add disposables to be disposed when the composite is disposed. - * If this object has already been disposed, this method has no effect. - */ - add(...disposables: DisposableLike[]): void; - - /** Remove a previously added disposable. */ - remove(disposable: DisposableLike): void; - - /** Alias to CompositeDisposable::remove. */ - delete(disposable: DisposableLike): void; - - /** Clear all disposables. They will not be disposed by the next call to - * dispose. - */ - clear(): void; - } - - /** The static side to the CompositeDisposable class. */ - interface CompositeDisposableStatic { - /** Construct an instance, optionally with one or more disposables. */ - new (...disposables: DisposableLike[]): CompositeDisposable; - } - - /** Utility class to be used when implementing event-based APIs that allows - * for handlers registered via ::on to be invoked with calls to ::emit. - */ - interface Emitter extends DisposableLike { - disposed: boolean; - - /** Clear out any existing subscribers. */ - clear(): void; - - /** Unsubscribe all handlers. */ - dispose(): boolean; - - // Event Subscription - /** Registers a handler to be invoked whenever the given event is emitted. */ - // tslint:disable-next-line:no-any - on(eventName: string, handler: (value: any) => void): Disposable; - - /** Register the given handler function to be invoked the next time an event - * with the given name is emitted via ::emit. - */ - // tslint:disable-next-line:no-any - once(eventName: string, handler: (value: any) => void): Disposable; - - /** Register the given handler function to be invoked before all other - * handlers existing at the time of subscription whenever events by the - * given name are emitted via ::emit. - */ - // tslint:disable-next-line:no-any - preempt(eventName: string, handler: (value: any) => void): Disposable; - - // Event Emission - /** Invoke handlers registered via ::on for the given event name. */ - // tslint:disable-next-line:no-any - emit(eventName: string, value?: any): void; - } - - /** The static side to the Emitter class. */ - interface EmitterStatic { - /** Construct an emitter. */ - new (): Emitter; - } - } +export interface DisposableLike { + dispose(): void; } /** A handle to a resource that can be disposed. */ -export const Disposable: EventKit.DisposableStatic; +export class Disposable implements DisposableLike { + disposed: boolean; -/** An object that aggregates multiple Disposable instances together into a + /** Ensure that Object correctly implements the Disposable contract. */ + static isDisposable(object: object): boolean; + + /** Construct a Disposable. */ + constructor(disposableAction?: () => void); + + /** A callback which will be called within dispose(). */ + disposalAction?: () => void; + + /** + * Perform the disposal action, indicating that the resource associated + * with this disposable is no longer needed. + */ + dispose(): void; +} + +/** + * An object that aggregates multiple Disposable instances together into a * single disposable, so they can all be disposed as a group. */ -export const CompositeDisposable: EventKit.CompositeDisposableStatic; +export class CompositeDisposable implements DisposableLike { + disposed: boolean; -/** Utility class to be used when implementing event-based APIs that allows + /** Construct an instance, optionally with one or more disposables. */ + constructor(...disposables: DisposableLike[]); + + /** + * Dispose all disposables added to this composite disposable. + * If this object has already been disposed, this method has no effect. + */ + dispose(): void; + + // Managing Disposables + /** + * Add disposables to be disposed when the composite is disposed. + * If this object has already been disposed, this method has no effect. + */ + add(...disposables: DisposableLike[]): void; + + /** Remove a previously added disposable. */ + remove(disposable: DisposableLike): void; + + /** Alias to CompositeDisposable::remove. */ + delete(disposable: DisposableLike): void; + + /** + * Clear all disposables. They will not be disposed by the next call to + * dispose. + */ + clear(): void; +} + +/** + * Allows you to strongly type event emissions across your codebase. Additional + * key:value pairings merged into this interface will result in emissions under + * the value of each key being templated by the type of the associated value. + */ +export interface Emissions { + // tslint:disable-next-line:no-any + [key: string]: any; +} + +/** + * Utility class to be used when implementing event-based APIs that allows * for handlers registered via ::on to be invoked with calls to ::emit. */ -export const Emitter: EventKit.EmitterStatic; +export class Emitter implements DisposableLike { + disposed: boolean; + + /** Construct an emitter. */ + constructor(); + + /** Clear out any existing subscribers. */ + clear(): void; + + /** Unsubscribe all handlers. */ + dispose(): boolean; + + // Event Subscription + /** Registers a handler to be invoked whenever the given event is emitted. */ + on(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + /** + * Register the given handler function to be invoked the next time an event + * with the given name is emitted via ::emit. + */ + once(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + /** + * Register the given handler function to be invoked before all other + * handlers existing at the time of subscription whenever events by the + * given name are emitted via ::emit. + */ + preempt(eventName: T, handler: (value?: Emissions[T]) => void): + Disposable; + + // Event Emission + /** Invoke the handlers registered via ::on for the given event name. */ + emit(eventName: T, value?: Emissions[T]): void; + + /** + * Asynchronously invoke the handlers registered via ::on for the given event name. + * @return A promise that will be fulfilled once all handlers have been invoked. + */ + emitAsync(eventName: T, value?: Emissions[T]): Promise; +} diff --git a/types/event-kit/tsconfig.json b/types/event-kit/tsconfig.json index 0097bf6ba3..0b6a81c5f8 100644 --- a/types/event-kit/tsconfig.json +++ b/types/event-kit/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +21,4 @@ "index.d.ts", "event-kit-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/event-kit/tslint.json b/types/event-kit/tslint.json index d1318cfc63..e0508241c7 100644 --- a/types/event-kit/tslint.json +++ b/types/event-kit/tslint.json @@ -1,36 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "class-name": true, "indent": [true, "spaces", 4], - "jsdoc-format": true, - "max-line-length": [true, 110], - "quotemark": [true, "double", "avoid-escape"], - "trailing-comma": [true, { - "multiline": { "objects": "always", "arrays": "always", "functions": "never" }, - "singleline": { "objects": "never", "arrays": "never", "functions": "never" } - }], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type", - "check-typecast", - "check-rest-spread", - "check-preblock" - ], - // Soon to be defaults. - "arrow-return-shorthand": [true, "multiline"], - "no-any": true, - "no-floating-promises": true, - "no-unbound-method": true, - "no-unsafe-any": true, - "number-literal-format": true, - "restrict-plus-operands": true, - "return-undefined": true, - "switch-final-break": true + "max-line-length": [true, 100], + "no-any": true } } diff --git a/types/event-stream/event-stream-tests.ts b/types/event-stream/event-stream-tests.ts index cdb541b382..38525be696 100644 --- a/types/event-stream/event-stream-tests.ts +++ b/types/event-stream/event-stream-tests.ts @@ -1,18 +1,14 @@ - - - import gulp = require("gulp"); import * as es from "event-stream"; gulp.task("es:concat", () => { - var streams = gulp.src(["*"]) + var streams = gulp.src(["*"]) .pipe(gulp.dest("build")); - + return es.concat.apply(null, streams); }); gulp.task("es:readArray ", () => { var reader = es.readArray([1, 2, 3]); - }); diff --git a/types/event-stream/tsconfig.json b/types/event-stream/tsconfig.json index 93e6b0c016..6f3624e82f 100644 --- a/types/event-stream/tsconfig.json +++ b/types/event-stream/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index 84c6939798..ee33bea59e 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for execa 0.7 +// Type definitions for execa 0.8 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil // BendingBender +// Borek Bernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,46 +11,46 @@ import { ChildProcess, ExecOptions, SpawnOptions, SpawnSyncOptions } from "child_process"; import { Stream } from 'stream'; -type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; - -interface ExecaOptions { - input: string | Buffer | Stream; - preferLocal: boolean; - stripEof: boolean; - extendEnv: boolean; - argv0: string; - localDir: string; - reject: boolean; - cleanup: boolean; - stdin: StdIOOption; - stdout: StdIOOption; - stderr: StdIOOption; -} - -type Options = SpawnOptions & ExecaOptions & ExecOptions; -type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; - -interface ExecaReturns { - cmd: string; - code: number; - failed: boolean; - killed: boolean; - signal: string | null; - stderr: string; - stdout: string; - timedOut: boolean; -} - -type ExecaError = Error & ExecaReturns; - -interface ExecaChildPromise { - catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; -} -type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; - -declare function execa(file: string, options?: Partial): ExecaChildProcess; -declare function execa(file: string, args?: string[], options?: Partial): ExecaChildProcess; +declare function execa(file: string, options?: Partial): execa.ExecaChildProcess; +declare function execa(file: string, args?: string[], options?: Partial): execa.ExecaChildProcess; declare namespace execa { + type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + + interface ExecaOptions { + input: string | Buffer | Stream; + preferLocal: boolean; + stripEof: boolean; + extendEnv: boolean; + argv0: string; + localDir: string; + reject: boolean; + cleanup: boolean; + stdin: StdIOOption; + stdout: StdIOOption; + stderr: StdIOOption; + } + + type Options = SpawnOptions & ExecaOptions & ExecOptions; + type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; + + interface ExecaReturns { + cmd: string; + code: number; + failed: boolean; + killed: boolean; + signal: string | null; + stderr: string; + stdout: string; + timedOut: boolean; + } + + type ExecaError = Error & ExecaReturns; + + interface ExecaChildPromise { + catch(onrejected?: ((reason: ExecaError) => TResult | PromiseLike) | null): Promise; + } + type ExecaChildProcess = ChildProcess & ExecaChildPromise & Promise; + function stdout(file: string, options?: Partial): Promise; function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx new file mode 100644 index 0000000000..333b9d3e3c --- /dev/null +++ b/types/expo/expo-tests.tsx @@ -0,0 +1,203 @@ +import * as React from 'react'; + +import { + Accelerometer, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem +} from 'expo'; + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', {key: 'value'}); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); +async () => { + const result = await Audio.Sound.create('uri', { + volume: 0.5, + rate: 0.6 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync('uri'); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(.6); + await Brightness.setSystemBrightnessAsync(.7); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const result = await Facebook.logInWithReadPermissionsAsync('appId'); + + if (result.type === 'success') { + result.expires; + result.token; + } +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts new file mode 100644 index 0000000000..04d500ab6b --- /dev/null +++ b/types/expo/index.d.ts @@ -0,0 +1,1481 @@ +// Type definitions for expo 23.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventSubscription } from 'fbemitter'; +import { Component, Ref } from 'react'; +import { + ViewStyle, + ViewProperties, + ColorPropType, + ImageURISource, + NativeEventEmitter, + ImageRequireSource +} from 'react-native'; + +export type URISource = ImageURISource; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type Orientation = 'portrait' | 'landscape'; +export type Axis = number; +export interface HashMap { [key: string]: any; } +export type FloatFromZeroToOne = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type Md5 = string; + +/** + * Accelerometer + */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Amplitude + */ +export namespace Amplitude { + function initialize(apiKey: string): void; + function setUserId(userId: string): void; + function setUserProperties(userProperties: HashMap): void; + function clearUserProperties(): void; + function logEvent(eventName: string): void; + function logEventWithProperties(eventName: string, properties: HashMap): void; + function setGroup(groupType: string, groupNames: HashMap): void; +} + +/** + * Asset + */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + name: string; + type: string; + hash: string; + uri: string; + localUri: string; + width?: number; + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + downloadAsync(): Promise; + + static fromModule(module: RequireSource): Asset; + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * AuthSession + */ +export namespace AuthSession { + function startAsync(options: { authUrl: string; returnUrl: string; }): Promise<{ + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }>; + function dismiss(): void; + function getRedirectUrl(): string; +} + +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: FloatFromZeroToOne; + shouldCorrectPitch?: boolean; + volume?: FloatFromZeroToOne; + isMuted?: boolean; + isLooping?: boolean; +} + +export type Source = string | RequireSource | Asset; + +export class PlaybackObject { + loadAsync(source: Source, initialStatus?: PlaybackStatusToSet, downloadFirst?: boolean): Promise; + unloadAsync(): Promise; + getStatusAsync(): Promise; + setOnPlaybackStatusUpdate(onPlaybackStatusUpdate: (status: PlaybackStatus) => void): void; + setStatusAsync(status: PlaybackStatusToSet): Promise; + playAsync(): Promise; + playFromPositionAsync(positionMillis: number): Promise; + pauseAsync(): Promise; + stopAsync(): Promise; + setPositionAsync(positionMillis: number): Promise; + setRateAsync(rate: number, shouldCorrectPitch: boolean): Promise; + setVolumeAsync(volume: number): Promise; + setIsMutedAsync(isMuted: boolean): Promise; + setIsLoopingAsync(isLooping: boolean): Promise; + setProgressUpdateIntervalAsync(progressUpdateIntervalMillis: number): Promise; +} + +export namespace Audio { + enum InterruptionModeIOS { + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + enum InterruptionModeAndroid { + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + interface AudioMode { + playsInSilentModeIOS: boolean; + allowsRecordingIOS: boolean; + interruptionModeIOS: InterruptionModeIOS; + shouldDuckAndroid: boolean; + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + class Sound extends PlaybackObject { + constructor(); + + static create( + source: Source, + initialStatus?: PlaybackStatusToSet, + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + class Recording { + constructor(); + + getStatusAsync(): Promise; + setOnRecordingStatusUpdate(onRecordingStatusUpdate: (status: RecordingStatus) => void): void; + setProgressUpdateInterval(miliss: number): void; + prepareToRecordAsync(options: Recording): Promise; + isPreparedToRecord(): boolean; + startAsync(): Promise; + pauseAsync(): Promise; + stopAndUnloadAsync(): Promise; + getURI(): string | undefined; + createNewLoadedSound(initialStatus: PlaybackStatusToSet, onPlaybackStatusUpdate: (status: PlaybackStatus) => void): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: Source | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} + +/** + * AppLoading + */ +export type AppLoadingProperties = { + startAsync: () => Promise; + onFinish: () => void; + onError?: (error: Error) => void; +} | { + startAsync: null; + onFinish: null; + onError?: null; +}; +export class AppLoading extends Component { } + +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProperties { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { } + +/** + * BlurView + */ +export interface BlurViewProps extends ViewProperties { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } + +/** + * Brightness + */ +export namespace Brightness { + function setBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; + function getBrightnessAsync(): Promise; + function getSystemBrightnessAsync(): Promise; + function setSystemBrightnessAsync(brightnessValue: FloatFromZeroToOne): Promise; +} + +/** + * Camera + */ +export interface TakePictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; +} +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} +export interface RecordOptions { + quality?: string; + maxDuration?: number; + maxFileSize?: number; + mute?: boolean; +} +export class CameraObject { + takePictureAsync(options: TakePictureOptions): Promise; + recordAsync(options: RecordOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} +export interface CameraProperties extends ViewProperties { + flashMode?: string | number; + type?: string | number; + ratio?: string; + autoFocus?: string | number | boolean; + focusDepth?: FloatFromZeroToOne; + zoom?: FloatFromZeroToOne; + whiteBalance?: string | number; + barCodeTypes?: string[]; + onCameraReady?: () => void; + onMountError?: () => void; + onBarCodeRead?: BarCodeReadCallback; + ref?: Ref; +} +export interface CameraConstants { + readonly Type: string; + readonly FlashMode: string; + readonly AutoFocus: string; + readonly WhiteBalance: string; + readonly VideoQuality: string; + readonly BarCodeType: string; +} +export class Camera extends Component { + static readonly Constants: CameraConstants; +} + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios: { + platform: string; + model: string; + userInterfaceIdiom: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + icon?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBarColor?: string; + androidStatusBar?: { + barStyle?: 'lignt-content' | 'dark-content', + backgroundColor?: string + }; + androidHideExponentNotificationInShellApp?: boolean; + scheme?: string; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme: any; + xde: boolean; + developper?: { + tool?: string, + [propName: string]: any + }; + bundleUrl?: string; + debuggerHost?: string; + mainModuleName?: string; + logUrl?: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + type Response = { + type: 'success'; + token: string; + expires: number; + } | { + type: 'cancel'; + }; + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** + * Fingerprint + */ +export namespace Fingerprint { + type FingerprintAuthenticationResult = { success: true } | { success: false, error: string }; + + function hasHardwareAsync(): Promise; + function isEnrolledAsync(): Promise; + function authenticateAsync(promptMessageIOS?: string): Promise; + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +/** + * GLView + */ +export interface GLViewProps extends ViewProperties { + onContextCreate(): void; + msaaSamples: number; +} +export class GLView extends Component { } + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** + * Gyroscope + */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + } + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: string; + const ACTION_APP_NOTIFICATION_REDACTION: string; + const ACTION_CONDITION_PROVIDER_SETTINGS: string; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: string; + const ACTION_PRINT_SETTINGS: string; + const ACTION_ADD_ACCOUNT_SETTINGS: string; + const ACTION_AIRPLANE_MODE_SETTINGS: string; + const ACTION_APN_SETTINGS: string; + const ACTION_APPLICATION_DETAILS_SETTINGS: string; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: string; + const ACTION_APPLICATION_SETTINGS: string; + const ACTION_APP_NOTIFICATION_SETTINGS: string; + const ACTION_APP_OPS_SETTINGS: string; + const ACTION_BATTERY_SAVER_SETTINGS: string; + const ACTION_BLUETOOTH_SETTINGS: string; + const ACTION_CAPTIONING_SETTINGS: string; + const ACTION_CAST_SETTINGS: string; + const ACTION_DATA_ROAMING_SETTINGS: string; + const ACTION_DATE_SETTINGS: string; + const ACTION_DEVICE_INFO_SETTINGS: string; + const ACTION_DEVICE_NAME: string; + const ACTION_DISPLAY_SETTINGS: string; + const ACTION_DREAM_SETTINGS: string; + const ACTION_HARD_KEYBOARD_SETTINGS: string; + const ACTION_HOME_SETTINGS: string; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: string; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: string; + const ACTION_INPUT_METHOD_SETTINGS: string; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: string; + const ACTION_INTERNAL_STORAGE_SETTINGS: string; + const ACTION_LOCALE_SETTINGS: string; + const ACTION_LOCATION_SOURCE_SETTINGS: string; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: string; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: string; + const ACTION_MEMORY_CARD_SETTINGS: string; + const ACTION_MONITORING_CERT_INFO: string; + const ACTION_NETWORK_OPERATOR_SETTINGS: string; + const ACTION_NFCSHARING_SETTINGS: string; + const ACTION_NFC_PAYMENT_SETTINGS: string; + const ACTION_NFC_SETTINGS: string; + const ACTION_NIGHT_DISPLAY_SETTINGS: string; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: string; + const ACTION_NOTIFICATION_SETTINGS: string; + const ACTION_PAIRING_SETTINGS: string; + const ACTION_PRIVACY_SETTINGS: string; + const ACTION_QUICK_LAUNCH_SETTINGS: string; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: string; + const ACTION_SECURITY_SETTINGS: string; + const ACTION_SETTINGS: string; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: string; + const ACTION_SHOW_INPUT_METHOD_PICKER: string; + const ACTION_SHOW_REGULATORY_INFO: string; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: string; + const ACTION_SOUND_SETTINGS: string; + const ACTION_STORAGE_MANAGER_SETTINGS: string; + const ACTION_SYNC_SETTINGS: string; + const ACTION_SYSTEM_UPDATE_SETTINGS: string; + const ACTION_TETHER_PROVISIONING_UI: string; + const ACTION_TRUSTED_CREDENTIALS_USER: string; + const ACTION_USAGE_ACCESS_SETTINGS: string; + const ACTION_USER_DICTIONARY_INSERT: string; + const ACTION_USER_DICTIONARY_SETTINGS: string; + const ACTION_USER_SETTINGS: string; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: string; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: string; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: string; + const ACTION_VOICE_INPUT_SETTINGS: string; + const ACTION_VPN_SETTINGS: string; + const ACTION_VR_LISTENER_SETTINGS: string; + const ACTION_WEBVIEW_SETTINGS: string; + const ACTION_WIFI_IP_SETTINGS: string; + const ACTION_WIFI_SETTINGS: string; + const ACTION_WIRELESS_SETTINGS: string; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: string; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: string; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: string; + const ACTION_ZEN_MODE_SETTINGS: string; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start: [number, number]; + end: [number, number]; + locations: number[]; +} + +export class LinearGradient extends Component { } + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExponentPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'remoteNotifications' | 'location' | + 'camera' | 'contacts' | 'audioRecording'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + const CAMERA: string; + const CAMERA_ROLL: string; + const AUDIO_RECORDING: string; + const LOCATION: string; + const REMOTE_NOTIFICATIONS: string; + const NOTIFICATIONS: string; + const CONTACTS: string; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: Component): Component; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientation { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + const Orientation: Orientation; + function allow(orientation: string): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number; + stroke?: string; + strokeWidth?: number; + strokeOpacity?: number; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + x?: Axis; + y?: Axis; + rotate?: number; + scale?: number; + origin?: number | string; + originX?: number; + originY?: number; +} + +export class Svg extends Component<{ width: number, heigth: number }> { } +export class Rect extends Component { } + +export interface CircleProps extends SvgCommonProps { + cx: Axis; + cy: Axis; +} +export class Circle extends Component { } + +export interface EllipseProps extends CircleProps { + rx: Axis; + ry: Axis; +} +export class Ellipse extends Component { } + +export interface LineProps extends SvgCommonProps { + x1: Axis; + y1: Axis; + x2: Axis; + y2: Axis; +} +export class Line extends Component { } + +export interface PolyProps extends SvgCommonProps { + points: string; +} +export class Polygon extends Component { } +export class Polyline extends Component { } + +export interface PathLine extends SvgCommonProps { + d: string; +} +export class Path extends Component { } + +export interface TextProps extends SvgCommonProps { + textAnchor: string; +} +export class Text extends Component { } +export class G extends Component { } +export class Use extends Component<{ href: string, x: number, y: number }> { } +export class Symbol extends Component<{ viewbox: string, widt: number, height: number }> { } +export class Defs extends Component { } +export class RadialGradient extends Component { } + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** + * Util + */ +export namespace Util { + function getCurrentDeviceCountryAsync(): Promise; + function getCurrentLocaleAsync(): Promise; + function getCurrentTimeZoneAsync(): Promise; + function reload(): void; + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; // Android only +} + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} diff --git a/types/expo/tsconfig.json b/types/expo/tsconfig.json new file mode 100644 index 0000000000..5d0f560837 --- /dev/null +++ b/types/expo/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/tslint.json b/types/expo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-brute-memcached/index.d.ts b/types/express-brute-memcached/index.d.ts index dd7f2d2573..ca8cccda4d 100644 --- a/types/express-brute-memcached/index.d.ts +++ b/types/express-brute-memcached/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/AdamPflug/express-brute-memcached // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /** * @summary Memcached options. diff --git a/types/express-cluster/express-cluster-tests.ts b/types/express-cluster/express-cluster-tests.ts new file mode 100644 index 0000000000..4eb096ffd6 --- /dev/null +++ b/types/express-cluster/express-cluster-tests.ts @@ -0,0 +1,6 @@ +import cluster = require('express-cluster'); + +() => { + cluster(worker => {}, {count: 5}); + cluster({count: 5}, worker => {}); +}; diff --git a/types/express-cluster/index.d.ts b/types/express-cluster/index.d.ts new file mode 100644 index 0000000000..bee845d02e --- /dev/null +++ b/types/express-cluster/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for express-cluster 0.0 +// Project: https://github.com/Flipboard/express-cluster +// Definitions by: Miloslav Nenadál +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import cluster = require('cluster'); + +interface Config { + count?: number; + respawn?: boolean; + verbose?: boolean; + workerListener?(): void; + outputStream?: NodeJS.WritableStream; +} + +type WorkerFunction = (worker: cluster.Worker) => void; + +interface Cluster { + (fn: WorkerFunction, config: Config): void; + (config: Config, fn: WorkerFunction): void; +} + +declare const c: Cluster; +export = c; diff --git a/types/express-cluster/tsconfig.json b/types/express-cluster/tsconfig.json new file mode 100644 index 0000000000..5d27d3ec2e --- /dev/null +++ b/types/express-cluster/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-cluster-tests.ts" + ] +} \ No newline at end of file diff --git a/types/express-cluster/tslint.json b/types/express-cluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-cluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-ejs-layouts/express-ejs-layouts-tests.ts b/types/express-ejs-layouts/express-ejs-layouts-tests.ts new file mode 100644 index 0000000000..9d77105a9d --- /dev/null +++ b/types/express-ejs-layouts/express-ejs-layouts-tests.ts @@ -0,0 +1,7 @@ +import * as express from 'express'; +import * as expressEjsLayouts from 'express-ejs-layouts'; + +function expressRequestHandlerTest() { + const app = express() + .use(expressEjsLayouts()); +} diff --git a/types/express-ejs-layouts/index.d.ts b/types/express-ejs-layouts/index.d.ts new file mode 100644 index 0000000000..958cd158e2 --- /dev/null +++ b/types/express-ejs-layouts/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for express-ejs-layouts 2.3 +// Project: https://github.com/Soarez/express-ejs-layouts +// Definitions by: Erik Mavrinac +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { RequestHandler } from 'express'; + +declare function expressEjsLayouts(): RequestHandler; + +declare namespace expressEjsLayouts { +} + +export = expressEjsLayouts; diff --git a/types/express-ejs-layouts/tsconfig.json b/types/express-ejs-layouts/tsconfig.json new file mode 100644 index 0000000000..7ade9f8819 --- /dev/null +++ b/types/express-ejs-layouts/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-ejs-layouts-tests.ts" + ] +} diff --git a/types/express-ejs-layouts/tslint.json b/types/express-ejs-layouts/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/express-ejs-layouts/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/express-flash-2/index.d.ts b/types/express-flash-2/index.d.ts index 06c1bc6591..42ace71f78 100644 --- a/types/express-flash-2/index.d.ts +++ b/types/express-flash-2/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jack2gs/express-flash-2 // Definitions by: Matheus Salmi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import express = require('express'); diff --git a/types/express-formidable/express-formidable-tests.ts b/types/express-formidable/express-formidable-tests.ts index 91f9e34519..f508f0be95 100644 --- a/types/express-formidable/express-formidable-tests.ts +++ b/types/express-formidable/express-formidable-tests.ts @@ -3,7 +3,12 @@ import expform = require("express-formidable"); const app = express(); -app.use("/form1", expform()); +app.use("/form1", expform(), (req, res, next) => { + console.log(req.fields); + console.log(req.files); + next(); +}); + app.use("/form2", expform({ encoding: "utf-8", uploadDir: "./uploads", diff --git a/types/express-formidable/index.d.ts b/types/express-formidable/index.d.ts index 57342521c2..75a34d0350 100644 --- a/types/express-formidable/index.d.ts +++ b/types/express-formidable/index.d.ts @@ -1,9 +1,21 @@ -// Type definitions for express-formidable 1.0.0 +// Type definitions for express-formidable 1.0 // Project: https://github.com/noraesae/express-formidable -// Definitions by: Torkild Dyvik Olsen +// Definitions by: Torkild Dyvik Olsen , Evan Shortiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -import { RequestHandler } from "express"; +import * as express from "express"; +import { Fields, Files } from "formidable"; + +// Extend the express request object with attached formidable files and fields +declare global { + namespace Express { + interface Request { + fields?: Fields; + files?: Files; + } + } +} interface ExpressFormidableOptions { encoding?: string; @@ -16,6 +28,8 @@ interface ExpressFormidableOptions { multiples?: boolean; } -declare function ExpressFormidable(options?: ExpressFormidableOptions): RequestHandler; +declare function ExpressFormidable(options?: ExpressFormidableOptions): express.RequestHandler; + +declare namespace ExpressFormidable {} export = ExpressFormidable; diff --git a/types/express-formidable/tsconfig.json b/types/express-formidable/tsconfig.json index 9deeebd96f..45a7b6c12b 100644 --- a/types/express-formidable/tsconfig.json +++ b/types/express-formidable/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "express-formidable-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/express-formidable/tslint.json b/types/express-formidable/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/express-formidable/tslint.json +++ b/types/express-formidable/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/express-handlebars/index.d.ts b/types/express-handlebars/index.d.ts index 3f11234d46..2c718e08b8 100644 --- a/types/express-handlebars/index.d.ts +++ b/types/express-handlebars/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ericf/express-handlebars // Definitions by: Sam Saint-Pettersen , Igor Dultsev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 interface PartialTemplateOptions { cache?: boolean; diff --git a/types/express-less/index.d.ts b/types/express-less/index.d.ts index c414e759f7..4a4accaa51 100644 --- a/types/express-less/index.d.ts +++ b/types/express-less/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.npmjs.com/package/express-less // Definitions by: xyb // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/express-oauth-server/express-oauth-server-tests.ts b/types/express-oauth-server/express-oauth-server-tests.ts new file mode 100644 index 0000000000..436763b9b8 --- /dev/null +++ b/types/express-oauth-server/express-oauth-server-tests.ts @@ -0,0 +1,83 @@ +import ExpressOAuthServer = require("express-oauth-server"); +import * as OAuth2Server from "oauth2-server"; +import * as express from "express"; + +const oauth2Model: OAuth2Server.AuthorizationCodeModel = { + getClient: async (clientId: string, clientSecret: string): Promise => { + return undefined; + }, + saveToken: async (token: OAuth2Server.Token, client: OAuth2Server.Client, user: OAuth2Server.User): Promise => { + return token; + }, + getAccessToken: async (accessToken: string): Promise => { + return { + accessToken, + client: {id: "testClient", grants: ["access_token"]}, + user: {id: "testUser"} + }; + }, + verifyScope: async (token: OAuth2Server.Token, scope: string): Promise => { + return true; + }, + getAuthorizationCode: async (authorizationCode: string): Promise => { + return { + authorizationCode, + expiresAt: new Date(), + redirectUri: "www.test.com", + client: {id: "testClient", grants: ["access_token"]}, + user: {id: "testUser"} + }; + }, + saveAuthorizationCode: async (code: OAuth2Server.AuthorizationCode, client: OAuth2Server.Client, user: OAuth2Server.User): Promise => { + return code; + }, + revokeAuthorizationCode: async (code: OAuth2Server.AuthorizationCode): Promise => { + return true; + } +}; + +const serverOptions: OAuth2Server.ServerOptions = { + model: oauth2Model, +}; +const expressOAuthServer: ExpressOAuthServer = new ExpressOAuthServer(serverOptions); + +let oAuthServer: OAuth2Server; +let resultingTokenMiddleware: ( + request: express.Request, + response: express.Response, + next: express.NextFunction, +) => Promise; +let resultingAuthorizationCodeMiddleware: ( + request: express.Request, + response: express.Response, + next: express.NextFunction, +) => Promise; + +oAuthServer = expressOAuthServer.server; +resultingTokenMiddleware = expressOAuthServer.authenticate(); +resultingTokenMiddleware = expressOAuthServer.token(); +resultingAuthorizationCodeMiddleware = expressOAuthServer.authorize(); + +// Real-life example + +const expressApp = express(); + +expressApp.all( + "/path", + expressOAuthServer.authenticate(), + (req: express.Request, res: express.Response, next: express.NextFunction) => { + res.json({message: "Secure data"}); + }, +); + +expressApp.get( + "/profile", + expressOAuthServer.authenticate({scope: "profile"}), + (req: express.Request & {user?: OAuth2Server.Token}, res: express.Response, next: express.NextFunction) => { + res.json({ + profile: req.user + }); + }, +); + +expressApp.listen(1234); diff --git a/types/express-oauth-server/index.d.ts b/types/express-oauth-server/index.d.ts new file mode 100644 index 0000000000..0a5a1162ea --- /dev/null +++ b/types/express-oauth-server/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for express-oauth-server 2.0 +// Project: https://github.com/oauthjs/express-oauth-server#readme +// Definitions by: Arne Schubert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as express from 'express'; +import * as OAuth2Server from 'oauth2-server'; + +declare class ExpressOAuthServer { + server: OAuth2Server; + + constructor(options: OAuth2Server.ServerOptions); + + authenticate(options?: OAuth2Server.AuthenticateOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; + + authorize(options?: OAuth2Server.AuthorizeOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; + + token(options?: OAuth2Server.TokenOptions): ( + request: express.Request, + response: express.Response, + next: express.NextFunction, + ) => Promise; +} + +export = ExpressOAuthServer; diff --git a/types/express-oauth-server/tsconfig.json b/types/express-oauth-server/tsconfig.json new file mode 100644 index 0000000000..197ec65f00 --- /dev/null +++ b/types/express-oauth-server/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-oauth-server-tests.ts" + ] +} diff --git a/types/express-oauth-server/tslint.json b/types/express-oauth-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-oauth-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-openapi/index.d.ts b/types/express-openapi/index.d.ts index cfb38fee5c..a6ac5bda65 100644 --- a/types/express-openapi/index.d.ts +++ b/types/express-openapi/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kogosoftwarellc/express-openapi // Definitions by: TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /* =================== USAGE =================== import express = require('express'); diff --git a/types/express-partials/index.d.ts b/types/express-partials/index.d.ts index fb043b1307..6a604a2996 100644 --- a/types/express-partials/index.d.ts +++ b/types/express-partials/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/publicclass/express-partials // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/express-rate-limit/index.d.ts b/types/express-rate-limit/index.d.ts index cb0d16ec61..a46e0ed6cc 100644 --- a/types/express-rate-limit/index.d.ts +++ b/types/express-rate-limit/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nfriedly/express-rate-limit // Definitions by: Cyril Schumacher , makepost // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 import express = require("express"); diff --git a/types/express-route-fs/index.d.ts b/types/express-route-fs/index.d.ts index a16f7dd171..ddc6e90e46 100644 --- a/types/express-route-fs/index.d.ts +++ b/types/express-route-fs/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kripod/express-route-fs // Definitions by: Kristóf Poduszló // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /** diff --git a/types/express-serve-static-core/express-serve-static-core-tests.ts b/types/express-serve-static-core/express-serve-static-core-tests.ts index 5803337a65..4c2f0919c2 100644 --- a/types/express-serve-static-core/express-serve-static-core-tests.ts +++ b/types/express-serve-static-core/express-serve-static-core-tests.ts @@ -1,5 +1,3 @@ - - import * as express from 'express-serve-static-core'; -// null test file - everything should be tested from express.d.ts and serve-static.d.ts \ No newline at end of file +// null test file - everything should be tested from express.d.ts and serve-static.d.ts diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 6d8b771e58..2f8d862b14 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -2,90 +2,85 @@ // Project: http://expressjs.com // Definitions by: Boris Yankov , Michał Lytek , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + // This extracts the core definitions from express to prevent a circular dependency between express and serve-static /// declare global { namespace Express { - // These open interfaces may be extended in an application-specific manner via declaration merging. // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } + interface Request { } + interface Response { } + interface Application { } } } import * as http from "http"; -interface NextFunction { +export interface NextFunction { + // tslint:disable-next-line callable-types (In ts2.1 it thinks the type alias has no call signatures) (err?: any): void; } -interface RequestHandler { +export interface RequestHandler { + // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2 (req: Request, res: Response, next: NextFunction): any; } -interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; -} +export type ErrorRequestHandler = (err: any, req: Request, res: Response, next: NextFunction) => any; -type PathParams = string | RegExp | (string | RegExp)[]; +export type PathParams = string | RegExp | Array; -type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; +export type RequestHandlerParams = RequestHandler | ErrorRequestHandler | Array; -interface IRouterMatcher { +export interface IRouterMatcher { (path: PathParams, ...handlers: RequestHandler[]): T; (path: PathParams, ...handlers: RequestHandlerParams[]): T; } -interface IRouterHandler { +export interface IRouterHandler { (...handlers: RequestHandler[]): T; (...handlers: RequestHandlerParams[]): T; } -interface IRouter extends RequestHandler { +export interface IRouter extends RequestHandler { /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + */ param(name: string, handler: RequestParamHandler): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API // deprecated since express 4.11.0 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + */ all: IRouterMatcher; get: IRouterMatcher; post: IRouterMatcher; @@ -124,7 +119,7 @@ interface IRouter extends RequestHandler { stack: any[]; } -interface IRoute { +export interface IRoute { path: string; stack: any; all: IRouterHandler; @@ -151,12 +146,12 @@ interface IRoute { subscribe: IRouterHandler; trace: IRouterHandler; unlock: IRouterHandler; - unsubscribe: IRouterHandler + unsubscribe: IRouterHandler; } export interface Router extends IRouter { } -interface CookieOptions { +export interface CookieOptions { maxAge?: number; signed?: boolean; expires?: Date | boolean; @@ -168,40 +163,32 @@ interface CookieOptions { sameSite?: boolean | string; } -interface ByteRange { start: number; end: number; } +export interface ByteRange { start: number; end: number; } -interface RequestRanges extends Array { type: string; } +export interface RequestRanges extends Array { type: string; } -interface Errback { (err: Error): void; } - -interface Request< - Body = any, - Query = any, - Params = any, - Cookies = any -> extends http.IncomingMessage, Express.Request { +export type Errback = (err: Error) => void; +export interface Request extends http.IncomingMessage, Express.Request { /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + */ get(name: "set-cookie"): string[] | undefined; get(name: string): string | undefined; @@ -209,255 +196,239 @@ interface Request< header(name: string): string | undefined; /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ accepts(): string[]; accepts(type: string): string | false; accepts(type: string[]): string | false; accepts(...type: string[]): string | false; /** - * Returns the first accepted charset of the specified character sets, - * based on the request's Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ + * Returns the first accepted charset of the specified character sets, + * based on the request's Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ acceptsCharsets(): string[]; acceptsCharsets(charset: string): string | false; acceptsCharsets(charset: string[]): string | false; acceptsCharsets(...charset: string[]): string | false; /** - * Returns the first accepted encoding of the specified encodings, - * based on the request's Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ + * Returns the first accepted encoding of the specified encodings, + * based on the request's Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ acceptsEncodings(): string[]; acceptsEncodings(encoding: string): string | false; acceptsEncodings(encoding: string[]): string | false; acceptsEncodings(...encoding: string[]): string | false; /** - * Returns the first accepted language of the specified languages, - * based on the request's Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ + * Returns the first accepted language of the specified languages, + * based on the request's Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + */ acceptsLanguages(): string[]; acceptsLanguages(lang: string): string | false; acceptsLanguages(lang: string[]): string | false; acceptsLanguages(...lang: string[]): string | false; /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + */ range(size: number): RequestRanges|null|-1|-2; /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ accepted: MediaType[]; /** - * @deprecated Use either req.params, req.body or req.query, as applicable. - * - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ + * @deprecated Use either req.params, req.body or req.query, as applicable. + * + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + */ param(name: string, defaultValue?: any): string; /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + */ is(type: string): string | false; /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ protocol: string; /** - * Short-hand for: - * - * req.protocol == 'https' - */ + * Short-hand for: + * + * req.protocol == 'https' + */ secure: boolean; /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ ip: string; /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ ips: string[]; /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ subdomains: string[]; /** - * Short-hand for `url.parse(req.url).pathname`. - */ + * Short-hand for `url.parse(req.url).pathname`. + */ path: string; /** - * Parse the "Host" header field hostname. - */ + * Parse the "Host" header field hostname. + */ hostname: string; /** - * @deprecated Use hostname instead. - */ + * @deprecated Use hostname instead. + */ host: string; /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ fresh: boolean; /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ stale: boolean; /** - * Check if the request was an _XMLHttpRequest_. - */ + * Check if the request was an _XMLHttpRequest_. + */ xhr: boolean; //body: { username: string; password: string; remember: boolean; title: string; }; - body: Body; + body: any; //cookies: { string; remember: boolean; }; - cookies: Cookies; + cookies: any; method: string; - params: Params; + params: any; - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ + /** Clear cookie `name`. */ clearCookie(name: string, options?: any): Response; - query: Query; + query: any; route: any; @@ -472,275 +443,259 @@ interface Request< app: Application; } -interface MediaType { +export interface MediaType { value: string; quality: number; type: string; subtype: string; } -interface Send { - (body?: any): Response; -} +export type Send = (body?: any) => Response; -interface Response extends http.ServerResponse, Express.Response { +export interface Response extends http.ServerResponse, Express.Response { /** - * Set status `code`. - * - * @param code - */ + * Set status `code`. + */ status(code: number): Response; /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + */ sendStatus(code: number): Response; /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + */ links(links: any): Response; /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ send: Send; /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ json: Send; /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ jsonp: Send; /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ sendFile(path: string): void; sendFile(path: string, options: any): void; sendFile(path: string, fn: Errback): void; sendFile(path: string, options: any, fn: Errback): void; /** - * @deprecated Use sendFile instead. - */ + * @deprecated Use sendFile instead. + */ sendfile(path: string): void; /** - * @deprecated Use sendFile instead. - */ + * @deprecated Use sendFile instead. + */ sendfile(path: string, options: any): void; /** - * @deprecated Use sendFile instead. - */ + * @deprecated Use sendFile instead. + */ sendfile(path: string, fn: Errback): void; /** - * @deprecated Use sendFile instead. - */ + * @deprecated Use sendFile instead. + */ sendfile(path: string, options: any, fn: Errback): void; /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ download(path: string): void; download(path: string, filename: string): void; download(path: string, fn: Errback): void; download(path: string, filename: string, fn: Errback): void; /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ contentType(type: string): Response; /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + */ type(type: string): Response; /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + */ format(obj: any): Response; /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + */ attachment(filename?: string): Response; /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ set(field: any): Response; set(field: string, value?: string): Response; @@ -750,102 +705,91 @@ interface Response extends http.ServerResponse, Express.Response { // Property indicating if HTTP headers has been sent for the response. headersSent: boolean; - /** - * Get value for header `field`. - * - * @param field - */ + /** Get value for header `field`. */ get(field: string): string; - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ + /** Clear cookie `name`. */ clearCookie(name: string, options?: any): Response; /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ cookie(name: string, val: string, options: CookieOptions): Response; cookie(name: string, val: any, options: CookieOptions): Response; cookie(name: string, val: any): Response; /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + */ location(url: string): Response; /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ redirect(url: string): void; redirect(status: number, url: string): void; redirect(url: string, status: number): void; /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; render(view: string, callback?: (err: Error, html: string) => void): void; @@ -865,183 +809,163 @@ interface Response extends http.ServerResponse, Express.Response { app: Application; } -interface Handler extends RequestHandler { } +export interface Handler extends RequestHandler { } -interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, value: any, name: string): any; -} +export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any; -type ApplicationRequestHandler = IRouterHandler & IRouterMatcher & { - (...handlers: RequestHandlerParams[]): T; -}; +export type ApplicationRequestHandler = IRouterHandler & IRouterMatcher & ((...handlers: RequestHandlerParams[]) => T); -interface Application extends IRouter, Express.Application { +export interface Application extends IRouter, Express.Application { /** * Express instance itself is a request handler, which could be invoked without * third argument. */ - (req: Request, res: Response): any; + (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any; /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ init(): void; /** - * Initialize application configuration. - */ + * Initialize application configuration. + */ defaultConfiguration(): void; /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ engine(ext: string, fn: Function): Application; /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + */ set(setting: string, val: any): Application; - get: { (name: string): any; } & IRouterMatcher; + get: ((name: string) => any) & IRouterMatcher; param(name: string | string[], handler: RequestParamHandler): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ path(): string; /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ enabled(setting: string): boolean; /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + */ disabled(setting: string): boolean; - /** - * Enable `setting`. - * - * @param setting - */ + /** Enable `setting`. */ enable(setting: string): Application; - /** - * Disable `setting`. - * - * @param setting - */ + /** Disable `setting`. */ disable(setting: string): Application; /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + */ configure(fn: Function): Application; configure(env0: string, fn: Function): Application; configure(env0: string, env1: string, fn: Function): Application; @@ -1050,41 +974,36 @@ interface Application extends IRouter, Express.Application { configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + */ render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; render(name: string, callback: (err: Error, html: string) => void): void; - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; listen(port: number, hostname: string, callback?: Function): http.Server; listen(port: number, callback?: Function): http.Server; @@ -1102,13 +1021,13 @@ interface Application extends IRouter, Express.Application { locals: any; /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ routes: any; /** @@ -1119,8 +1038,7 @@ interface Application extends IRouter, Express.Application { use: ApplicationRequestHandler; } -interface Express extends Application { +export interface Express extends Application { request: Request; - response: Response; } diff --git a/types/express-serve-static-core/tslint.json b/types/express-serve-static-core/tslint.json index a41bf5d19a..9b8c6a0c20 100644 --- a/types/express-serve-static-core/tslint.json +++ b/types/express-serve-static-core/tslint.json @@ -1,79 +1,11 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, + // TODOs "ban-types": false, - "callable-types": false, "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "unified-signatures": false } -} + } diff --git a/types/express-session/index.d.ts b/types/express-session/index.d.ts index 8c5faa7873..13ce6ab8b2 100644 --- a/types/express-session/index.d.ts +++ b/types/express-session/index.d.ts @@ -1,9 +1,8 @@ // Type definitions for express-session 1.15 // Project: https://www.npmjs.org/package/express-session -// Definitions by: Hiroki Horiuchi +// Definitions by: Hiroki Horiuchi , Jacob Bogers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Definitions by: Jacob Bogers diff --git a/types/express-useragent/index.d.ts b/types/express-useragent/index.d.ts index a8d55b113b..d6f47aa206 100644 --- a/types/express-useragent/index.d.ts +++ b/types/express-useragent/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.npmjs.org/package/express-useragent // Definitions by: Isman Usoh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/express/express-tests.ts b/types/express/express-tests.ts index d578a24886..0c1081b49b 100644 --- a/types/express/express-tests.ts +++ b/types/express/express-tests.ts @@ -17,10 +17,9 @@ namespace express_tests { next(); }); - app.use((err: any, req: express.Request<{ hello: string; }>, res: express.Response, next: express.NextFunction) => { - console.log(req.body.hello); - console.error(err); - next(err); + app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { + console.error(err); + next(err); }); app.get('/', (req, res) => { diff --git a/types/express/index.d.ts b/types/express/index.d.ts index 66bf4180c8..59f60e92df 100644 --- a/types/express/index.d.ts +++ b/types/express/index.d.ts @@ -2,7 +2,7 @@ // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 /* =================== USAGE =================== @@ -76,12 +76,7 @@ declare namespace e { interface IRouterMatcher extends core.IRouterMatcher { } interface MediaType extends core.MediaType { } interface NextFunction extends core.NextFunction { } - interface Request< - Body = any, - Query = any, - Params = any, - Cookies = any - > extends core.Request { } + interface Request extends core.Request { } interface RequestHandler extends core.RequestHandler { } interface RequestParamHandler extends core.RequestParamHandler { } export interface Response extends core.Response { } diff --git a/types/faker/faker-tests.ts b/types/faker/faker-tests.ts index 5fb6a53746..df671dcf6a 100644 --- a/types/faker/faker-tests.ts +++ b/types/faker/faker-tests.ts @@ -1,5 +1,3 @@ - - let resultStr: string; let resultBool: boolean; let resultNum: number; @@ -17,7 +15,7 @@ resultStr = faker.address.cityPrefix(); resultStr = faker.address.citySuffix(); resultStr = faker.address.streetName(); resultStr = faker.address.streetAddress(); -resultStr = faker.address.streetAddress(false);; +resultStr = faker.address.streetAddress(false); resultStr = faker.address.streetSuffix(); resultStr = faker.address.streetPrefix(); resultStr = faker.address.secondaryAddress(); @@ -63,6 +61,8 @@ resultDate = faker.date.between('foo', 'bar'); resultDate = faker.date.between(new Date(), new Date()); resultDate = faker.date.recent(); resultDate = faker.date.recent(100); +resultDate = faker.date.soon(); +resultDate = faker.date.soon(30); resultStr = faker.date.month(); resultStr = faker.date.month({ abbr: true, @@ -86,6 +86,9 @@ resultStr = faker.finance.currencyCode(); resultStr = faker.finance.currencyName(); resultStr = faker.finance.currencySymbol(); resultStr = faker.finance.bitcoinAddress(); +resultStr = faker.finance.ethereumAddress(); +resultStr = faker.finance.iban(); +resultStr = faker.finance.iban(true); resultStr = faker.finance.bic(); resultStr = faker.hacker.abbreviation(); @@ -96,7 +99,7 @@ resultStr = faker.hacker.ingverb(); resultStr = faker.hacker.phrase(); resultStr = faker.helpers.randomize(); -resultNum = faker.helpers.randomize([1,2,3,4]); +resultNum = faker.helpers.randomize([1, 2, 3, 4]); resultStr = faker.helpers.randomize(['foo', 'bar', 'quux']); resultStr = faker.helpers.slugify('foo bar quux'); resultStr = faker.helpers.replaceSymbolWithNumber('foo# bar#'); @@ -167,7 +170,6 @@ resultStr = faker.name.jobType(); resultStr = faker.phone.phoneNumber(); resultStr = faker.phone.phoneNumber('#'); resultStr = faker.phone.phoneNumberFormat(); -// https://github.com/Marak/faker.js/blob/master/lib/phone_number.js#L9-L13 resultStr = faker.phone.phoneNumberFormat(0); resultStr = faker.phone.phoneFormats(); @@ -179,27 +181,104 @@ resultNum = faker.random.number({ precision: 0 }); resultStr = faker.random.arrayElement(); -resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']) +resultStr = faker.random.arrayElement(['foo', 'bar', 'quux']); resultStr = faker.random.objectElement(); resultStr = faker.random.objectElement({foo: 'bar', field: 'foo'}); resultStr = faker.random.uuid(); resultBool = faker.random.boolean(); resultStr = faker.random.word(); +resultStr = faker.random.word("noun"); resultStr = faker.random.words(); resultStr = faker.random.words(0); resultStr = faker.random.image(); resultStr = faker.random.locale(); resultStr = faker.random.alphaNumeric(); resultStr = faker.random.alphaNumeric(0); +resultStr = faker.random.hexaDecimal(); +resultStr = faker.random.hexaDecimal(3); -resultStr = faker.system.fileName( "foo", "bar" ); -resultStr = faker.system.commonFileName( "foo", "bar" ); +resultStr = faker.system.fileName("foo", "bar"); +resultStr = faker.system.commonFileName("foo", "bar"); resultStr = faker.system.mimeType(); resultStr = faker.system.commonFileType(); resultStr = faker.system.commonFileExt(); resultStr = faker.system.fileType(); -resultStr = faker.system.fileExt( "foo" ); +resultStr = faker.system.fileExt("foo"); +resultStr = faker.system.directoryPath(); +resultStr = faker.system.filePath(); resultStr = faker.system.semver(); +import fakerAz = require('faker/locale/az'); +resultStr = fakerAz.name.firstName(); +import fakerCz = require('faker/locale/cz'); +resultStr = fakerCz.name.firstName(); +import fakerDe = require('faker/locale/de'); +resultStr = fakerDe.name.firstName(); +import fakerDeAT = require('faker/locale/de_AT'); +resultStr = fakerDeAT.name.firstName(); +import fakerdeCH = require('faker/locale/de_CH'); +resultStr = fakerdeCH.name.firstName(); import fakerEn = require('faker/locale/en'); -resultStr = faker.name.firstName(); +resultStr = fakerEn.name.firstName(); +import fakerEnAU = require('faker/locale/en_AU'); +resultStr = fakerEnAU.name.firstName(); +import fakerEnBORK = require('faker/locale/en_BORK'); +resultStr = fakerEnBORK.name.firstName(); +import fakerEnCA = require('faker/locale/en_CA'); +resultStr = fakerEnCA.name.firstName(); +import fakerEnGB = require('faker/locale/en_GB'); +resultStr = fakerEnGB.name.firstName(); +import fakerEnIE = require('faker/locale/en_IE'); +resultStr = fakerEnIE.name.firstName(); +import fakerEnIND = require('faker/locale/en_IND'); +resultStr = fakerEnIND.name.firstName(); +import fakerEnUS = require('faker/locale/en_US'); +resultStr = fakerEnUS.name.firstName(); +import fakerEnAuOcker = require('faker/locale/en_au_ocker'); +resultStr = fakerEnAuOcker.name.firstName(); +import fakerEs = require('faker/locale/es'); +resultStr = fakerEs.name.firstName(); +import fakerEsMX = require('faker/locale/es_MX'); +resultStr = fakerEsMX.name.firstName(); +import fakerFa = require('faker/locale/fa'); +resultStr = fakerFa.name.firstName(); +import fakerFr = require('faker/locale/fr'); +resultStr = fakerFr.name.firstName(); +import fakerFrCA = require('faker/locale/fr_CA'); +resultStr = fakerFrCA.name.firstName(); +import fakerGe = require('faker/locale/ge'); +resultStr = fakerGe.name.firstName(); +import fakerIdID = require('faker/locale/id_ID'); +resultStr = fakerIdID.name.firstName(); +import fakerIt = require('faker/locale/it'); +resultStr = fakerIt.name.firstName(); +import fakerJa = require('faker/locale/ja'); +resultStr = fakerJa.name.firstName(); +import fakerKo = require('faker/locale/ko'); +resultStr = fakerKo.name.firstName(); +import fakerNbNO = require('faker/locale/nb_NO'); +resultStr = fakerNbNO.name.firstName(); +import fakerNep = require('faker/locale/nep'); +resultStr = fakerNep.name.firstName(); +import fakerNl = require('faker/locale/nl'); +resultStr = fakerNl.name.firstName(); +import fakerPl = require('faker/locale/pl'); +resultStr = fakerPl.name.firstName(); +import fakerPtBR = require('faker/locale/pt_BR'); +resultStr = fakerPtBR.name.firstName(); +import fakerRu = require('faker/locale/ru'); +resultStr = fakerRu.name.firstName(); +import fakerSk = require('faker/locale/sk'); +resultStr = fakerSk.name.firstName(); +import fakerSv = require('faker/locale/sv'); +resultStr = fakerSv.name.firstName(); +import fakerTr = require('faker/locale/tr'); +resultStr = fakerTr.name.firstName(); +import fakerUk = require('faker/locale/uk'); +resultStr = fakerUk.name.firstName(); +import fakerVi = require('faker/locale/vi'); +resultStr = fakerVi.name.firstName(); +import fakerZhCN = require('faker/locale/zh_CN'); +resultStr = fakerZhCN.name.firstName(); +import fakerZhTW = require('faker/locale/zh_TW'); +resultStr = fakerZhTW.name.firstName(); diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index eda944d515..552e7d3eeb 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -1,9 +1,12 @@ -// Type definitions for faker v4.1.0 +// Type definitions for faker 4.1 // Project: http://marak.com/faker.js/ -// Definitions by: Ben Swartz , Bas Pennings , Yuki Kokubun +// Definitions by: Ben Swartz , +// Bas Pennings , +// Yuki Kokubun , +// Matt Bishop // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var fakerStatic: Faker.FakerStatic; +declare const fakerStatic: Faker.FakerStatic; declare namespace Faker { interface FakerStatic { @@ -64,6 +67,7 @@ declare namespace Faker { future(years?: number, refDate?: string|Date): Date; between(from: string|number|Date, to: string|Date): Date; recent(days?: number): Date; + soon(days?: number): Date; month(options?: { abbr?: boolean, context?: boolean }): string; weekday(options?: { abbr?: boolean, context?: boolean }): string; }; @@ -74,12 +78,14 @@ declare namespace Faker { account(length?: number): string; accountName(): string; mask(length?: number, parens?: boolean, elipsis?: boolean): string; - amount(min?:number, max?: number, dec?: number, symbol?: string): string; + amount(min?: number, max?: number, dec?: number, symbol?: string): string; transactionType(): string; currencyCode(): string; currencyName(): string; currencySymbol(): string; bitcoinAddress(): string; + ethereumAddress(): string; + iban(formatted?: boolean): string bic(): string }; @@ -101,13 +107,12 @@ declare namespace Faker { shuffle(o: T[]): T[]; shuffle(): string[]; mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string; - createCard(): Faker.Card; - contextualCard(): Faker.ContextualCard; - userCard(): Faker.UserCard; - createTransaction(): Faker.Transaction; + createCard(): Card; + contextualCard(): ContextualCard; + userCard(): UserCard; + createTransaction(): Transaction; }; - image: { image(): string; avatar(): string; @@ -186,11 +191,12 @@ declare namespace Faker { objectElement(object?: { [key: string]: T }, field?: any): T; uuid(): string; boolean(): boolean; - word(): string; // TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc + word(type?: string): string; words(count?: number): string; image(): string; locale(): string; alphaNumeric(count?: number): string; + hexaDecimal(count?: number): string; }; system: { @@ -201,8 +207,8 @@ declare namespace Faker { commonFileExt(): string; fileType(): string; fileExt(mimeType: string): string; - //directoryPath(): string; - //filePath(): string; + directoryPath(): string; + filePath(): string; semver(): string; }; @@ -315,10 +321,6 @@ declare module "faker/locale/de_CH" { export = fakerStatic; } -declare module "faker/locale/el_GR" { - export = fakerStatic; -} - declare module "faker/locale/en" { export = fakerStatic; } diff --git a/types/fancy-log/fancy-log-tests.ts b/types/fancy-log/fancy-log-tests.ts new file mode 100644 index 0000000000..581f75e42a --- /dev/null +++ b/types/fancy-log/fancy-log-tests.ts @@ -0,0 +1,26 @@ +import log = require('fancy-log'); + +log(); +log(1); +log('foo'); +log('foo', 'bar'); + +log.dir(); +log.dir(1); +log.dir('foo'); +log.dir('foo', 'bar'); + +log.error(); +log.error(1); +log.error('foo'); +log.error('foo', 'bar'); + +log.info(); +log.info(1); +log.info('foo'); +log.info('foo', 'bar'); + +log.warn(); +log.warn(1); +log.warn('foo'); +log.warn('foo', 'bar'); diff --git a/types/fancy-log/index.d.ts b/types/fancy-log/index.d.ts new file mode 100644 index 0000000000..2fbdb3f0d2 --- /dev/null +++ b/types/fancy-log/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for fancy-log 1.3 +// Project: https://github.com/js-cli/fancy-log +// Definitions by: Pine Mizune +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace FancyLog { + interface Logger { + (...args: any[]): Logger; + dir(...args: any[]): Logger; + error(...args: any[]): Logger; + info(...args: any[]): Logger; + warn(...args: any[]): Logger; + } +} + +declare var logger: FancyLog.Logger; +export = logger; diff --git a/types/fancy-log/tsconfig.json b/types/fancy-log/tsconfig.json new file mode 100644 index 0000000000..0ef3d95d9e --- /dev/null +++ b/types/fancy-log/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fancy-log-tests.ts" + ] +} diff --git a/types/fancy-log/tslint.json b/types/fancy-log/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fancy-log/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/feedparser/index.d.ts b/types/feedparser/index.d.ts index 7c257f15b5..75f3dde979 100644 --- a/types/feedparser/index.d.ts +++ b/types/feedparser/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/danmactough/node-feedparser // Definitions by: Juan J. Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + /** Declaration file generated by dts-gen */ /// diff --git a/types/fetch-mock/fetch-mock-tests.ts b/types/fetch-mock/fetch-mock-tests.ts index cfd595cb16..459c8e1076 100644 --- a/types/fetch-mock/fetch-mock-tests.ts +++ b/types/fetch-mock/fetch-mock-tests.ts @@ -1,6 +1,11 @@ import * as fetchMock from "fetch-mock"; fetchMock.mock("http://test.com", 200); +fetchMock.mock("http://test.com", 200, { + headers: { + test: "header" + } +}); fetchMock.mock(/test\.com/, 200); fetchMock.mock(() => true, 200); fetchMock.mock((url, opts) => true, 200); diff --git a/types/fetch-mock/index.d.ts b/types/fetch-mock/index.d.ts index b8c47b1e97..13563277b4 100644 --- a/types/fetch-mock/index.d.ts +++ b/types/fetch-mock/index.d.ts @@ -96,6 +96,10 @@ declare namespace fetchMock { * http method to match */ method?: string; + /** + * key/value map of headers to match + */ + headers?: { [key: string]: string }; /** * as specified above */ diff --git a/types/file-saver/file-saver-tests.ts b/types/file-saver/file-saver-tests.ts index 1cc06f58ba..7e704663d8 100644 --- a/types/file-saver/file-saver-tests.ts +++ b/types/file-saver/file-saver-tests.ts @@ -1,30 +1,40 @@ - - -import { saveAs as importedSaveAs } from "file-saver"; -function testImportedSaveAs() { - var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); - var filename: string = 'hello world.txt'; - var disableAutoBOM = true; - - importedSaveAs(data, filename, disableAutoBOM); -} +import "file-saver"; /** * @summary Test for "saveAs" function. */ function testSaveAs() { - var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); - var filename: string = 'hello world.txt'; - var disableAutoBOM = true; + const data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); + const filename = 'hello world.txt'; + const disableAutoBOM = true; saveAs(data, filename, disableAutoBOM); } /** - * @summary Test for "saveAs" function. + * @summary Test for "saveAs" function on the window object. */ -function testSaveAsFile() { - const data = new File(["Hello, world!"], "hello world.txt" ,{type: "text/plain;charset=utf-8"}); - +function testWindowSaveAs() { + const data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); + const filename = 'hello world.txt'; + const disableAutoBOM = true; + + window.saveAs(data, filename, disableAutoBOM); +} + +/** + * @summary Test for "saveAs" function with the 3rd parameter omitted + */ +function testOptionalOneParamSaveAs() { + const data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); + const filename = 'hello world.txt'; + saveAs(data, filename); +} + +/** + * @summary Test for "saveAs" function with the 2nd and 3rd parameters omitted + */ +function testOptionalTwoParamsSaveAs() { + const data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); saveAs(data); } diff --git a/types/file-saver/index.d.ts b/types/file-saver/index.d.ts index 8d78e10682..935fed44c2 100644 --- a/types/file-saver/index.d.ts +++ b/types/file-saver/index.d.ts @@ -1,46 +1,26 @@ -// Type definitions for FileSaver.js +// Type definitions for FileSaver.js 1.3 // Project: https://github.com/eligrey/FileSaver.js/ -// Definitions by: Cyril Schumacher , Daniel Roth -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Cyril Schumacher +// Daniel Roth +// Chris Barr +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/file-saver -/** - * @summary Interface for "saveAs" function. - * @author Cyril Schumacher - * @version 1.0 - */ -interface FileSaver { - ( - /** - * @summary Data. - * @type {Blob} - */ - data: Blob, - - /** - * @summary File name. - * @type {DOMString} - */ - filename: string, - - /** - * @summary Disable Unicode text encoding hints or not. - * @type {boolean} - */ - disableAutoBOM?: boolean - ): void - - ( - /** - * @summary File. - * @type {File} - */ - data: File - ): void +declare namespace FileSaver { + /** + * FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it. + * @param data - The actual file data blob. + * @param filename - The optional name of the file to be downloaded. If omitted, the name used in the file data will be used. If none is provided "download" will be used. + * @param disableAutoBOM - Optional & defaults to `false`. Set to `true` if you don't want FileSaver.js to automatically provide Unicode text encoding hints + */ + function saveAs(data: Blob, filename?: string, disableAutoBOM?: boolean): void; } -declare var saveAs: FileSaver; +declare global { + const saveAs: typeof FileSaver.saveAs; -declare module "file-saver" { - var fileSaver: { saveAs: typeof saveAs }; - export = fileSaver + interface Window { + saveAs: typeof FileSaver.saveAs; + } } + +export = FileSaver; diff --git a/types/file-saver/tsconfig.json b/types/file-saver/tsconfig.json index 1dc5a6f8f4..803ff5f510 100644 --- a/types/file-saver/tsconfig.json +++ b/types/file-saver/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "file-saver-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/file-saver/tslint.json b/types/file-saver/tslint.json index a41bf5d19a..adaee1b55f 100644 --- a/types/file-saver/tslint.json +++ b/types/file-saver/tslint.json @@ -1,79 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "export-just-namespace": false } } diff --git a/types/find/find-tests.ts b/types/find/find-tests.ts new file mode 100644 index 0000000000..c6c1cd04f5 --- /dev/null +++ b/types/find/find-tests.ts @@ -0,0 +1,32 @@ +import * as find from "find"; + +const stringPattern = ".d.ts"; +const regexPattern = /ts(config|lint)\.json/; +const rootDir = "."; + +const emptyCb = (): void => { }; +const errorCb = (err: Error): void => { }; +const stringArrayCallback = (paths: string[]): void => { }; +const singleStringCb = (paths: string): void => { }; + +find.file(rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void +find.file(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.file(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.file(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.fileSync(rootDir); // $ExpectType string[] +find.fileSync(stringPattern, rootDir); // $ExpectType string[] +find.fileSync(regexPattern, rootDir); // $ExpectType string[] +find.eachFile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachFile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachFile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream + +find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void +find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.dir(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.dir(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void +find.dirSync(rootDir); // $ExpectType string[] +find.dirSync(stringPattern, rootDir); // $ExpectType string[] +find.dirSync(regexPattern, rootDir); // $ExpectType string[] +find.eachDir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachDir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachDir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream diff --git a/types/find/index.d.ts b/types/find/index.d.ts new file mode 100644 index 0000000000..61166669db --- /dev/null +++ b/types/find/index.d.ts @@ -0,0 +1,116 @@ +// Type definitions for find 0.2 +// Project: https://github.com/yuanchuan/find#readme +// Definitions by: Andrey Lalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface AsyncFindStream { + /** + * Handling errors in asynchronous interfaces. + * @param callback The callback that is called upon an error + */ + error(callback: (() => void) | ((err: Error) => void)): void; +} + +export interface FindEachStream { + /** + * Handling errors in asynchronous interfaces. + * @param callback The callback that is called upon an error + */ + error(callback: (() => void) | ((err: Error) => void)): FindEachStream; + + /** + * Detect end in find.eachfile and find.eachdir. + * @param callback The callback called at the end of find.eachfile and find.eachdir + */ + end(callback: () => void): FindEachStream; +} + +/** + * Find all files in a given directory asynchronously. + * @param root The root directory + * @param callback A callback that accepts an array of the found files + */ +export function file(root: string, callback: (files: string[]) => void): AsyncFindStream; + +/** + * Find all files that match a glob pattern in a given directory asynchronously. + * @param pattern The pattern to filter the files with + * @param root The root directory + * @param callback A callback that accepts an array of the found files + */ +export function file(pattern: string | RegExp, root: string, callback: (files: string[]) => void): AsyncFindStream; + +/** + * Find all files in a given directory asynchronously. + * @param root The root directory + * @param callback A callback that accepts each file separately + */ +export function eachFile(root: string, callback: (file: string) => void): FindEachStream; + +/** + * Find all files that match a glob pattern in a given directory asynchronously. + * @param pattern The pattern to filter the files with + * @param root The root directory + * @param callback A callback that accepts an array of the found files + */ +export function eachFile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; + +/** + * Find all files in a given directory synchronously. + * @param root The root directory + * @returns The files that have been found + */ +export function fileSync(root: string): string[]; + +/** + * Find all files that match a glob pattern in a given directory synchronously. + * @param pattern The pattern to filter the files with + * @param root The root directory + * @returns The files that have been found + */ +export function fileSync(pattern: string | RegExp, root: string): string[]; + +/** + * Find all directories in a given directory asynchronously. + * @param root The root directory + * @param callback A callback that accepts an array of the found directories + */ +export function dir(root: string, callback: (directories: string[]) => void): AsyncFindStream; + +/** + * Find all directories that match a glob pattern in a given directory asynchronously. + * @param pattern The pattern to filter the directories with + * @param root The root directory + * @param callback A callback that accepts an array of the found directories + */ +export function dir(pattern: RegExp | string, root: string, callback: (directories: string[]) => void): AsyncFindStream; + +/** + * Find all directories in a given directory synchronously. + * @param root The root directory + * @returns The directories that have been found + */ +export function dirSync(root: string): string[]; + +/** + * Find all directories that match a glob pattern in a given directory synchronously. + * @param pattern The pattern to filter the directories with + * @param root The root directory + * @returns The directories that have been found + */ +export function dirSync(pattern: string | RegExp, root: string): string[]; + +/** + * Find all directories in a given directory asynchronously. + * @param root The root directory + * @param callback A callback that accepts each of the found directories separately + */ +export function eachDir(root: string, callback: (directory: string) => void): FindEachStream; + +/** + * Find all directories that match a glob pattern in a given directory asynchronously. + * @param pattern The pattern to filter the directories with + * @param root The root directory + * @param callback A callback that accepts each of the found directories separately + */ +export function eachDir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; diff --git a/types/find/tsconfig.json b/types/find/tsconfig.json new file mode 100644 index 0000000000..e231e78ff5 --- /dev/null +++ b/types/find/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "find-tests.ts" + ] +} diff --git a/types/find/tslint.json b/types/find/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/find/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fingerprintjs2/index.d.ts b/types/fingerprintjs2/index.d.ts index c9fc9b2a39..94b705b807 100644 --- a/types/fingerprintjs2/index.d.ts +++ b/types/fingerprintjs2/index.d.ts @@ -13,7 +13,7 @@ declare class Fingerprint2 { interface Fingerprint2Options { swfContainerId?: string; swfPath?: string; - userDefinedFonts?: [string]; + userDefinedFonts?: string[]; excludeUserAgent?: boolean; excludeLanguage?: boolean; excludeColorDepth?: boolean; diff --git a/types/firebase-client/index.d.ts b/types/firebase-client/index.d.ts index fe5dd5b9e7..f13c8499f5 100644 --- a/types/firebase-client/index.d.ts +++ b/types/firebase-client/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.github.com/jpstevens/firebase-client // Definitions by: Andrew Breen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from "q"; diff --git a/types/firebird/index.d.ts b/types/firebird/index.d.ts index 771a61f706..37d88324fc 100644 --- a/types/firebird/index.d.ts +++ b/types/firebird/index.d.ts @@ -445,7 +445,6 @@ declare module 'firebird' { */ class Stream extends stream.Stream { constructor(blob: FBBlob); - /* tslint:disable */ /* NodeJS.ReadStream */ readable: boolean; @@ -462,7 +461,6 @@ declare module 'firebird' { end(str: string, encoding?: string, cb?: Function): void; destroy(error?: Error): void; - /* tslint:enable */ check_destroyed(): void; } } diff --git a/types/firebird/tslint.json b/types/firebird/tslint.json index 4b3c58f2c3..b9ced8ae6f 100644 --- a/types/firebird/tslint.json +++ b/types/firebird/tslint.json @@ -2,8 +2,11 @@ "extends": "dtslint/dt.json", "rules": { // TODO + "ban-types": false, "no-boolean-literal-compare": false, "no-declare-current-package": false, - "no-unnecessary-generics": false + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "unified-signatures": false } } diff --git a/types/first-mate/README.md b/types/first-mate/README.md deleted file mode 100644 index 9d8ccb3d39..0000000000 --- a/types/first-mate/README.md +++ /dev/null @@ -1,38 +0,0 @@ -## First Mate Type Definitions - -TypeScript type definitions for [First Mate](https://github.com/atom/first-mate), which is published as "[first-mate](https://www.npmjs.com/package/first-mate)" on NPM. - -### Usage Notes - -#### Exports - -The three classes exported from this module are: [Grammar](https://github.com/atom/first-mate/blob/master/src/grammar.coffee), [GrammarRegistry](https://github.com/atom/first-mate/blob/master/src/grammar-registry.coffee), and [ScopeSelector](https://github.com/atom/first-mate/blob/master/src/scope-selector.coffee). - -```ts -import { Grammar, GrammarRegistry, ScopeSelector } from "first-mate"; -let selector = new ScopeSelector("a | b"); -``` - -#### The FirstMate Namespace - -Many of the types used by First Mate can be referenced from the FirstMate namespace. - -```ts -function example(grammar: FirstMate.Grammar) {} -``` - -### Exposing Private Methods and Properties - -[Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) can be used to augment any of the types used within First Mate. As an example, if we wanted to reveal the private ```getMaxTokensPerLine``` method within the Grammar class, then we would create a file with the following contents: - -```ts -// <>.d.ts - -declare namespace FirstMate { - interface Grammar { - getMaxTokensPerLine(): number; - } -} -``` - -Once this file is either referenced or included within your project, then this new member function would be freely usable on instances of the Grammar class without TypeScript reporting errors. diff --git a/types/first-mate/first-mate-tests.ts b/types/first-mate/first-mate-tests.ts index b348cd1758..3d3be512a1 100644 --- a/types/first-mate/first-mate-tests.ts +++ b/types/first-mate/first-mate-tests.ts @@ -1,8 +1,9 @@ +import { Disposable } from "event-kit"; import { GrammarRegistry, Grammar, ScopeSelector } from "first-mate"; -declare let subscription: EventKit.Disposable; -declare let grammar: FirstMate.Grammar; -declare let grammars: FirstMate.Grammar[]; +declare let subscription: Disposable; +declare let grammar: Grammar; +declare let grammars: Grammar[]; // NPM Examples =============================================================== const selector = new ScopeSelector("a | b"); diff --git a/types/first-mate/index.d.ts b/types/first-mate/index.d.ts index 0bd44b7ede..c7df2365c3 100644 --- a/types/first-mate/index.d.ts +++ b/types/first-mate/index.d.ts @@ -4,251 +4,249 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -/// - -declare global { - /** TextMate helpers. */ - namespace FirstMate { - /** The option objects that the user is expected to fill out and provide to - * specific API calls. - */ - namespace Options { - interface Grammar { - name?: string; - fileTypes?: ReadonlyArray; - scopeName?: string; - foldingStopMarker?: string; - maxTokensPerLine?: number; - maxLineLength?: number; - - injections?: object; - injectionSelector?: ScopeSelector; - patterns?: ReadonlyArray; - repository?: object; - firstLineMatch?: boolean; - } - } - - /** The structures that are passed to the user by Atom following specific API calls. */ - namespace Structures { - interface GrammarToken { - value: string; - scopes: string[]; - } - - /** Result returned by `Grammar.tokenizeLine`. */ - interface TokenizeLineResult { - /** The string of text that was tokenized. */ - line: string; - - /** An array of integer scope ids and strings. Positive ids indicate the - * beginning of a scope, and negative tags indicate the end. To resolve ids - * to scope names, call GrammarRegistry::scopeForId with the absolute - * value of the id. - */ - tags: Array; - - /** This is a dynamic property. Invoking it will incur additional overhead, - * but will automatically translate the `tags` into token objects with `value` - * and `scopes` properties. - */ - tokens: GrammarToken[]; - - /** An array of rules representing the tokenized state at the end of the line. - * These should be passed back into this method when tokenizing the next line - * in the file. - */ - ruleStack: GrammarRule[]; - } - - interface GrammarRule { - // https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee - // This is private. Don't go down the rabbit hole. - rule: object; - scopeName: string; - contentScopeName: string; - } - } - - /** Grammar that tokenizes lines of text. */ - interface Grammar { - name: string; - fileTypes: string[]; - scopeName: string; - maxTokensPerLine: number; - maxLineLength: number; - - // Event Subscription - onDidUpdate(callback: () => void): EventKit.Disposable; - - // Tokenizing - /** Tokenize all lines in the given text. - * @param text A string containing one or more lines. - * @return An array of token arrays for each line tokenized. - */ - tokenizeLines(text: string): Structures.GrammarToken[][]; - - /** Tokenizes the line of text. - * @param line A string of text to tokenize. - * @param ruleStack An optional array of rules previously returned from this - * method. This should be null when tokenizing the first line in the file. - * @param firstLine A optional boolean denoting whether this is the first line - * in the file which defaults to `false`. - * @return An object representing the result of the tokenize. - */ - tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean): - Structures.TokenizeLineResult; - /** Tokenizes the line of text. - * @param line A string of text to tokenize. - * @param ruleStack An optional array of rules previously returned from this - * method. This should be null when tokenizing the first line in the file. - * @param firstLine A optional boolean denoting whether this is the first line - * in the file which defaults to `false`. - * @return An object representing the result of the tokenize. - */ - tokenizeLine(line: string, ruleStack: Structures.GrammarRule[], firstLine?: false): - Structures.TokenizeLineResult; - } - - /** The static side to the Grammar class. */ - interface GrammarStatic { - new (registry: GrammarRegistry, options?: Options.Grammar): Grammar; - } - - /** Instance side of GrammarRegistry class. */ - interface GrammarRegistry { - maxTokensPerLine: number; - maxLineLength: number; - - // Event Subscription - /** Invoke the given callback when a grammar is added to the registry. - * @param callback The callback to be invoked whenever a grammar is added. - * @return A Disposable on which `.dispose()` can be called to unsubscribe. - */ - onDidAddGrammar(callback: (grammar: Grammar) => void): EventKit.Disposable; - - /** Invoke the given callback when a grammar is updated due to a grammar it - * depends on being added or removed from the registry. - * @param callback The callback to be invoked whenever a grammar is updated. - * @return A Disposable on which `.dispose()` can be called to unsubscribe. - */ - onDidUpdateGrammar(callback: (grammar: Grammar) => void): EventKit.Disposable; - - // Managing Grammars - /** Get all the grammars in this registry. - * @return A non-empty array of Grammar instances. - */ - getGrammars(): Grammar[]; - - /** Get a grammar with the given scope name. - * @param scopeName A string such as `source.js`. - * @return A Grammar or undefined. - */ - grammarForScopeName(scopeName: string): Grammar|undefined; - - /** Add a grammar to this registry. - * A 'grammar-added' event is emitted after the grammar is added. - * @param grammar The Grammar to add. This should be a value previously returned - * from ::readGrammar or ::readGrammarSync. - * @return Returns a Disposable on which `.dispose()` can be called to remove - * the grammar. - */ - addGrammar(grammar: Grammar): EventKit.Disposable; - - /** Remove the given grammar from this registry. - * @param grammar The grammar to remove. This should be a grammar previously - * added to the registry from ::addGrammar. - */ - removeGrammar(grammar: Grammar): void; - - /** Remove the grammar with the given scope name. - * @param scopeName A string such as `source.js`. - * @return Returns the removed Grammar or undefined. - */ - removeGrammarForScopeName(scopeName: string): Grammar|undefined; - - /** Read a grammar synchronously but don't add it to the registry. - * @param grammarPath The absolute file path to a grammar. - * @return The newly loaded Grammar. - */ - readGrammarSync(grammarPath: string): Grammar; - - /** Read a grammar asynchronously but don't add it to the registry. - * @param grammarPath The absolute file path to the grammar. - * @param callback The function to be invoked once the Grammar has been read in. - */ - readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => - void): void; - - /** Read a grammar synchronously and add it to this registry. - * @param grammarPath The absolute file path to the grammar. - * @return The newly loaded Grammar. - */ - loadGrammarSync(grammarPath: string): Grammar; - - /** Read a grammar asynchronously and add it to the registry. - * @param grammarPath The absolute file path to the grammar. - * @param callback The function to be invoked once the Grammar has been read in - * and added to the registry. - */ - loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => - void): void; - - /** Convert compact tags representation into convenient, space-inefficient tokens. - * @param lineText The text of the tokenized line. - * @param tags The tags returned from a call to Grammar::tokenizeLine(). - * @return An array of Token instances decoded from the given tags. - */ - decodeTokens(lineText: string, tags: Array): Structures.GrammarToken[]; - } - - /** The static side to the GrammarRegistry class. */ - interface GrammarRegistryStatic { - new (options?: { maxTokensPerLine?: number, maxLineLength?: number }): - GrammarRegistry; - } - - interface ScopeSelector { - /** Check if this scope selector matches the scopes. - * @param scopes A single scope or an array of them to be compared against. - * @return A boolean indicating whether or not this ScopeSelector matched. - */ - matches(scopes: string|ReadonlyArray): boolean; - - /** Gets the prefix of this scope selector. - * @param scopes The scopes to match a prefix against. - * @return The matching prefix, if there is one. - */ - getPrefix(scopes: string|ReadonlyArray): string|undefined; - - /** Convert this TextMate scope selector to a CSS selector. - * @return A string with the CSSSelector representation of this ScopeSelector. - */ - toCssSelector(): string; - - /** Convert this TextMate scope selector to a CSS selector, prefixing scopes - * with `syntax--`. - * @return A string with the syntax-specific CSSSelector representation of this - * ScopeSelector. - */ - toCssSyntaxSelector(): string; - } - - /** The static side to the ScopeSelector class. */ - interface ScopeSelectorStatic { - /** Create a new scope selector. - * @param source The string to parse as a scope selector. - * @return A newly constructed ScopeSelector. - */ - new (source: string): ScopeSelector; - } - } -} - -/** Registry containing one or more grammars. */ -export const GrammarRegistry: FirstMate.GrammarRegistryStatic; - -export const ScopeSelector: FirstMate.ScopeSelectorStatic; +import { Disposable } from "event-kit"; /** Grammar that tokenizes lines of text. */ -export const Grammar: FirstMate.GrammarStatic; +export class Grammar { + name: string; + fileTypes: string[]; + scopeName: string; + maxTokensPerLine: number; + maxLineLength: number; + + constructor(registry: GrammarRegistry, options?: GrammarOptions); + + // Event Subscription + onDidUpdate(callback: () => void): Disposable; + + // Tokenizing + /** + * Tokenize all lines in the given text. + * @param text A string containing one or more lines. + * @return An array of token arrays for each line tokenized. + */ + tokenizeLines(text: string): GrammarToken[][]; + + /** + * Tokenizes the line of text. + * @param line A string of text to tokenize. + * @param ruleStack An optional array of rules previously returned from this + * method. This should be null when tokenizing the first line in the file. + * @param firstLine A optional boolean denoting whether this is the first line + * in the file which defaults to `false`. + * @return An object representing the result of the tokenize. + */ + tokenizeLine(line: string, ruleStack?: null, firstLine?: boolean): TokenizeLineResult; + /** + * Tokenizes the line of text. + * @param line A string of text to tokenize. + * @param ruleStack An optional array of rules previously returned from this + * method. This should be null when tokenizing the first line in the file. + * @param firstLine A optional boolean denoting whether this is the first line + * in the file which defaults to `false`. + * @return An object representing the result of the tokenize. + */ + tokenizeLine(line: string, ruleStack: GrammarRule[], firstLine?: false): + TokenizeLineResult; +} + +/** Instance side of GrammarRegistry class. */ +export class GrammarRegistry { + maxTokensPerLine: number; + maxLineLength: number; + + constructor(options?: { maxTokensPerLine?: number, maxLineLength?: number }); + + // Event Subscription + /** + * Invoke the given callback when a grammar is added to the registry. + * @param callback The callback to be invoked whenever a grammar is added. + * @return A Disposable on which `.dispose()` can be called to unsubscribe. + */ + onDidAddGrammar(callback: (grammar: Grammar) => void): Disposable; + + /** + * Invoke the given callback when a grammar is updated due to a grammar it + * depends on being added or removed from the registry. + * @param callback The callback to be invoked whenever a grammar is updated. + * @return A Disposable on which `.dispose()` can be called to unsubscribe. + */ + onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable; + + // Managing Grammars + /** + * Get all the grammars in this registry. + * @return A non-empty array of Grammar instances. + */ + getGrammars(): Grammar[]; + + /** + * Get a grammar with the given scope name. + * @param scopeName A string such as `source.js`. + * @return A Grammar or undefined. + */ + grammarForScopeName(scopeName: string): Grammar|undefined; + + /** + * Add a grammar to this registry. + * A 'grammar-added' event is emitted after the grammar is added. + * @param grammar The Grammar to add. This should be a value previously returned + * from ::readGrammar or ::readGrammarSync. + * @return Returns a Disposable on which `.dispose()` can be called to remove + * the grammar. + */ + addGrammar(grammar: Grammar): Disposable; + + /** + * Remove the given grammar from this registry. + * @param grammar The grammar to remove. This should be a grammar previously + * added to the registry from ::addGrammar. + */ + removeGrammar(grammar: Grammar): void; + + /** + * Remove the grammar with the given scope name. + * @param scopeName A string such as `source.js`. + * @return Returns the removed Grammar or undefined. + */ + removeGrammarForScopeName(scopeName: string): Grammar|undefined; + + /** + * Read a grammar synchronously but don't add it to the registry. + * @param grammarPath The absolute file path to a grammar. + * @return The newly loaded Grammar. + */ + readGrammarSync(grammarPath: string): Grammar; + + /** + * Read a grammar asynchronously but don't add it to the registry. + * @param grammarPath The absolute file path to the grammar. + * @param callback The function to be invoked once the Grammar has been read in. + */ + readGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => + void): void; + + /** + * Read a grammar synchronously and add it to this registry. + * @param grammarPath The absolute file path to the grammar. + * @return The newly loaded Grammar. + */ + loadGrammarSync(grammarPath: string): Grammar; + + /** + * Read a grammar asynchronously and add it to the registry. + * @param grammarPath The absolute file path to the grammar. + * @param callback The function to be invoked once the Grammar has been read in + * and added to the registry. + */ + loadGrammar(grammarPath: string, callback: (error: Error|null, grammar?: Grammar) => + void): void; + + /** + * Convert compact tags representation into convenient, space-inefficient tokens. + * @param lineText The text of the tokenized line. + * @param tags The tags returned from a call to Grammar::tokenizeLine(). + * @return An array of Token instances decoded from the given tags. + */ + decodeTokens(lineText: string, tags: Array): GrammarToken[]; +} + +export class ScopeSelector { + /** + * Create a new scope selector. + * @param source The string to parse as a scope selector. + * @return A newly constructed ScopeSelector. + */ + constructor(source: string); + + /** + * Check if this scope selector matches the scopes. + * @param scopes A single scope or an array of them to be compared against. + * @return A boolean indicating whether or not this ScopeSelector matched. + */ + matches(scopes: string|ReadonlyArray): boolean; + + /** + * Gets the prefix of this scope selector. + * @param scopes The scopes to match a prefix against. + * @return The matching prefix, if there is one. + */ + getPrefix(scopes: string|ReadonlyArray): string|undefined; + + /** + * Convert this TextMate scope selector to a CSS selector. + * @return A string with the CSSSelector representation of this ScopeSelector. + */ + toCssSelector(): string; + + /** + * Convert this TextMate scope selector to a CSS selector, prefixing scopes + * with `syntax--`. + * @return A string with the syntax-specific CSSSelector representation of this + * ScopeSelector. + */ + toCssSyntaxSelector(): string; +} + +// Options ==================================================================== +// The option objects that the user is expected to fill out and provide to +// specific API calls. + +export interface GrammarOptions { + name?: string; + fileTypes?: ReadonlyArray; + scopeName?: string; + foldingStopMarker?: string; + maxTokensPerLine?: number; + maxLineLength?: number; + + injections?: object; + injectionSelector?: ScopeSelector; + patterns?: ReadonlyArray; + repository?: object; + firstLineMatch?: boolean; +} + +// Structures ================================================================= +// The structures that are passed to the user by Atom following specific API calls. + +export interface GrammarToken { + value: string; + scopes: string[]; +} + +/** Result returned by `Grammar.tokenizeLine`. */ +export interface TokenizeLineResult { + /** The string of text that was tokenized. */ + line: string; + + /** + * An array of integer scope ids and strings. Positive ids indicate the + * beginning of a scope, and negative tags indicate the end. To resolve ids + * to scope names, call GrammarRegistry::scopeForId with the absolute + * value of the id. + */ + tags: Array; + + /** + * This is a dynamic property. Invoking it will incur additional overhead, + * but will automatically translate the `tags` into token objects with `value` + * and `scopes` properties. + */ + tokens: GrammarToken[]; + + /** + * An array of rules representing the tokenized state at the end of the line. + * These should be passed back into this method when tokenizing the next line + * in the file. + */ + ruleStack: GrammarRule[]; +} + +export interface GrammarRule { + // https://github.com/atom/first-mate/blob/v7.0.7/src/rule.coffee + // This is private. Don't go down the rabbit hole. + rule: object; + scopeName: string; + contentScopeName: string; +} diff --git a/types/first-mate/tsconfig.json b/types/first-mate/tsconfig.json index 3d6aadabec..3c11f8dbb2 100644 --- a/types/first-mate/tsconfig.json +++ b/types/first-mate/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +21,4 @@ "index.d.ts", "first-mate-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/first-mate/tslint.json b/types/first-mate/tslint.json index d1318cfc63..e0508241c7 100644 --- a/types/first-mate/tslint.json +++ b/types/first-mate/tslint.json @@ -1,36 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "class-name": true, "indent": [true, "spaces", 4], - "jsdoc-format": true, - "max-line-length": [true, 110], - "quotemark": [true, "double", "avoid-escape"], - "trailing-comma": [true, { - "multiline": { "objects": "always", "arrays": "always", "functions": "never" }, - "singleline": { "objects": "never", "arrays": "never", "functions": "never" } - }], - "whitespace": [ - true, - "check-branch", - "check-decl", - "check-operator", - "check-module", - "check-separator", - "check-type", - "check-typecast", - "check-rest-spread", - "check-preblock" - ], - // Soon to be defaults. - "arrow-return-shorthand": [true, "multiline"], - "no-any": true, - "no-floating-promises": true, - "no-unbound-method": true, - "no-unsafe-any": true, - "number-literal-format": true, - "restrict-plus-operands": true, - "return-undefined": true, - "switch-final-break": true + "max-line-length": [true, 100], + "no-any": true } } diff --git a/types/fixed-data-table/fixed-data-table-tests.tsx b/types/fixed-data-table/fixed-data-table-tests.tsx index cdbd46eb6c..bb09fedcaf 100644 --- a/types/fixed-data-table/fixed-data-table-tests.tsx +++ b/types/fixed-data-table/fixed-data-table-tests.tsx @@ -36,7 +36,7 @@ class MyTable2 extends React.Component { // provide Custom Data interface MyTable3State { - myTableData: [{name: string}]; + myTableData: {name: string}[]; } class MyTable3 extends React.Component<{}, MyTable3State> { diff --git a/types/fontfaceobserver/index.d.ts b/types/fontfaceobserver/index.d.ts index 8f461dbd4f..a10214a57d 100644 --- a/types/fontfaceobserver/index.d.ts +++ b/types/fontfaceobserver/index.d.ts @@ -25,7 +25,7 @@ declare class FontFaceObserver { * @param testString If your font doesn't contain latin characters you can pass a custom test string. * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. */ - load(testString?: string, timeout?: number): Promise; + load(testString?: string | null, timeout?: number): Promise; } declare module "fontfaceobserver" { diff --git a/types/form-data/index.d.ts b/types/form-data/index.d.ts index 9b102b287f..24e46b3bb8 100644 --- a/types/form-data/index.d.ts +++ b/types/form-data/index.d.ts @@ -4,6 +4,7 @@ // Leon Yu // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts diff --git a/types/format-io/format-io-tests.ts b/types/format-io/format-io-tests.ts new file mode 100644 index 0000000000..bb551740d0 --- /dev/null +++ b/types/format-io/format-io-tests.ts @@ -0,0 +1,6 @@ +import * as format from 'format-io'; + +format.addSlashToEnd('a/s/d'); // $ExpectType string +format.size(1024 * 1024); // $ExpectType string +format.permissions.symbolic('00777'); // $ExpectType string +format.permissions.numeric('rwx rwx rwx'); // $ExpectType string diff --git a/types/format-io/index.d.ts b/types/format-io/index.d.ts new file mode 100644 index 0000000000..67e86188d6 --- /dev/null +++ b/types/format-io/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for format-io 0.9 +// Project: http://github.com/coderaiser/format-io +// Definitions by: Amit Beckenstein +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Appends a '/' to the end of the path unless it exists. + * @param path A path. + * @returns The path with a '/' appended to it. + */ +export function addSlashToEnd(path: string): string; + +/** + * Returns a short string representing the size of bytes in unit symbols up to petabytes. + * @param size Size in bytes. + * @returns A string representing the size in the matching unit symbol. + */ +export function size(size: number): string; + +/** + * Contains functions to format permissions. + */ +export namespace permissions { + /** + * Converts Unix-like permissions from numeric to symbolic notation. + * @param perm A string of Unix-like permission in numeric notation. + * @returns A representation of the permissions in symbolic notation. + */ + function symbolic(perm: string): string; + + /** + * Converts Unix-like permissions from symbolic to numeric notation. + * @param perm A string of Unix-like permission in symbolic notation. + * @returns A representation of the permissions in numeric notation. + */ + function numeric(perm: string): string; +} diff --git a/types/format-io/tsconfig.json b/types/format-io/tsconfig.json new file mode 100644 index 0000000000..29333d35cf --- /dev/null +++ b/types/format-io/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "format-io-tests.ts" + ] +} diff --git a/types/format-io/tslint.json b/types/format-io/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/format-io/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fossil-delta/index.d.ts b/types/fossil-delta/index.d.ts index 98ab4cc600..3b79af9cc4 100644 --- a/types/fossil-delta/index.d.ts +++ b/types/fossil-delta/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fossil-delta 0.2.5 +// Type definitions for fossil-delta 1.0.0 // Project: https://github.com/dchest/fossil-delta-js // Definitions by: Endel Dreyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,5 +8,5 @@ type ByteArray = Array | Uint8Array | Buffer; export function create(origin: ByteArray, target: ByteArray): Array; -export function apply(origin: ByteArray, delta: Array): Array; +export function apply(origin: ByteArray, delta: Array, ops?: { verifyChecksum: boolean }): Array; export function outputSize(delta: Array): number; diff --git a/types/fs-cson/fs-cson-tests.ts b/types/fs-cson/fs-cson-tests.ts new file mode 100644 index 0000000000..1d23580cad --- /dev/null +++ b/types/fs-cson/fs-cson-tests.ts @@ -0,0 +1,39 @@ +import * as fsCson from 'fs-cson'; + +fsCson.register(); + +fsCson.readFile('sample.cson', (err, data) => { + if (!err) { + console.log(data); + } +}); + +const data = fsCson.readFileSync('sample.cson'); + +function updater(data: any) { + const result: any = {}; + for (const key in data) { + const value = data[key]; + result[key] = value * 2; + } + result.c = 6; + return result; +} + +fsCson.updateFile('sample.cson', updater, (err) => { + if (err) console.error(err); +}); + +fsCson.updateFileSync('sample.cson', updater); + +fsCson.writeFile('sample.cson', { a: 1, b: 2 }, (err) => { + if (err) console.error(err); +}); + +fsCson.writeFileSync('sample.cson', { a: 1, b: 2 }); + +fsCson.writeFileSafe('sample.cson', { a: 1, b: 2 }, (err) => { + if (err) console.error(err); +}); + +fsCson.writeFileSafeSync('sample.cson', { a: 1, b: 2 }); diff --git a/types/fs-cson/index.d.ts b/types/fs-cson/index.d.ts new file mode 100644 index 0000000000..86d37c0634 --- /dev/null +++ b/types/fs-cson/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fs-cson 0.3 +// Project: https://github.com/charlierudolph/fs-cson +// Definitions by: Piotr Roszatycki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function readFile(filePath: string, done: (err: Error | null, result: any) => void): void; +export function readFileSync(filePath: string): any; +export function register(): void; +export function updateFile(filePath: string, updater: (data: any) => any, done: (err: NodeJS.ErrnoException) => void): void; +export function updateFileSync(filePath: string, updater: (data: any) => any): void; +export function writeFile(filePath: string, data: any, done: (err: NodeJS.ErrnoException) => void): void; +export function writeFileSync(filePath: string, data: any): void; +export function writeFileSafe(filePath: string, data: any, done: (err: NodeJS.ErrnoException) => void): void; +export function writeFileSafeSync(filePath: string, data: any): void; diff --git a/types/fs-cson/tsconfig.json b/types/fs-cson/tsconfig.json new file mode 100644 index 0000000000..fcd9242b1d --- /dev/null +++ b/types/fs-cson/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-cson-tests.ts" + ] +} diff --git a/types/fs-cson/tslint.json b/types/fs-cson/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fs-cson/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index f405486adb..1af094260d 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -14,7 +14,7 @@ const fd = 0; const modeNum = 0; const modeStr = ""; const object = {}; -const errorCallback = (err: Error | null) => { }; +const errorCallback = (err: Error) => { }; const readOptions: fs.ReadOptions = { reviver: {} }; diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 84548e48a4..82bd401c39 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -14,141 +14,141 @@ import { Stats } from "fs"; export * from "fs"; export function copy(src: string, dest: string, options?: CopyOptions): Promise; -export function copy(src: string, dest: string, callback: (err: Error | null) => void): void; -export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error | null) => void): void; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; export function copySync(src: string, dest: string, options?: CopyOptions): void; export function move(src: string, dest: string, options?: MoveOptions): Promise; -export function move(src: string, dest: string, callback: (err: Error | null) => void): void; -export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error | null) => void): void; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; export function moveSync(src: string, dest: string, options?: MoveOptions): void; export function createFile(file: string): Promise; -export function createFile(file: string, callback: (err: Error | null) => void): void; +export function createFile(file: string, callback: (err: Error) => void): void; export function createFileSync(file: string): void; export function ensureDir(path: string): Promise; -export function ensureDir(path: string, callback: (err: Error | null) => void): void; +export function ensureDir(path: string, callback: (err: Error) => void): void; export function ensureDirSync(path: string): void; export function mkdirs(dir: string): Promise; -export function mkdirs(dir: string, callback: (err: Error | null) => void): void; +export function mkdirs(dir: string, callback: (err: Error) => void): void; export function mkdirp(dir: string): Promise; -export function mkdirp(dir: string, callback: (err: Error | null) => void): void; +export function mkdirp(dir: string, callback: (err: Error) => void): void; export function mkdirsSync(dir: string): void; export function mkdirpSync(dir: string): void; -export function outputFile(file: string, data: any): Promise; -export function outputFile(file: string, data: any, callback: (err: Error | null) => void): void; -export function outputFileSync(file: string, data: any): void; +export function outputFile(file: string, data: any, options?: WriteFileOptions | string): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFile(file: string, data: any, options: WriteFileOptions | string, callback: (err: Error) => void): void; +export function outputFileSync(file: string, data: any, options?: WriteFileOptions | string): void; export function readJson(file: string, options?: ReadOptions): Promise; -export function readJson(file: string, callback: (err: Error | null, jsonObject: any) => void): void; -export function readJson(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; export function readJSON(file: string, options?: ReadOptions): Promise; -export function readJSON(file: string, callback: (err: Error | null, jsonObject: any) => void): void; -export function readJSON(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; export function readJsonSync(file: string, options?: ReadOptions): any; export function readJSONSync(file: string, options?: ReadOptions): any; export function remove(dir: string): Promise; -export function remove(dir: string, callback: (err: Error | null) => void): void; +export function remove(dir: string, callback: (err: Error) => void): void; export function removeSync(dir: string): void; export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; -export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; -export function outputJSON(file: string, data: any, callback: (err: Error | null) => void): void; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; export function outputJson(file: string, data: any, options?: WriteOptions): Promise; -export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; -export function outputJson(file: string, data: any, callback: (err: Error | null) => void): void; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; -export function writeJSON(file: string, object: any, callback: (err: Error | null) => void): void; -export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; export function writeJson(file: string, object: any, options?: WriteOptions): Promise; -export function writeJson(file: string, object: any, callback: (err: Error | null) => void): void; -export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; export function ensureFile(path: string): Promise; -export function ensureFile(path: string, callback: (err: Error | null) => void): void; +export function ensureFile(path: string, callback: (err: Error) => void): void; export function ensureFileSync(path: string): void; export function ensureLink(src: string, dest: string): Promise; -export function ensureLink(src: string, dest: string, callback: (err: Error | null) => void): void; +export function ensureLink(src: string, dest: string, callback: (err: Error) => void): void; export function ensureLinkSync(src: string, dest: string): void; export function ensureSymlink(src: string, dest: string, type?: SymlinkType): Promise; -export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error | null) => void): void; -export function ensureSymlink(src: string, dest: string, callback: (err: Error | null) => void): void; +export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error) => void): void; +export function ensureSymlink(src: string, dest: string, callback: (err: Error) => void): void; export function ensureSymlinkSync(src: string, dest: string, type?: SymlinkType): void; export function emptyDir(path: string): Promise; -export function emptyDir(path: string, callback: (err: Error | null) => void): void; +export function emptyDir(path: string, callback: (err: Error) => void): void; export function emptyDirSync(path: string): void; export function pathExists(path: string): Promise; -export function pathExists(path: string, callback: (err: Error | null, exists: boolean) => void): void; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; export function pathExistsSync(path: string): boolean; // fs async methods // copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts -/** Tests a user's permissions for the file specified by path. */ -export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; -export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode?: number): Promise; export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, - callback: (err: NodeJS.ErrnoException | null) => void): void; -export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; + callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function appendFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; -export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function chmod(path: string | Buffer, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; export function chmod(path: string | Buffer, mode: string | number): Promise; export function chown(path: string | Buffer, uid: number, gid: number): Promise; -export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; -export function close(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; export function close(fd: number): Promise; -export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; export function fchmod(fd: number, mode: string | number): Promise; -export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; export function fchown(fd: number, uid: number, gid: number): Promise; export function fdatasync(fd: number, callback: () => void): void; export function fdatasync(fd: number): Promise; -export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function fstat(fd: number): Promise; -export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; export function fsync(fd: number): Promise; -export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err: NodeJS.ErrnoException) => void): void; export function ftruncate(fd: number, len?: number): Promise; -export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; export function futimes(fd: number, atime: number, mtime: number): Promise; export function futimes(fd: number, atime: Date, mtime: Date): Promise; -export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; export function lchown(path: string | Buffer, uid: number, gid: number): Promise; -export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; -export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function lstat(path: string | Buffer): Promise; /** @@ -156,42 +156,42 @@ export function lstat(path: string | Buffer): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function mkdir(path: string | Buffer, mode: number | string, callback: (err: NodeJS.ErrnoException) => void): void; export function mkdir(path: string | Buffer): Promise; -export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; -export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; -export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; -export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; +export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; // tslint:disable-next-line:unified-signatures export function readFile(file: string | Buffer | number, encoding: string): Promise; export function readFile(file: string | Buffer | number): Promise; -export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; export function readdir(path: string | Buffer): Promise; -export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => any): void; +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; export function readlink(path: string | Buffer): Promise; -export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; -export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; -export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function rename(oldPath: string, newPath: string, callback: (err: NodeJS.ErrnoException) => void): void; export function rename(oldPath: string, newPath: string): Promise; /** @@ -199,17 +199,17 @@ export function rename(oldPath: string, newPath: string): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function rmdir(path: string | Buffer): Promise; -export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function stat(path: string | Buffer): Promise; -export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err: NodeJS.ErrnoException) => void): void; export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; -export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function truncate(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException) => void): void; export function truncate(path: string | Buffer, len?: number): Promise; /** @@ -217,25 +217,25 @@ export function truncate(path: string | Buffer, len?: number): Promise; * * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function unlink(path: string | Buffer): Promise; -export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; -export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err: NodeJS.ErrnoException) => void): void; export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; -export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; export function write(fd: number, data: any, offset: number, encoding?: string): Promise; -export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; -export function writeFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; -export function writeFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options?: WriteFileOptions | string): Promise; +export function writeFile(file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. @@ -243,7 +243,7 @@ export function writeFile(file: string | Buffer | number, data: any, options: { * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string): Promise; -export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; +export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; export interface PathEntry { path: string; @@ -280,15 +280,18 @@ export interface ReadOptions { flag?: string; } -export interface WriteOptions { - fs?: object; - replacer?: any; - spaces?: number; +export interface WriteFileOptions { encoding?: string; flag?: string; mode?: number; } +export interface WriteOptions extends WriteFileOptions { + fs?: object; + replacer?: any; + spaces?: number; +} + export interface ReadResult { bytesRead: number; buffer: Buffer; diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index c5cfff0d9e..0acae5e2a7 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -27,7 +27,7 @@ declare namespace gapi.auth2 { * Signs in the user using the specified options. * If no option specified here, fallback to the options specified to gapi.auth2.init(). */ - signIn(options?: SigninOptions | SigninOptionsBuilder): any; + signIn(options?: SigninOptions | SigninOptionsBuilder): Promise; /** * Signs out all accounts from the application. diff --git a/types/geodesy/geodesy-tests.ts b/types/geodesy/geodesy-tests.ts index 984b8e80c2..6f6641520e 100644 --- a/types/geodesy/geodesy-tests.ts +++ b/types/geodesy/geodesy-tests.ts @@ -4,7 +4,9 @@ import { Dms, Vector3d, OsGridRef, - LatLonEllipsoidal as LatLon, LatLonSpherical } from 'geodesy'; + LatLonEllipsoidal as LatLon, LatLonSpherical, + LatLonVectors +} from 'geodesy'; /** * Mgrs @@ -165,3 +167,38 @@ LatLonSpherical.crossingParallels(point1, point2, 30); const polygon = [new LatLonSpherical(0, 0), new LatLonSpherical(1, 0), new LatLonSpherical(0, 1)]; LatLonSpherical.areaOf(polygon); // 6.18e9 m² LatLonSpherical.areaOf(polygon, 6371e3); // 6.18e9 m² + +/** + * LatLonVectors + */ +const point3 = new LatLonVectors(49.78846, -97.44306); +const point4 = new LatLonVectors(49.79822, -97.4592); +const point5 = new LatLonVectors(49.7981, -97.41371); +const point6 = new LatLonVectors(49.76851, -97.41371); +const point7 = new LatLonVectors(49.76873, -97.45954); +const point8 = new LatLonVectors(49.78846, -97.44306); +point3.toVector(); // Vector3d { x: -0.08363305717526297, y: -0.6401716454146233, z: 0.7636660108677438 } +point3.greatCircle(45); // Vector3d { x: -0.6311975610221534, y: 0.6270426835846277, z: 0.45651627782881243 } +point3.distanceTo(point4, 6371e3); // 1587.463492544562 m +point3.bearingTo(point4); // 313.1353494923952 deg +point3.midpointTo(point4); // LatLon { lat: 49.79334028019261, lon: -97.45112918683637 } +point3.intermediatePointTo(point4, 0.25); // LatLon { lat: 49.79090021013134, lon: -97.44709439015365 } +point3.intermediatePointOnChordTo(point4, 0.5); // LatLon { lat: 49.7933402801926, lon: -97.45112918683637 } +point3.destinationPoint(100, 0, 6371e3); // LatLon { lat: 49.78935932160593, lon: -97.44306000000003 } +point3.crossTrackDistanceTo(point4, point5, 6371e3); // 1080.7461902301488 m +point3.crossTrackDistanceTo(point4, 60, 6371e3); // 1519.091945034438 m +point3.alongTrackDistanceTo(point4, point5, 6371e3); // 1162.7673995854138 m +point3.alongTrackDistanceTo(point4, 60, 6371e3); // 460.86875216457025 m +point3.nearestPointOnSegment(point4, point5); // LatLon { lat: 49.79817930627353, lon: -97.44299978937423 } +point3.isBetween(point4, point5); // true + +const boundary = [point4, point5, point6, point7]; +point3.enclosedBy(boundary); // true +point3.equals(point4); // false +point3.equals(point8); // true +point3.toString('dms', 3); // 49°47′18.456″N, 097°26′35.016″W + +// Static functions +LatLonVectors.intersection(point4, point5, point3, 1); // LatLon { lat: 49.7981787830497, lon: -97.44279718554108 } +LatLonVectors.areaOf(boundary, 6371e3); // 10768180.94129682 m^2 +LatLonVectors.meanOf(boundary); // LatLon { lat: 49.783392242641824, lon: -97.43653998581752 } diff --git a/types/geodesy/index.d.ts b/types/geodesy/index.d.ts index d66de9fe3d..15a53796e0 100644 --- a/types/geodesy/index.d.ts +++ b/types/geodesy/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for geodesy 1.1 +// Type definitions for geodesy 1.2 // Project: https://github.com/chrisveness/geodesy // Definitions by: Denis Carriere // Gilbert Handy +// Harry Nicholls // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export type format = 'd' | 'dm' | 'dms'; @@ -168,3 +169,27 @@ export class LatLonSpherical { static areaOf(polygon: LatLonSpherical[], radius?: number): number; toString(format?: string, dp?: number): string; } + +export class LatLonVectors { + lat: number; + lon: number; + constructor(lat: number, lon: number); + toVector(): Vector3d; + greatCircle(bearing: number): Vector3d; + distanceTo(point: LatLonVectors, radius?: number): number; + bearingTo(point: LatLonVectors): number; + midpointTo(point: LatLonVectors): number; + intermediatePointTo(point: LatLonVectors, fraction: number): LatLonVectors; + intermediatePointOnChordTo(point: LatLonVectors, fraction: number): LatLonVectors; + destinationPoint(distance: number, bearing: number, radius?: number): LatLonVectors; + static intersection(path1start: LatLonVectors, path1brngEnd: LatLonVectors | number, path2start: LatLonVectors, path2brngEnd: LatLonVectors | number): LatLonVectors; + crossTrackDistanceTo(pathStart: LatLonVectors, pathBrngEnd: LatLonVectors | number, radius?: number): number; + alongTrackDistanceTo(pathStart: LatLonVectors, pathBrngEnd: LatLonVectors | number, radius?: number): number; + nearestPointOnSegment(point1: LatLonVectors, point2: LatLonVectors): LatLonVectors; + isBetween(point1: LatLonVectors, point2: LatLonVectors): boolean; + enclosedBy(polygon: LatLonVectors[]): boolean; + static areaOf(polygon: LatLonVectors[], radius?: number): number; + static meanOf(points: ReadonlyArray): LatLonVectors; + equals(point: LatLonVectors): boolean; + toString(format?: string, dp?: number): string; + } diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 85a7df2034..ce8c62418e 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,4 +1,10 @@ -let featureCollection: GeoJSON.FeatureCollection = { +import { + BBox, + Feature, FeatureCollection, GeometryCollection, LineString, + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryObject +} from "geojson"; + +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -34,7 +40,7 @@ let featureCollection: GeoJSON.FeatureCollection = { geometry: { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }, properties: { @@ -44,17 +50,10 @@ let featureCollection: GeoJSON.FeatureCollection = { } } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; -let featureWithPolygon: GeoJSON.Feature = { +const featureWithPolygon: Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { @@ -66,57 +65,57 @@ let featureWithPolygon: GeoJSON.Feature = { properties: null }; -let point: GeoJSON.Point = { - type: "Point", - coordinates: [100.0, 0.0] +const point: Point = { + type: "Point", + coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package -let pointCoordinates: number[] = point.coordinates; +const pointCoordinates: number[] = point.coordinates; -let lineString: GeoJSON.LineString = { - type: "LineString", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] +const lineString: LineString = { + type: "LineString", + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let polygon: GeoJSON.Polygon = { +const polygon: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }; -let polygonWithHole: GeoJSON.Polygon = { +const polygonWithHole: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], - [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]] ] }; -let multiPoint: GeoJSON.MultiPoint = { +const multiPoint: MultiPoint = { type: "MultiPoint", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let multiLineString: GeoJSON.MultiLineString = { +const multiLineString: MultiLineString = { type: "MultiLineString", coordinates: [ - [ [100.0, 0.0], [101.0, 1.0] ], - [ [102.0, 2.0], [103.0, 3.0] ] + [[100.0, 0.0], [101.0, 1.0]], + [[102.0, 2.0], [103.0, 3.0]] ] }; -let multiPolygon: GeoJSON.MultiPolygon = { +const multiPolygon: MultiPolygon = { type: "MultiPolygon", coordinates: [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], - [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }; -let geometryCollection: GeoJSON.GeometryCollection = { +const geometryCollection: GeometryCollection = { type: "GeometryCollection", geometries: [ { @@ -125,16 +124,17 @@ let geometryCollection: GeoJSON.GeometryCollection = { }, { type: "LineString", - coordinates: [ [101.0, 0.0], [102.0, 1.0] ] + coordinates: [[101.0, 0.0], [102.0, 1.0]] } ] }; -let feature: GeoJSON.Feature = { +let feature: Feature = { type: "Feature", geometry: lineString, properties: null }; + feature = { type: "Feature", geometry: polygon, @@ -172,55 +172,79 @@ featureCollection = { { type: "Feature", geometry: lineString, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: polygon, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: polygonWithHole, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPoint, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: multiLineString, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPolygon, - properties: {test: 'OK'} + properties: { test: "OK" } }, { type: "Feature", geometry: geometryCollection, - properties: {test: 'OK'} + properties: { test: "OK" } } - ], - crs: { - type: "link", - properties: { - href: "http://example.com/crs/42", - type: "proj4" - } - } + ] }; // Allow access to custom properties -const pt: GeoJSON.Feature = { - type: 'Feature', +const pt: Feature = { + type: "Feature", properties: { - foo: 'bar', - hello: 'world', + foo: "bar", + hello: "world", 1: 2 }, geometry: { - type: 'Point', + type: "Point", coordinates: [0, 0] } }; -pt.properties.foo; -pt.properties.hello; -pt.properties[1]; + +if (pt.properties) { + if (pt.properties.foo == null || pt.properties.hello == null || pt.properties[1] == null) { + throw TypeError("Properties should not be null or undefined."); + } +} else { + throw TypeError("Feature should have a 'properties' property."); +} + +// Optional generic for properties + +interface TestProperty { + foo: "bar" | "baz"; + hello: string; +} + +const testProps: TestProperty = { + foo: "bar", + hello: "world" +}; + +const typedPropertiesFeature: Feature = { + type: "Feature", + properties: testProps, + geometry: { + type: "Point", + coordinates: [0, 0] + } +}; + +const typedPropertiesFeatureCollection: FeatureCollection = { + type: "FeatureCollection", + features: [typedPropertiesFeature] +}; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index 9c55aa19c9..e6783255eb 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,121 +1,165 @@ -// Type definitions for GeoJSON Format Specification Revision 1.0 -// Project: http://geojson.org/ +// Type definitions for geojson 7946.0 +// Project: https://geojson.org/ // Definitions by: Jacob Bruun +// Arne Schubert +// Jeff Jacobson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems +// are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} export as namespace GeoJSON; -/*** -* http://geojson.org/geojson-spec.html#geojson-objects -*/ -export interface GeoJsonObject { - type: string; - bbox?: number[]; - crs?: CoordinateReferenceSystem; -} - -/*** -* http://geojson.org/geojson-spec.html#positions -*/ -export type Position = number[]; - -/*** -* http://geojson.org/geojson-spec.html#geometry-objects -*/ -export interface DirectGeometryObject extends GeoJsonObject { - coordinates: Position[][][] | Position[][] | Position[] | Position; -} /** - * GeometryObject supports geometry collection as well + * The valid values for the "type" property of GeoJSON geometry objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 */ -export type GeometryObject = DirectGeometryObject | GeometryCollection; +export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | + "MultiPolygon" | "GeometryCollection"; -/*** -* http://geojson.org/geojson-spec.html#point -*/ -export interface Point extends DirectGeometryObject { - type: 'Point'; +/** + * The value values for the "type" property of GeoJSON Objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; + +/** + * Bounding box + * https://tools.ietf.org/html/rfc7946#section-5 + */ +export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; + +/** + * A Position is an array of coordinates. + * https://tools.ietf.org/html/rfc7946#section-3.1.1 + * Array should contain between two and three elements. + * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), + * but the current specification only allows X, Y, and (optionally) Z to be defined. + */ +export type Position = number[]; // [number, number] | [number, number, number]; + +/** + * The base GeoJSON object. + * https://tools.ietf.org/html/rfc7946#section-3 + * The GeoJSON specification also allows foreign members + * (https://tools.ietf.org/html/rfc7946#section-6.1) + * Developers should use "&" type in TypeScript or extend the interface + * to add these foreign members. + */ +export interface GeoJsonObject { + // Don't include foreign members directly into this type def. + // in order to preserve type safety. + // [key: string]: any; + /** + * Specifies the type of GeoJSON object. + */ + type: GeoJsonTypes; + /** + * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * https://tools.ietf.org/html/rfc7946#section-5 + */ + bbox?: BBox; +} + +/** + * A geometry object. + * https://tools.ietf.org/html/rfc7946#section-3 + */ +export interface GeometryObject extends GeoJsonObject { + type: GeoJsonGeometryTypes; +} + +/** + * Point geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.2 + */ +export interface Point extends GeometryObject { + type: "Point"; coordinates: Position; } -/*** -* http://geojson.org/geojson-spec.html#multipoint -*/ -export interface MultiPoint extends DirectGeometryObject { - type: 'MultiPoint'; +/** + * MultiPoint geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.3 + */ +export interface MultiPoint extends GeometryObject { + type: "MultiPoint"; coordinates: Position[]; } -/*** -* http://geojson.org/geojson-spec.html#linestring -*/ -export interface LineString extends DirectGeometryObject { - type: 'LineString'; +/** + * LineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.4 + */ +export interface LineString extends GeometryObject { + type: "LineString"; coordinates: Position[]; } -/*** -* http://geojson.org/geojson-spec.html#multilinestring -*/ -export interface MultiLineString extends DirectGeometryObject { - type: 'MultiLineString'; +/** + * MultiLineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.5 + */ +export interface MultiLineString extends GeometryObject { + type: "MultiLineString"; coordinates: Position[][]; } -/*** -* http://geojson.org/geojson-spec.html#polygon -*/ -export interface Polygon extends DirectGeometryObject { - type: 'Polygon'; +/** + * Polygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.6 + */ +export interface Polygon extends GeometryObject { + type: "Polygon"; coordinates: Position[][]; } -/*** -* http://geojson.org/geojson-spec.html#multipolygon -*/ -export interface MultiPolygon extends DirectGeometryObject { - type: 'MultiPolygon'; +/** + * MultiPolygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.7 + */ +export interface MultiPolygon extends GeometryObject { + type: "MultiPolygon"; coordinates: Position[][][]; } -/*** -* http://geojson.org/geojson-spec.html#geometry-collection -*/ -export interface GeometryCollection extends GeoJsonObject { - type: 'GeometryCollection'; - geometries: GeometryObject[]; +/** + * Geometry Collection + * https://tools.ietf.org/html/rfc7946#section-3.1.8 + */ +export interface GeometryCollection extends GeometryObject { + type: "GeometryCollection"; + geometries: Array; } -/*** -* https://tools.ietf.org/html/rfc7946#section-3.2 -*/ -export interface Feature extends GeoJsonObject { - type: 'Feature'; - geometry: T; - properties: any; +export type GeoJsonProperties = { [name: string]: any; } | null; + +/** + * A feature object which contains a geometry and associated properties. + * https://tools.ietf.org/html/rfc7946#section-3.2 + */ +export interface Feature extends GeoJsonObject { + type: "Feature"; + /** + * The feature's geometry + */ + geometry: G | null; + /** + * A value that uniquely identifies this feature in a + * https://tools.ietf.org/html/rfc7946#section-3.2. + */ id?: string | number; + /** + * Properties associated with this feature. + */ + properties: P | null; } -/*** -* http://geojson.org/geojson-spec.html#feature-collection-objects -*/ -export interface FeatureCollection extends GeoJsonObject { - type: 'FeatureCollection'; - features: Array>; -} - -/*** -* http://geojson.org/geojson-spec.html#coordinate-reference-system-objects -*/ -export interface CoordinateReferenceSystem { - type: string; - properties: any; -} - -export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { name: string }; -} - -export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { href: string; type: string }; +/** + * A collection of feature objects. + * https://tools.ietf.org/html/rfc7946#section-3.3 + */ +export interface FeatureCollection extends GeoJsonObject { + features: Array>; } diff --git a/types/geojson2osm/index.d.ts b/types/geojson2osm/index.d.ts index 08bc529cc0..39b03de5bf 100644 --- a/types/geojson2osm/index.d.ts +++ b/types/geojson2osm/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Rub21/geojson2osm // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index 02654491b4..c929323764 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -338,6 +338,7 @@ outVal = quat.squaredLength(quatA); outVal = quat.sqrLen(quatA); outQuat = quat.normalize(outQuat, quatA); outVal = quat.dot(quatA, quatB); +outQuat = quat.fromEuler(outQuat, deg90, deg90, deg90); outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); outQuat = quat.invert(outQuat, quatA); diff --git a/types/gl-matrix/index.d.ts b/types/gl-matrix/index.d.ts index e698f2d4bb..cad714796d 100644 --- a/types/gl-matrix/index.d.ts +++ b/types/gl-matrix/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for gl-matrix 2.3.2 +// Type definitions for gl-matrix 2.4 // Project: https://github.com/toji/gl-matrix // Definitions by: Mattijs Kneppers , based on definitions by Tat // Nikolay Babanov // Austin Martin +// Wayne Langman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'gl-matrix' { @@ -2943,6 +2944,17 @@ declare module 'gl-matrix' { */ public static dot(a: quat, b: quat): number; + /** + * Creates a quaternion from the given euler angle x, y, z. + * + * @param {quat} out the receiving quaternion + * @param {number} x Angle to rotate around X axis in degrees. + * @param {number} y Angle to rotate around Y axis in degrees. + * @param {number} z Angle to rotate around Z axis in degrees. + * @returns {quat} out + */ + public static fromEuler(out: quat, x: number, y: number, z: number): quat; + /** * Performs a linear interpolation between two quat's * diff --git a/types/glob-parent/glob-parent-tests.ts b/types/glob-parent/glob-parent-tests.ts new file mode 100644 index 0000000000..13c7df5d59 --- /dev/null +++ b/types/glob-parent/glob-parent-tests.ts @@ -0,0 +1,4 @@ +import globParent = require('glob-parent'); + +// $ExpectType string +globParent('*.js'); diff --git a/types/glob-parent/index.d.ts b/types/glob-parent/index.d.ts new file mode 100644 index 0000000000..052bbcd1db --- /dev/null +++ b/types/glob-parent/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for glob-parent 3.1 +// Project: https://github.com/es128/glob-parent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function globParent(pattern: string): string; + +export = globParent; diff --git a/types/glob-parent/tsconfig.json b/types/glob-parent/tsconfig.json new file mode 100644 index 0000000000..1e74b9bc82 --- /dev/null +++ b/types/glob-parent/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "glob-parent-tests.ts" + ] +} diff --git a/types/glob-parent/tslint.json b/types/glob-parent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/glob-parent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts b/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts new file mode 100644 index 0000000000..ca6d874fa4 --- /dev/null +++ b/types/google-apps-script-oauth2/google-apps-script-oauth2-tests.ts @@ -0,0 +1,32 @@ +// Examples from https://github.com/googlesamples/apps-script-oauth2 + +/** + * Create the OAuth2 service. + */ +function getDriveService() { + return OAuth2.createService('drive') + .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') + .setTokenUrl('https://accounts.google.com/o/oauth2/token') + .setClientId('xxx') + .setClientSecret('yyy') + .setCallbackFunction('authCallback') + .setPropertyStore(PropertiesService.getUserProperties()) + .setScope('https://www.googleapis.com/auth/drive') + .setParam('login_hint', Session.getActiveUser().getEmail()) + .setParam('access_type', 'offline') + .setParam('approval_prompt', 'force') + ; +} + +/** + * Handle the callback. + */ +function authCallback(request: any) { + const driveService = getDriveService(); + const isAuthorized = driveService.handleCallback(request); + if (isAuthorized) { + Logger.log('success'); + } else { + Logger.log('denied'); + } +} diff --git a/types/google-apps-script-oauth2/index.d.ts b/types/google-apps-script-oauth2/index.d.ts new file mode 100644 index 0000000000..d5d9022849 --- /dev/null +++ b/types/google-apps-script-oauth2/index.d.ts @@ -0,0 +1,197 @@ +// Type definitions for google-apps-script-oauth2 24.0 +// Project: https://github.com/googlesamples/apps-script-oauth2 +// Definitions by: dhayab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +declare namespace GoogleAppsScriptOAuth2 { + interface OAuth2 { + /** + * The supported locations for passing the state parameter. + */ + STATE_PARAMETER_LOCATION: typeof StateParameterLocation; + /** + * The supported formats for the returned OAuth2 token. + */ + TOKEN_FORMAT: typeof TokenFormat; + /** + * Creates a new OAuth2 service with the name specified. + * It's usually best to create and configure your service once at the start of your script, + * and then reference them during the different phases of the authorization flow. + */ + createService(serviceName: string): OAuth2Service; + /** + * Returns the redirect URI that will be used for a given script. + * Often this URI needs to be entered into a configuration screen of your OAuth provider. + */ + getRedirectUri(scriptId: string): string; + } + + interface OAuth2Service { + /** + * Gets an access token for this service. + * This token can be used in HTTP requests to the service's endpoint. + * This method will throw an error if the user's access was not granted or has expired. + */ + getAccessToken(): string; + /** + * Gets the authorization URL. + * The first step in getting an OAuth2 token is to have the user visit this URL + * and approve the authorization request. The user will then be redirected back to your + * application using callback function name specified, so that the flow may continue. + */ + getAuthorizationUrl(): string; + /** + * Gets the last error that occurred this execution when trying to + * automatically refresh or generate an access token. + */ + getLastError(): any; + /** + * Returns the redirect URI that will be used for this service. + * Often this URI needs to be entered into a configuration screen of your OAuth provider. + */ + getRedirectUri(): string; + /** + * Gets the token from the service's property store or cache. + */ + getToken(): object | null; + /** + * Completes the OAuth2 flow using the request data passed in to the callback function. + */ + handleCallback(callbackRequest: object): boolean; + /** + * Determines if the service has access (has been authorized and hasn't expired). + * If offline access was granted and the previous token has expired this method attempts + * to generate a new token. + */ + hasAccess(): boolean; + /** + * Refreshes a token that has expired. + * This is only possible if offline access was requested when the token was authorized. + */ + refresh(): void; + /** + * Resets the service, removing access and requiring the service to be re-authorized. + */ + reset(): void; + /** + * Sets the service's authorization base URL (required). + * For Google services this URL should be `https://accounts.google.com/o/oauth2/auth`. + */ + setAuthorizationBaseUrl(authorizationBaseUrl: string): OAuth2Service; + /** + * Sets the cache to use when persisting credentials (optional). + * Using a cache will reduce the need to read from the property store and may increase + * performance. In most cases this should be a private cache, but a public cache may be + * appropriate if you want to share access across users. + */ + setCache(cache: GoogleAppsScript.Cache.Cache): OAuth2Service; + /** + * Sets the name of the authorization callback function (required). + * This is the function that will be called when the user completes the authorization flow + * on the service provider's website. The callback accepts a request parameter, which + * should be passed to this service's `handleCallback()` method to complete the process. + */ + setCallbackFunction(callbackFunctionName: string): OAuth2Service; + /** + * Sets the client ID to use for the OAuth flow (required). + * You can create client IDs in the "Credentials" section of a Google Developers Console + * project. Although you can use any project with this library, it may be convinient to use + * the project that was created for your script. These projects are not visible if you + * visit the console directly, but you can access it by click on the menu item + * "Resources > Advanced Google services" in the Script Editor, and then click on the link + * "Google Developers Console" in the resulting dialog. + */ + setClientId(clientId: string): OAuth2Service; + /** + * Sets the client secret to use for the OAuth flow (required). + * See the documentation for `setClientId()` for more information on how to create client IDs and secrets. + */ + setClientSecret(clientSecret: string): OAuth2Service; + /** + * Sets number of minutes that a token obtained through Service Account authorization should be valid. Default: 60 minutes. + */ + setExpirationMinutes(expirationMinutes: string): OAuth2Service; + /** + * Sets the issuer (iss) value to use for Service Account authorization. + * If not set the client ID will be used instead. + */ + setIssuer(issuer: string): OAuth2Service; + /** + * Sets an additional parameter to use when constructing the authorization URL (optional). + * See the documentation for your service provider for information on what parameter values they support. + */ + setParam(name: string, value: string): OAuth2Service; + /** + * Sets the private key to use for Service Account authorization. + */ + setPrivateKey(privateKey: string): OAuth2Service; + /** + * Sets the property store to use when persisting credentials (required). + * In most cases this should be user properties, but document or script properties may be appropriate + * if you want to share access across users. + */ + setPropertyStore(propertyStore: GoogleAppsScript.Properties.Properties): OAuth2Service; + /** + * Sets the scope or scopes to request during the authorization flow (optional). + * If the scope value is an array it will be joined using the separator before being sent to the server, + * which is is a space character by default. + */ + setScope(scope: string | string[], separator?: string): OAuth2Service; + /** + * Sets the subject (sub) value to use for Service Account authorization. + */ + setSubject(subject: string): OAuth2Service; + /** + * Sets the format of the returned token. Default: `OAuth2.TOKEN_FORMAT.JSON`. + */ + setTokenFormat(tokenFormat: TokenFormat): OAuth2Service; + /** + * Sets the additional HTTP headers that should be sent when retrieving or refreshing the access token. + */ + setTokenHeaders(tokenHeaders: { [key: string]: string }): OAuth2Service; + /** + * Sets an additional function to invoke on the payload of the access token request. + */ + setTokenPayloadHandler(tokenHandler: (tokenPayload: TokenPayload) => object): OAuth2Service; + /** + * Sets the service's token URL (required). + * For Google services this URL should be `https://accounts.google.com/o/oauth2/token`. + */ + setTokenUrl(tokenUrl: string): OAuth2Service; + } + + enum StateParameterLocation { + /** + * Pass the state parameter in the authorization URL. + */ + AUTHORIZATION_URL, + /** + * Pass the state token in the redirect URL, as a workaround for APIs that don't support the state parameter. + */ + REDIRECT_URL, + } + + enum TokenFormat { + /** + * JSON format, for example `{"access_token": "..."}`. + */ + JSON, + /** + * Form URL-encoded, for example `access_token=...`. + */ + FORM_URL_ENCODED, + } + + interface TokenPayload { + code: string; + client_id: string; + client_secret: string; + redirect_uri: string; + grant_type: string; + } +} + +declare var OAuth2: GoogleAppsScriptOAuth2.OAuth2; diff --git a/types/google-apps-script-oauth2/tsconfig.json b/types/google-apps-script-oauth2/tsconfig.json new file mode 100644 index 0000000000..bc09dd70b9 --- /dev/null +++ b/types/google-apps-script-oauth2/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-apps-script-oauth2-tests.ts" + ] +} diff --git a/types/google-apps-script-oauth2/tslint.json b/types/google-apps-script-oauth2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-apps-script-oauth2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-apps-script/google-apps-script.card.d.ts b/types/google-apps-script/google-apps-script.card.d.ts new file mode 100644 index 0000000000..62d497eb4f --- /dev/null +++ b/types/google-apps-script/google-apps-script.card.d.ts @@ -0,0 +1,657 @@ +// Type definitions for Google Apps Script 2017-10-30 +// Project: https://developers.google.com/apps-script/ +// Definitions by: dhayab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GoogleAppsScript { + export module Card { + export interface Action { + /** + * Sets the name of the callback function to be called. + */ + setFunctionName(functionName: string): Action; + /** + * Sets the loading indicator that displays while the action is in progress. + */ + setLoadIndicator(loadIndicator: LoadIndicator): Action; + /** + * Allows custom parameters to be passed to the callback function. + */ + setParameters(parameters: { [key: string]: string }): Action; + } + + export interface ActionEvent { + messageMetadata: { + /** + * An access token. You can use this to enable access to user data using temporary Gmail add-on scopes. + */ + accessToken: string; + /** + * The message ID of the thread open in the Gmail UI. + */ + messageId: string; + } + /** + * Indicates where the event originates (web, iOS, or Android). + */ + clientPlatform: string; + /** + * The current values of all form widgets in the card, restricted to one value per widget. The keys are the string IDs associated with the widgets. + * + * The event object provides `formInput` as a convenience for when you need to read data from multiple widgets with expected singular values, such as text inputs and switches. + * + * For multi-valued widgets such as checkboxes, you can read each value from `formInputs` instead. + */ + formInput: { [key: string]: string }; + /** + * The current values of widgets in the card, presented in arrays. The keys are the string IDs associated with the widget. + * + * For single-valued widgets, the value is presented in a single-element array. For multi-valued widgets such as checkboxes, all the values are presented in an array. + */ + formInputs: { [key: string]: string[] }; + /** + * Any additional parameters you supply to the `Action` using `Action.setParameters()`. + */ + parameters: { [key: string]: string }; + } + + export interface ActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ActionResponseBuilder { + /** + * Builds the current action response and validates it. + */ + build(): ActionResponse; + /** + * Sets the response to `Navigation` action. + */ + setNavigation(navigation: Navigation): ActionResponseBuilder; + /** + * Sets the notification to display when the action is activated. + */ + setNotification(notification: Notification): ActionResponseBuilder; + /** + * Sets the URL to navigate to when the action is activated. + */ + setOpenLink(openLink: OpenLink): ActionResponseBuilder; + } + + export interface AuthorizationAction { + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authorizationUrl: string): AuthorizationAction; + } + + export interface AuthorizationException { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Sets the authorization URL that user is taken to from the authorization prompt. + */ + setAuthorizationUrl(authUrl: string): AuthorizationException; + /** + * The name of a function to call to generate a custom authorization prompt. + */ + setCustomUiCallback(callback: string): AuthorizationException; + /** + * Sets the name that is displayed to the user when asking for authorization. + */ + setResourceDisplayName(name: string): AuthorizationException; + /** + * Triggers this exception to be thrown. + */ + throwException(): void; + } + + interface Button extends Widget { + /** + * Sets an authorization action that opens a URL to the authorization flow when the object is clicked. + */ + setAuthorizationAction(action: AuthorizationAction): T; + /** + * Sets an action that composes a draft email when the object is clicked. + */ + setComposeAction(action: Action, composedEmailType: ComposedEmailType): T; + /** + * Sets an action that executes when the object is clicked. + */ + setOnClickAction(action: Action): T; + /** + * Sets an action that opens a URL in a tab when the object is clicked. + */ + setOnClickOpenLinkAction(action: Action): T; + /** + * Sets a URL to be opened when the object is clicked. + */ + setOpenLink(openLink: OpenLink): T; + } + + export interface ButtonSet extends Widget { + /** + * Adds a button. + */ + addButton(button: Button): ButtonSet; + } + + export interface Card { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface CardAction extends Button { + /** + * Sets the menu text for this action. + */ + setText(text: string): CardAction; + } + + export interface CardBuilder { + /** + * Adds a CardAction to this Card. + */ + addCardAction(cardAction: CardAction): CardBuilder; + /** + * Adds a section to this card. + */ + addSection(section: CardSection): CardBuilder; + /** + * Builds the current card and validates it. + */ + build(): Card; + /** + * Sets the header for this card. + */ + setHeader(cardHeader: CardHeader): CardBuilder; + /** + * Sets the name for this card. + */ + setName(name: string): CardBuilder; + } + + export interface CardHeader { + /** + * Sets the alternative text for the header image. + */ + setImageAltText(imageAltText: string): CardHeader; + /** + * Sets the cropping of the icon in the card header. + */ + setImageStyle(imageStyle: ImageStyle): CardHeader; + /** + * Sets the image to use in the header by providing its URL. + */ + setImageUrl(imageUrl: string): CardHeader; + /** + * Sets the subtitle of the card header. + */ + setSubtitle(subtitle: string): CardHeader; + /** + * Sets the title of the card header. + */ + setTitle(title: string): CardHeader; + } + + export interface CardSection { + /** + * Adds the given widget to this section. + */ + addWidget(widget: Widget): CardSection; + /** + * Sets whether the section can be collapsed. + */ + setCollapsible(collapsible: boolean): CardSection; + /** + * Sets the header of the section. + */ + setHeader(header: string): CardSection; + /** + * Sets the number of widgets that are still shown when this section is collapsed. + */ + setNumUncollapsibleWidgets(numUncollapsibleWidgets: Integer): CardSection; + } + + export interface CardService { + /** + * Specifies whether the composed email is a standalone or reply draft. + */ + ComposedEmailType: typeof ComposedEmailType; + /** + * Predefined icons that can be used in various UI objects, such as ImageButton or KeyValue widgets. + */ + Icon: typeof Icon; + /** + * Defines an image cropping style. + */ + ImageStyle: typeof ImageStyle; + /** + * Specifies the type of loading or progress indicator to display while an Action is being processed. + */ + LoadIndicator: typeof LoadIndicator; + /** + * Type of notification to show. + */ + NotificationType: typeof NotificationType; + /** + * Specifies what to do when a URL opened through an OpenLink is closed. + * + * When a link is opened, the client either forgets about it or waits until the window is closed. The implementation depends on the client platform capabilities. OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OnClose: typeof OnClose; + /** + * Specifies how to open a URL. + * + * The client can open a URL as either a full size window (if that is the frame used by the client), or an overlay (such as a pop-up). The implementation depends on the client platform capabilities, and the value selected may be ignored if the client does not support it. FULL_SIZE is supported by all clients. + * + * Using OnClose may cause OpenAs to be ignored; if the client platform cannot support both selected values together, OnClose takes precedence. + */ + OpenAs: typeof OpenAs; + /** + * Type of selection input. + */ + SelectionInputType: typeof SelectionInputType; + /** + * Creates a new `Action`. + */ + newAction(): Action; + /** + * Creates a new `ActionResponseBuilder`. + */ + newActionResponseBuilder(): ActionResponseBuilder; + /** + * Creates a new `AuthorizationAction`. + */ + newAuthorizationAction(): AuthorizationAction; + /** + * Creates a new `AuthorizationException`. + */ + newAuthorizationException(): AuthorizationException; + /** + * Creates a new `ButtonSet`. + */ + newButtonSet(): ButtonSet; + /** + * Creates a new `CardAction`. + */ + newCardAction(): CardAction; + /** + * Creates a new `CardBuilder`. + */ + newCardBuilder(): CardBuilder; + /** + * Creates a new `CardHeader`. + */ + newCardHeader(): CardHeader; + /** + * Creates a new `CardSection`. + */ + newCardSection(): CardSection; + /** + * Creates a new `ComposeActionResponseBuilder`. + */ + newComposeActionResponseBuilder(): ComposeActionResponseBuilder; + /** + * Creates a new `Image`. + */ + newImage(): Image; + /** + * Creates a new `ImageButton`. + */ + newImageButton(): ImageButton; + /** + * Creates a new `KeyValue`. + */ + newKeyValue(): KeyValue; + /** + * Creates a new `Navigation`. + */ + newNavigation(): Navigation; + /** + * Creates a new `Notification`. + */ + newNotification(): Notification; + /** + * Creates a new `OpenLink`. + */ + newOpenLink(): OpenLink; + /** + * Creates a new `SelectionInput`. + */ + newSelectionInput(): SelectionInput; + /** + * Creates a new `Suggestions`. + */ + newSuggestions(): Suggestions; + /** + * Creates a new `SuggestionsResponseBuilder`. + */ + newSuggestionsResponseBuilder(): SuggestionsResponseBuilder; + /** + * Creates a new `Switch`. + */ + newSwitch(): Switch; + /** + * Creates a new `TextButton`. + */ + newTextButton(): TextButton; + /** + * Creates a new `TextInput`. + */ + newTextInput(): TextInput; + /** + * Creates a new `TextParagraph`. + */ + newTextParagraph(): TextParagraph; + /** + * Creates a new `UniversalActionResponseBuilder`. + */ + newUniversalActionResponseBuilder(): UniversalActionResponseBuilder; + } + + export interface ComposeActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface ComposeActionResponseBuilder { + /** + * Builds the current compose action response and validates it. + */ + build(): ComposeActionResponse; + /** + * Sets the draft `GmailMessage` created using `GmailMessage.createDraftReply(body)` or similar functions. + */ + setGmailDraft(draft: Gmail.GmailDraft): ComposeActionResponseBuilder; + } + + export interface Image extends Button { + /** + * Sets the alternative text of the image for accessibility. + */ + setAltText(altText: string): Image; + /** + * Sets the URL of the image. + */ + setImageUrl(url: string): Image; + } + + export interface ImageButton extends Button { + /** + * Sets the alternative text of the button for accessibility. + */ + setAltText(altText: string): ImageButton; + /** + * Sets a predefined Icon to display on the button. + */ + setIcon(icon: Icon): ImageButton; + /** + * Sets the URL of an image to use as this button's icon. + */ + setIconUrl(url: string): ImageButton; + } + + export interface KeyValue extends Button { + /** + * Sets the label text to be used as the key. + */ + setBottomLabel(text: string): KeyValue; + /** + * Sets the Button that is displayed to the right of the context. + */ + setButton(button: Button): KeyValue; + /** + * Sets the text to be used as the value. + */ + setContent(text: string): KeyValue; + /** + * Sets the icon to be used as the key. + */ + setIcon(icon: Icon): KeyValue; + /** + * Sets the alternative text for the icon. + */ + setIconAltText(altText: string): KeyValue; + /** + * Sets the URL of the icon to be used as the key. + */ + setIconUrl(url: string): KeyValue; + /** + * Sets whether the value text should be displayed on a single line or multiple lines. + */ + setMultiline(multiline: boolean): KeyValue; + /** + * Sets the Switch that is displayed to the right of the content. + */ + setSwitch(switchToSet: Switch): KeyValue; + /** + * Sets the label text to be used as the key. + */ + setTopLabel(text: string): KeyValue; + } + + export interface Navigation { + /** + * Pops a card from the navigation stack. + */ + popCard(): Navigation; + /** + * Pops to the specified card by its card name. + */ + popToNamedCard(cardName: string): Navigation; + /** + * Pops the card stack to the root card. + */ + popToRoot(): Navigation; + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + /** + * Pushes the given card onto the stack. + */ + pushCard(card: Card): Navigation; + /** + * Does an in-place replacement of the current card. + */ + updateCard(card: Card): Navigation; + } + + export interface Notification { + /** + * Sets the text to show in the notification. + */ + setText(text: string): Notification; + /** + * Sets the notification type to show. + */ + setType(type: NotificationType): Notification; + } + + export interface OpenLink { + /** + * Sets the behavior of the URL action when the URL window or tab is closed. + */ + setOnClose(onClose: OnClose): OpenLink; + /** + * Sets the behavior of URL when it is opened. + */ + setOpenAs(openAs: OpenAs): OpenLink; + /** + * Sets the URL to be opened. + */ + setUrl(url: string): OpenLink; + } + + export interface SelectionInput extends Widget { + /** + * Adds a new item that can be selected. + */ + addItem(text: Object, value: Object, selected: boolean): SelectionInput; + /** + * Sets the key that identifies this selection input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): SelectionInput; + /** + * Sets an Action to be performed whenever the selection input changes. + */ + setOnChangeAction(action: Action): SelectionInput; + /** + * Sets the title to be shown ahead of the input field. + */ + setTitle(title: string): SelectionInput; + /** + * Sets the type of this input. + */ + setType(type: SelectionInputType): SelectionInput; + } + + export interface Suggestions { + /** + * Add a text suggestion. + */ + addSuggestion(suggestion: string): Suggestions; + /** + * Add a list of text suggestions. + */ + addSuggestions(suggestions: string[]): Suggestions; + } + + export interface SuggestionsResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface SuggestionsResponseBuilder { + /** + * Builds the current suggestions response and validates it. + */ + build(): SuggestionsResponse; + /** + * Sets the suggestions used in auto complete in text fields. + */ + setSuggestions(suggestions: Suggestions): SuggestionsResponseBuilder; + } + + export interface Switch extends Widget { + /** + * Sets the key that identified this switch in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): Switch; + /** + * Sets the action to take when the switch is toggled. + */ + setOnChangeAction(action: Action): Switch; + /** + * Sets whether this switch should start as selected or unselected. + */ + setSelected(selected: boolean): Switch; + /** + * Sets the value that is sent as the form input when this switch is toggled on. + */ + setValue(value: string): Switch; + } + + export interface TextButton extends Button { + /** + * Sets the text to be displayed on the button. + */ + setText(text: string): TextButton; + } + + export interface TextInput extends Widget { + /** + * Sets the key that identifies this text input in the event object that is generated when there is a UI interaction. + */ + setFieldName(fieldName: string): TextInput; + /** + * Sets a hint for the text input. + */ + setHint(hint: string): TextInput; + /** + * Sets whether the input text shows on one line or multiple lines. + */ + setMultiline(multiline: boolean): TextInput; + /** + * Sets an action to be performed whenever the text input changes. + */ + setOnChangeAction(action: Action): TextInput; + /** + * Sets the suggestions for autocompletion in the text field. + */ + setSuggestions(suggestions: Suggestions): TextInput; + /** + * Sets the callback action to fetch suggestions based on user input for autocompletion. + */ + setSuggestionsAction(suggestionsAction: Action): TextInput + /** + * Sets the title to be shown above the input field. + */ + setTitle(title: string): TextInput; + /** + * Sets the pre-filled value to be set in the input field. + */ + setValue(value: string): TextInput; + } + + export interface TextParagraph extends Widget { + /** + * Sets the text of the paragraph. + */ + setText(text: string): TextParagraph; + } + + export interface UniversalActionResponse { + /** + * Prints the JSON representation of this object. + */ + printJson(): string; + } + + export interface UniversalActionResponseBuilder { + /** + * Builds the current universal action response and validates it. + */ + build(): UniversalActionResponse; + /** + * Displays the add-on with the specified cards. + */ + displayAddOnCards(cardObjects: Card[]): UniversalActionResponseBuilder; + /** + * Sets the URL to open when the universal action is selected. + */ + setOpenLink(openLink: OpenLink): UniversalActionResponseBuilder; + } + + export interface Widget { } + + export enum ComposedEmailType { REPLY_AS_DRAFT, STANDALONE_DRAFT } + export enum Icon { NONE, AIRPLANE, BOOKMARK, BUS, CAR, CLOCK, CONFIRMATION_NUMBER_ICON, DOLLAR, DESCRIPTION, EMAIL, EVENT_PERFORMER, EVENT_SEAT, FLIGHT_ARRIVAL, FLIGHT_DEPARTURE, HOTEL, HOTEL_ROOM_TYPE, INVITE, MAP_PIN, MEMBERSHIP, MULTIPLE_PEOPLE, OFFER, PERSON, PHONE, RESTAURANT_ICON, SHOPPING_CART, STAR, STORE, TICKET, TRAIN, VIDEO_CAMERA, VIDEO_PLAY } + export enum ImageStyle { SQUARE, CIRCLE } + export enum LoadIndicator { SPINNER, NONE } + export enum NotificationType { INFO, ERROR, WARNING } + export enum OnClose { NOTHING, RELOAD_ADD_ON } + export enum OpenAs { FULL_SIZE, OVERLAY } + export enum SelectionInputType { CHECK_BOX, RADIO_BUTTON, DROPDOWN } + } +} + +/** + * CardService provides the ability to create generic cards used across different Google extensibility products, such as [Gmail add-ons](https://developers.google.com/gmail/add-ons). + */ +declare var CardService: GoogleAppsScript.Card.CardService; diff --git a/types/google-apps-script/google-apps-script.gmail.d.ts b/types/google-apps-script/google-apps-script.gmail.d.ts index 41be4dbb56..4967f53394 100644 --- a/types/google-apps-script/google-apps-script.gmail.d.ts +++ b/types/google-apps-script/google-apps-script.gmail.d.ts @@ -1,6 +1,7 @@ // Type definitions for Google Apps Script 2017-05-12 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// dhayab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,12 +13,16 @@ declare namespace GoogleAppsScript { * Provides access to Gmail threads, messages, and labels. */ export interface GmailApp { + createDraft(recipient: string, subject: string, body: string): GmailDraft; + createDraft(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; createLabel(name: string): GmailLabel; deleteLabel(label: GmailLabel): GmailApp; getAliases(): string[]; getChatThreads(): GmailThread[]; getChatThreads(start: Integer, max: Integer): GmailThread[]; + getDraft(draftId: string): GmailDraft; getDraftMessages(): GmailMessage[]; + getDrafts(): GmailDraft[]; getInboxThreads(): GmailThread[]; getInboxThreads(start: Integer, max: Integer): GmailThread[]; getInboxUnreadCount(): Integer; @@ -68,6 +73,7 @@ declare namespace GoogleAppsScript { search(query: string, start: Integer, max: Integer): GmailThread[]; sendEmail(recipient: string, subject: string, body: string): GmailApp; sendEmail(recipient: string, subject: string, body: string, options: Object): GmailApp; + setCurrentMessageAccessToken(accessToken: string): void; starMessage(message: GmailMessage): GmailApp; starMessages(messages: GmailMessage[]): GmailApp; unstarMessage(message: GmailMessage): GmailApp; @@ -112,6 +118,72 @@ declare namespace GoogleAppsScript { getAllBlobs(): Base.Blob[]; } + export interface GmailDraft { + /** + * Deletes this draft message. + */ + deleteDraft(): void; + /** + * Gets the ID of this draft message. + */ + getId(): string; + /** + * Returns a GmailMessage representing this draft. + */ + getMessage(): GmailMessage; + /** + * Returns the ID of the `GmailMessage` representing this draft. + */ + getMessageId(): string; + /** + * Sends this draft email message. + */ + send(): GmailMessage; + /** + * Replaces the contents of this draft message. + */ + update(recipient: string, subject: string, body: string): GmailDraft; + /** + * Replaces the contents of this draft message using optional arguments. + */ + update(recipient: string, subject: string, body: string, options: GmailDraftOptions): GmailDraft; + } + + export type GmailDraftOptions = { + /** + * An array of files to send with the email. + */ + attachments?: Base.BlobSource[]; + /** + * A comma-separated list of email addresses to BCC. + */ + bcc?: string; + /** + * A comma-separated list of email addresses to CC. + */ + cc?: string; + /** + * The address that the email should be sent from, which must be one of the values returned by `GmailApp.getAliases()`. + */ + from?: string; + /** + * If set, devices capable of rendering HTML will use it instead of the required body argument; you can add an optional `inlineImages` field in HTML body if you have inlined images for your email. + */ + htmlBody?: string; + /** + * A JavaScript object containing a mapping from image key (`String`) to image data (`BlobSource`) ; this assumes that the `htmlBody` parameter is used and contains references to these images in the format ``. + */ + inlineImages?: { [imageKey: string]: Base.BlobSource }; + /** + * The name of the sender of the email (default: the user's name). + */ + name?: string; + /** + * An email address to use as the default reply-to address (default: the user's email address). + */ + replyTo?: string; + } + /** * A user-created label in a user's Gmail account. */ @@ -131,6 +203,10 @@ declare namespace GoogleAppsScript { * A message in a user's Gmail account. */ export interface GmailMessage { + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; forward(recipient: string): GmailMessage; forward(recipient: string, options: Object): GmailMessage; getAttachments(): GmailAttachment[]; @@ -169,6 +245,10 @@ declare namespace GoogleAppsScript { */ export interface GmailThread { addLabel(label: GmailLabel): GmailThread; + createDraftReply(body: string): GmailDraft; + createDraftReply(body: string, options: GmailDraftOptions): GmailDraft; + createDraftReplyAll(body: string): GmailDraft; + createDraftReplyAll(body: string, options: GmailDraftOptions): GmailDraft; getFirstMessageSubject(): string; getId(): string; getLabels(): GmailLabel[]; diff --git a/types/google-apps-script/index.d.ts b/types/google-apps-script/index.d.ts index f80598c391..0e4ca164a9 100644 --- a/types/google-apps-script/index.d.ts +++ b/types/google-apps-script/index.d.ts @@ -7,6 +7,7 @@ /// /// /// +/// /// /// /// diff --git a/types/google-cloud__datastore/index.d.ts b/types/google-cloud__datastore/index.d.ts index 6eee49ba50..a8e64839e6 100644 --- a/types/google-cloud__datastore/index.d.ts +++ b/types/google-cloud__datastore/index.d.ts @@ -223,7 +223,7 @@ declare module '@google-cloud/datastore/request' { runQuery(query: Query, options: QueryOptions, callback: QueryCallback): void; runQuery(query: Query, callback: QueryCallback): void; - runQuery(query: Query, options?: QueryOptions): QueryResult; + runQuery(query: Query, options?: QueryOptions): Promise; runQueryStream(query: Query, options?: QueryOptions): NodeJS.ReadableStream; diff --git a/types/google-cloud__pubsub/google-cloud__pubsub-tests.ts b/types/google-cloud__pubsub/google-cloud__pubsub-tests.ts new file mode 100644 index 0000000000..7a9b9905c2 --- /dev/null +++ b/types/google-cloud__pubsub/google-cloud__pubsub-tests.ts @@ -0,0 +1,578 @@ +import * as PubSub from '@google-cloud/pubsub'; + +// AUTHOR NOTES: We use the examples directly from the library documentation +// where possible. If there is a problem with a given example (e.g. undocumented +// feature or option), we make a note of it and provide an alternative example +// call instead. + +/////////////////////////////////////////////////////////////////////////////// +// PUBSUB +/////////////////////////////////////////////////////////////////////////////// +{ + let pubsub: PubSub.PubSub; + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=PubSub + // When running on Google Cloud Platform: + pubsub = PubSub(); + // When running elsewhere: + pubsub = PubSub({ + projectId: 'grape-spaceship-123', + keyFilename: '/path/to/keyfile.json', + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=createSubscription + // Subscribe to a topic: + pubsub.createSubscription('messageCenter', 'newMessages', (err, subscription, apiResponse) => { }); + // Customize the subscription: + // NOTE: ackDeadline, as given in the example, is undocumented, so create a subscription only with the KNOWN options + pubsub.createSubscription('messageCenter', 'newMessages', { + retainAckedMessages: true, + }, (err, subscription, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + pubsub.createSubscription('messageCenter', 'newMessages').then((data) => { + const subscription = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=createTopic + // Create topic with callback + pubsub.createTopic('my-new-topic', (err, topic, apiResponse) => { + if (!err) { + // The topic was created successfully. + } + }); + // If the callback is omitted, we'll return a Promise. + pubsub.createTopic('my-new-topic').then((data) => { + const topic = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getSnapshots + // Get snapshots: + pubsub.getSnapshots((err, snapshots) => { + if (!err) { + // snapshots is an array of Snapshot objects. + } + }); + // If the callback is omitted, we'll return a Promise. + pubsub.getSnapshots().then((data) => { + const snapshots = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getSnapshotsStream + // Get snapshots stream + pubsub.getSnapshotsStream() + .on('error', console.error) + .on('data', (snapshot) => { + // snapshot is a Snapshot object. + }) + .on('end', () => { + // All snapshots retrieved. + }); + // If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests. + // NOTE: this had to be modified to work around the 'this' keyword as used in the example + { + const stream = pubsub.getSnapshotsStream(); + stream.on('data', (snapshot) => { + stream.end(); + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getSubscriptions + // Get subscriptions: + pubsub.getSubscriptions((err, subscriptions) => { + if (!err) { + // subscriptions is an array of Subscription objects. + } + }); + // If the callback is omitted, we'll return a Promise. + pubsub.getSubscriptions().then((data) => { + const subscriptions = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getSubscriptionsStream + // Get subscriptions stream + pubsub.getSubscriptionsStream() + .on('error', console.error) + .on('data', (subscription) => { + // subscription is a Subscription object. + }) + .on('end', () => { + // All subscriptions retrieved. + }); + // If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests. + // Note: this had to be modified to work around the 'this' keyword as used in the example. + { + const stream = pubsub.getSubscriptionsStream(); + stream.on('data', (subscription) => { + stream.end(); + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getTopics + // Get topics: + pubsub.getTopics((err, topics) => { + if (!err) { + // topics is an array of Topic objects. + } + }); + // Customize the query: + pubsub.getTopics({ + pageSize: 3 + }, (err, topics) => { }); + // If the callback is omitted, we'll return a Promise. + pubsub.getTopics().then((data) => { + const topics = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=getTopicsStream + // Get topics stream: + pubsub.getTopicsStream() + .on('error', console.error) + .on('data', (topic) => { + // topic is a Topic object. + }) + .on('end', () => { + // All topics retrieved. + }); + // If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests. + // Note: this had to be modified to work around the 'this' keyword as used in the example. + { + const stream = pubsub.getTopicsStream(); + stream.on('data', (topic) => { + stream.end(); + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=snapshot + // Snapshot: + { + const snapshot = pubsub.snapshot('my-snapshot'); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=subscription + // Subscription: + { + const subscription = pubsub.subscription('my-subscription'); + + // Register a listener for `message` events. + subscription.on('message', (message) => { + // Called every time a message is received. + // message.id = ID of the message. + // message.ackId = ID used to acknowledge the message receival. + // message.data = Contents of the message. + // message.attributes = Attributes of the message. + // message.publishTime = Timestamp when Pub/Sub received the message. + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub?method=topic + // Topic: + { + const topic = pubsub.topic('my-topic'); + } +} + +/////////////////////////////////////////////////////////////////////////////// +// PUBLISHER +/////////////////////////////////////////////////////////////////////////////// +{ + const pubsub = PubSub(); + const topic = pubsub.topic('my-topic'); + const publisher = topic.publisher(); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/publisher?method=publish + // Publish: + publisher.publish(new Buffer('Hello, world!'), (err, messageId) => { + if (err) { + // Error handling omitted. + } + }); + // Optionally you can provide an object containing attributes for the message. + publisher.publish(new Buffer('Hello, world!'), { key: 'value' }, (err, messageId) => { + if (err) { + // Error handling omitted. + } + }); +} + +/////////////////////////////////////////////////////////////////////////////// +// SNAPSHOT +/////////////////////////////////////////////////////////////////////////////// +{ + const pubsub = PubSub(); + const subscription = pubsub.subscription('my-subscription'); + + // There are two type of snapshots; the ones obtained from subscription.createSnapshot() have more functionality + const snapshot = pubsub.snapshot('my-snapshot'); + const snapshotFromSubscription = subscription.snapshot('my-snapshot'); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/snapshot?method=create + // Note: Only available to snapshots created via methods of Subscription + // Create snapshot + snapshotFromSubscription.create('my-snapshot', (err, snapshot, apiResponse) => { + if (!err) { + // The snapshot was created successfully. + } + }); + // If the callback is omitted, we'll return a Promise. + snapshotFromSubscription.create('my-snapshot').then((data) => { + const snapshot = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/snapshot?method=delete + // Delete the snapshot + snapshot.delete((err, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + snapshot.delete().then((data) => { + const apiResponse = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/snapshot?method=seek + // Note: Only available to snapshots created via methods of Subscription + // Seek: + snapshotFromSubscription.seek((err, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + snapshotFromSubscription.seek().then((data) => { + const apiResponse = data[0]; + }); +} + +/////////////////////////////////////////////////////////////////////////////// +// SUBSCRIPTION +/////////////////////////////////////////////////////////////////////////////// +{ + const pubsub = PubSub(); + const topic = pubsub.topic('my-topic'); + const subscription = topic.subscription('my-subscription'); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=close + // Close: + subscription.close((err) => { + if (err) { + // Error handling omitted. + } + }); + // If the callback is omitted, we'll return a Promise. + subscription.close().then(() => { }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=createSnapshot + // Create snapshot: + subscription.createSnapshot('my-snapshot', (err, snapshot, apiResponse) => { + if (!err) { + // The snapshot was created successfully. + } + }); + // If the callback is omitted, we'll return a Promise. + subscription.createSnapshot('my-snapshot').then((data) => { + const snapshot = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=delete + // Delete: + subscription.delete((err, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + subscription.delete().then((data) => { + const apiResponse = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=exists + // Exists: + subscription.exists((err, exists) => { }); + // If the callback is omitted, we'll return a Promise. + subscription.exists().then((data) => { + const exists = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=get + // Get: + subscription.get((err, subscription, apiResponse) => { + // The `subscription` data has been populated. + }); + // If the callback is omitted, we'll return a Promise. + subscription.get().then((data) => { + const subscription = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=getMetadata + // Get metadata: + subscription.getMetadata((err, apiResponse) => { + if (err) { + // Error handling omitted. + } + }); + // If the callback is omitted, we'll return a Promise. + subscription.getMetadata().then((data) => { + const apiResponse = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=modifyPushConfig + // Modify push config: + // Note: Had to modify the code to force typings + { + const pushConfig: PubSub.Subscription.PushConfig = { + pushEndpoint: 'https://mydomain.com/push', + attributes: { + 'x-goog-version': 'v1', + } + }; + subscription.modifyPushConfig(pushConfig, (err, apiResponse) => { + if (err) { + // Error handling omitted. + } + }); + // If the callback is omitted, we'll return a Promise. + subscription.modifyPushConfig(pushConfig).then((data) => { + const apiResponse = data[0]; + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=seek + // Seek: + { + const callback: PubSub.Subscription.SeekCallback = (err, resp) => { + if (!err) { + // Seek was successful. + } + }; + subscription.seek('my-snapshot', callback); + // Alternatively, to specify a certain point in time, you can provide a Date object. + subscription.seek(new Date('October 21 2015'), callback); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=setMetadata + { + const metadata = { + key: 'value' + }; + + // Set metadata + subscription.setMetadata(metadata, (err, apiResponse) => { + if (err) { + // Error handling omitted. + } + }); + // If the callback is omitted, we'll return a Promise. + subscription.setMetadata(metadata).then((data) => { + const apiResponse = data[0]; + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=snapshot + // Snapshot: + subscription.snapshot('my-snapshot'); +} + +/////////////////////////////////////////////////////////////////////////////// +// TOPIC +/////////////////////////////////////////////////////////////////////////////// +{ + const pubsub = PubSub(); + const topic = pubsub.topic('my-topic'); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=create + // Create: + topic.create((err, topic, apiResponse) => { + if (!err) { + // The topic was created successfully. + } + }); + // If the callback is omitted, we'll return a Promise. + topic.create().then((data) => { + const topic = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=createSubscription + { + const callback: PubSub.Topic.CreateSubscriptionCallback = (err, subscription, apiResponse) => { }; + + // Without specifying any options. + topic.createSubscription('newMessages', callback); + + // With options. + // Note: ackDeadline not documented, so we use a different option + topic.createSubscription('newMessages', { + // ackDeadline: 90000 // 90 seconds + retainAckedMessages: true, + }, callback); + + // If the callback is omitted, we'll return a Promise. + topic.createSubscription('newMessages').then((data) => { + const subscription = data[0]; + const apiResponse = data[1]; + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=delete + // Delete: + topic.delete((err, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + topic.delete().then((data) => { + const apiResponse = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=exists + // Exists: + topic.exists((err, exists) => { }); + // If the callback is omitted, we'll return a Promise. + topic.exists().then((data) => { + const exists = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=get + // Get: + topic.get((err, topic, apiResponse) => { + // The `topic` data has been populated. + }); + // If the callback is omitted, we'll return a Promise. + topic.get().then((data) => { + const topic = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=getMetadata + // Get metadata + topic.getMetadata((err, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + topic.getMetadata().then((data) => { + const apiResponse = data[0]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=getSubscriptions + // Get subscriptions: + // Note: Modified so that the callback is a constant + { + const callback: PubSub.Topic.GetSubscriptionsCallback = (err, subscriptions) => { + // subscriptions is an array of `Subscription` objects. + }; + + topic.getSubscriptions(callback); + + // Customize the query. + topic.getSubscriptions({ + pageSize: 3 + }, callback); + + // If the callback is omitted, we'll return a Promise. + topic.getSubscriptions().then((data) => { + const subscriptions = data[0]; + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=getSubscriptionsStream + // Get subscriptions stream: + topic.getSubscriptionsStream() + .on('error', console.error) + .on('data', (subscription) => { + // subscription is a Subscription object. + }) + .on('end', () => { + // All subscriptions retrieved. + }); + // If you anticipate many results, you can end a stream early to prevent unnecessary processing and API requests. + { + const stream = topic.getSubscriptionsStream(); + stream.on('data', (subscription) => { + stream.end(); + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=publisher + topic.publisher().publish(new Buffer('Hello, world!'), (err, messageId) => { + if (err) { + // Error handling omitted. + } + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=subscription + // Register a listener for `message` events. + topic.subscription('my-subscription').on('message', (message) => { + // Called every time a message is received. + // message.id = ID of the message. + // message.ackId = ID used to acknowledge the message receival. + // message.data = Contents of the message. + // message.attributes = Attributes of the message. + // message.publishTime = Timestamp when Pub/Sub received the message. + }); +} + +/////////////////////////////////////////////////////////////////////////////// +// IAM +/////////////////////////////////////////////////////////////////////////////// +{ + const pubsub = PubSub(); + const topic = pubsub.topic('my-topic'); + const subscription = topic.subscription('my-subscription'); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=iam.getPolicy + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=iam.getPolicy + // Get policy: + topic.iam.getPolicy((err, policy, apiResponse) => { }); + subscription.iam.getPolicy((err, policy, apiResponse) => { }); + // If the callback is omitted, we'll return a Promise. + topic.iam.getPolicy().then((data) => { + const policy = data[0]; + const apiResponse = data[1]; + }); + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=iam.setPolicy + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=iam.setPolicy + { + const myPolicy = { + bindings: [ + { + role: 'roles/pubsub.subscriber', + members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] + } + ] + }; + + // Set policy: + topic.iam.setPolicy(myPolicy, (err, policy, apiResponse) => { }); + subscription.iam.setPolicy(myPolicy, (err, policy, apiResponse) => { }); + + // If the callback is omitted, we'll return a Promise. + topic.iam.setPolicy(myPolicy).then((data) => { + const policy = data[0]; + const apiResponse = data[1]; + }); + } + + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/subscription?method=iam.testPermissions + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=iam.testPermissions + { + const test = 'pubsub.topics.update'; + + // Test permission + topic.iam.testPermissions(test, (err, permissions, apiResponse) => { + console.log(permissions); + // { + // "pubsub.topics.update": true + // } + }); + + // Test several permissions at once. + const tests = [ + 'pubsub.subscriptions.consume', + 'pubsub.subscriptions.update' + ]; + + subscription.iam.testPermissions(tests, (err, permissions) => { + console.log(permissions); + // { + // "pubsub.subscriptions.consume": true, + // "pubsub.subscriptions.update": false + // } + }); + + // If the callback is omitted, we'll return a Promise. + topic.iam.testPermissions(test).then((data) => { + const permissions = data[0]; + const apiResponse = data[1]; + }); + } +} diff --git a/types/google-cloud__pubsub/index.d.ts b/types/google-cloud__pubsub/index.d.ts new file mode 100644 index 0000000000..7c9014b7d3 --- /dev/null +++ b/types/google-cloud__pubsub/index.d.ts @@ -0,0 +1,344 @@ +// Type definitions for @google-cloud/pubsub 0.14 +// Project: https://github.com/GoogleCloudPlatform/google-cloud-node/tree/master/packages/pubsub +// Definitions by: Paul Huynh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +import { EventEmitter } from "events"; +import { Duplex } from "stream"; + +declare namespace PubSub { + // TODO write definitions for the for v1 + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/v1 + function v1(config?: GCloudConfiguration): any; + + interface GCloudConfiguration { + projectId?: string; + keyFilename?: string; + email?: string; + credentials?: { + client_email?: string; + private_key?: string + }; + autoRetry?: boolean; + maxRetries?: number; + promise?: any; + } + + interface PubSub { + createSubscription(topic: Topic | string, name: string, options?: PubSub.CreateSubscriptionOptions): Promise; + createSubscription(topic: Topic | string, name: string, callback: PubSub.CreateSubscriptionCallback): void; + createSubscription(topic: Topic | string, name: string, options: PubSub.CreateSubscriptionOptions, callback: PubSub.CreateSubscriptionCallback): void; + + createTopic(name: string, gaxOpts?: GAX.CallOptions): Promise; + createTopic(name: string, callback: PubSub.CreateTopicCallback): void; + createTopic(name: string, gaxOpts: GAX.CallOptions, callback: PubSub.CreateTopicCallback): void; + + getSnapshots(options?: PubSub.GetSnapshotsOptions): Promise; + getSnapshots(callback: PubSub.GetSnapshotsCallback): void; + getSnapshots(options: PubSub.GetSnapshotsOptions, callback: PubSub.GetSnapshotsCallback): void; + + getSnapshotsStream(options?: PubSub.GetSnapshotsOptions): Duplex; + + getSubscriptions(options?: PubSub.GetSubscriptionsOptions): Promise; + getSubscriptions(callback: PubSub.GetSubscriptionsCallback): void; + getSubscriptions(options: PubSub.GetSubscriptionsOptions, callback: PubSub.GetSubscriptionsCallback): void; + + getSubscriptionsStream(options?: PubSub.GetSubscriptionsOptions): Duplex; + + getTopics(query?: PubSub.GetTopicsQuery): Promise; + getTopics(callback: PubSub.GetTopicsCallback): void; + getTopics(query: PubSub.GetTopicsQuery, callback: PubSub.GetTopicsCallback): void; + + getTopicsStream(query?: PubSub.GetTopicsQuery): Duplex; + + snapshot(name: string): Snapshot; + + subscription(name: string, options?: PubSub.SubscriptionOptions): Subscription; + + topic(name: string): Topic; + } + namespace PubSub { + interface CreateSubscriptionOptions { + flowControl?: { + maxBytes?: number; + maxMessages?: number; + }; + gaxOpts?: GAX.CallOptions; + messageRetentionDuration?: number | Date; + pushEndpoint?: string; + retainAckedMessages?: boolean; + } + type CreateSubscriptionCallback = (err: Error | null, subscription: Subscription, apiResponse: object) => void; + + type CreateTopicCallback = (err: Error | null, topic: Topic, apiResponse: object) => void; + + interface GetSnapshotsOptions { + autoPaginate?: boolean; + gaxOpts?: GAX.CallOptions; + pageSize?: number; + pageToken?: string; + } + type GetSnapshotsCallback = (err: Error | null, snapshots: Snapshot[]) => void; + + interface GetSubscriptionsOptions { + autoPaginate?: boolean; + gaxOpts?: GAX.CallOptions; + pageSize?: number; + pageToken?: string; + topic?: Topic | string; + } + type GetSubscriptionsCallback = (err: Error | null, subscriptions: Subscription[], apiResponse: object) => void; + + interface GetTopicsQuery { + autoPaginate?: boolean; + gaxOpts?: GAX.CallOptions; + pageSize?: number; + pageToken?: string; + } + type GetTopicsCallback = (err: Error | null, topics: Topic[], apiResponse: object) => void; + + interface SubscriptionOptions { + flowControl?: { + maxBytes?: number; + maxMessages?: number; + }; + maxConnections?: number; + } + } + + interface Publisher { + publish(data: Buffer, callback: Publisher.PublishCallback): void; + publish(data: Buffer, attributes: object, callback: Publisher.PublishCallback): void; + publish(data: Buffer, attributes?: object): Promise; + } + namespace Publisher { + type PublishCallback = (error: Error | null, messageId: string) => void; + } + + interface Snapshot { + delete(): Promise; + delete(callback: Snapshot.DeleteCallback): void; + } + interface SnapshotFromSubscription extends Snapshot { + create(name: string): Promise; + create(name: string, callback: Snapshot.CreateCallback): void; + + seek(): Promise; + seek(callback: Snapshot.SeekCallback): void; + } + namespace Snapshot { + type DeleteCallback = (err: Error | null, apiResponse: object) => void; + + type CreateCallback = (err: Error | null, snapshot: Snapshot, apiResponse: object) => void; + + type SeekCallback = (err: Error | null, apiResponse: object) => void; + } + + interface Subscription extends EventEmitter { + close(): Promise; + close(callback: Subscription.CloseCallback): void; + + createSnapshot(name: string, gaxOpts?: GAX.CallOptions): Promise; + createSnapshot(name: string, callback: Subscription.CreateSnapshotCallback): void; + createSnapshot(name: string, gaxOpts: GAX.CallOptions, callback: Subscription.CreateSnapshotCallback): void; + + delete(gaxOpts?: GAX.CallOptions): Promise; + delete(callback: Subscription.DeleteCallback): void; + delete(gaxOpts: GAX.CallOptions, callback: Subscription.DeleteCallback): void; + + exists(): Promise; + exists(callback: Subscription.ExistsCallback): void; + + get(gaxOpts?: GAX.CallOptions): Promise; // TODO: only expose autoCreate + // NOTE: The following are not documented, but are possible signatures base on the source code + get(callback: Subscription.GetCallback): void; + get(gaxOpts: GAX.CallOptions, callback: Subscription.GetCallback): void; + + getMetadata(gaxOpts?: GAX.CallOptions): Promise; + getMetadata(callback: Subscription.GetMetadataCallback): void; + getMetadata(gaxOpts: GAX.CallOptions, callback: Subscription.GetMetadataCallback): void; + + iam: IAM; + + modifyPushConfig(config: Subscription.PushConfig, gaxOpts?: GAX.CallOptions): Promise; + modifyPushConfig(config: Subscription.PushConfig, callback: Subscription.ModifyPushConfigCallback): void; + modifyPushConfig(config: Subscription.PushConfig, gaxOpts: GAX.CallOptions, callback: Subscription.ModifyPushConfigCallback): void; + + seek(snapshot: string | Date, callback: Subscription.SeekCallback): void; + seek(snapshot: string | Date, gaxOpts: GAX.CallOptions, callback: Subscription.SeekCallback): void; + + setMetadata(metadata: object, gaxOpts?: GAX.CallOptions): Promise; + setMetadata(metadata: object, callback: Subscription.SetMetadataCallback): void; + setMetadata(metadata: object, gaxOpts: GAX.CallOptions, callback: Subscription.SetMetadataCallback): void; + + snapshot(name: string): SnapshotFromSubscription; + } + namespace Subscription { + type CloseCallback = (err: Error | null) => void; + + type CreateSnapshotCallback = (err: Error | null, snapshot: SnapshotFromSubscription, apiResponse: object) => void; + + type DeleteCallback = (err: Error | null, apiResponse: object) => void; + + type ExistsCallback = (err: Error | null, exists: boolean) => void; + + type GetCallback = (err: Error | null, subscription: Subscription, apiResponse: object) => void; + + type GetMetadataCallback = (err: Error | null, apiResponse: object) => void; + + interface PushConfig { + pushEndpoint?: string; + // https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions#pushconfig + attributes?: PushConfigAttributes; + } + interface PushConfigAttributes { + 'x-goog-version': 'v1beta' | 'v1' | 'v1beta2'; + } + type ModifyPushConfigCallback = (err: Error | null, apiResponse: object) => void; + + type SeekCallback = (err: Error | null, apiResponse: object) => void; + + type SetMetadataCallback = (err: Error | null, apiResponse: object) => void; + } + + interface Topic { + create(gaxOpts?: GAX.CallOptions): Promise; + create(callback: Topic.CreateCallback): void; + create(gaxOpts: GAX.CallOptions, callback: Topic.CreateCallback): void; + + createSubscription(nameOrOptions?: string | Topic.CreateSubscriptionOptions): Promise; + createSubscription(name: string, options: Topic.CreateSubscriptionOptions): Promise; + createSubscription(callback: Topic.CreateSubscriptionCallback): void; + createSubscription(nameOrOptions: string | Topic.CreateSubscriptionOptions, callback: Topic.CreateSubscriptionCallback): void; + createSubscription(name: string, options: Topic.CreateSubscriptionOptions, callback: Topic.CreateSubscriptionCallback): void; + + delete(gaxOpts?: GAX.CallOptions): Promise; + delete(callback: Topic.DeleteCallback): void; + delete(gaxOpts: GAX.CallOptions, callback: Topic.DeleteCallback): void; + + exists(): Promise; + exists(callback: Topic.ExistsCallback): void; + + // NOTE: The documentation in the link is incomplete; the function takes a callback + // as second argument (in the source): + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=get + get(gaxOpts?: GAX.CallOptions): Promise; + get(callback: Topic.GetCallback): void; + get(gaxOpts: GAX.CallOptions, callback: Topic.GetCallback): void; + + getMetadata(gaxOpts?: GAX.CallOptions): Promise; + getMetadata(callback: Topic.GetMetadataCallback): void; + getMetadata(gaxOpts: GAX.CallOptions, callback: Topic.GetMetadataCallback): void; + + getSubscriptions(options?: Topic.GetSubscriptionsOptions): Promise; + getSubscriptions(callback: Topic.GetSubscriptionsCallback): void; + getSubscriptions(options: Topic.GetSubscriptionsOptions, callback: Topic.GetSubscriptionsCallback): void; + + // Note: The documention lists the parameter as 'query', when it probably should be 'options'. + getSubscriptionsStream(options?: Topic.GetSubscriptionsOptions): Duplex; + + iam: IAM; + + publisher(options?: Topic.PublisherOptions): Publisher; + + subscription(name: string, options?: Topic.SubscriptionOptions): Subscription; + } + namespace Topic { + type CreateCallback = PubSub.CreateTopicCallback; + + type CreateSubscriptionOptions = PubSub.CreateSubscriptionOptions; + type CreateSubscriptionCallback = PubSub.CreateSubscriptionCallback; + + // Note: This is not fully documented in the link; browse the source code to find the callback parameters + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=delete + type DeleteCallback = (err: Error | null, apiResponse: object) => void; + + type ExistsCallback = (err: Error | null, exists: boolean) => void; + + // Note: This is not fully documented in the link; browse the source code to find the callback parameters + // https://googlecloudplatform.github.io/google-cloud-node/#/docs/pubsub/0.14.1/pubsub/topic?method=get + type GetCallback = (err: Error | null, topic: Topic, apiResponse: object) => void; + + type GetMetadataCallback = (err: Error | null, apiResponse: object) => void; + + // Options are SLIGHTLY different to PubSub.getSubscriptions(...), so we can't just reuse it + interface GetSubscriptionsOptions { + autoPaginate?: boolean; + gaxOpts?: GAX.CallOptions; + pageSize?: number; + pageToken?: string; + } + // Callback signature also slightly different to PubSub.getSubscriptions(callback), so we can't just reuse it + type GetSubscriptionsCallback = (err: Error | null, subscriptions: Subscription[]) => void; + + interface PublisherOptions { + batching?: { + maxBytes?: number; + maxMessages?: number; + maxMilliseconds?: number; + }; + } + + type SubscriptionOptions = PubSub.SubscriptionOptions; + } + + // Allow this interface to start with 'I', since it's an acronym! + // tslint:disable-next-line interface-name + interface IAM { + getPolicy(): Promise; + getPolicy(callback: IAM.GetPolicyCallback): void; + + setPolicy(policy: IAM.Policy): Promise; + setPolicy(policy: IAM.Policy, callback: IAM.SetPolicyCallback): void; + + testPermissions(permissions: string | string[]): Promise; + testPermissions(permissions: string | string[], callback: IAM.TestPermissionsCallback): void; + } + namespace IAM { + type GetPolicyCallback = (err: Error | null, policy: Policy, apiResponse: object) => void; + + type SetPolicyCallback = (err: Error | null, policy: Policy, apiResponse: object) => void; + + type TestPermissionsCallback = (err: Error | null, permissions: string | string[], apiResponse: object) => void; + + interface Policy { + bindings?: any[]; + rules?: object[]; + etag?: string; + } + } + + namespace GAX { + /** https://googleapis.github.io/gax-nodejs/global.html#CallOptions */ + interface CallOptions { + timeout?: number; + retry?: RetryOptions; + autoPaginate?: boolean; + pageToken?: object; + isBundling?: boolean; + longrunning?: BackoffSettings; + promise?: PromiseConstructor; // FIXME Unsure if this is the correct type; remove this comment if it is + } + + /** https://googleapis.github.io/gax-nodejs/global.html#RetryOptions */ + interface RetryOptions { + retryCodes: string[]; + backoffSettings: BackoffSettings; + } + + /** https://googleapis.github.io/gax-nodejs/global.html#BackoffSettings */ + interface BackoffSettings { + initialRetryDelayMillis: number; + retryDelayMultiplier: number; + maxRetryDelayMillis: number; + initialRpcTimeoutMillis: number; + maxRpcTimeoutMillis: number; + totalTimeoutMillis: number; + } + } +} + +declare function PubSub(config?: PubSub.GCloudConfiguration): PubSub.PubSub; +export = PubSub; diff --git a/types/google-cloud__pubsub/tsconfig.json b/types/google-cloud__pubsub/tsconfig.json new file mode 100644 index 0000000000..f71eb2a331 --- /dev/null +++ b/types/google-cloud__pubsub/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "paths": { + "@google-cloud/pubsub": [ + "google-cloud__pubsub" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-cloud__pubsub-tests.ts" + ] +} \ No newline at end of file diff --git a/types/google-cloud__pubsub/tslint.json b/types/google-cloud__pubsub/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__pubsub/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google.analytics/google.analytics-tests.ts b/types/google.analytics/google.analytics-tests.ts index 945f967dc9..5256f636c7 100644 --- a/types/google.analytics/google.analytics-tests.ts +++ b/types/google.analytics/google.analytics-tests.ts @@ -41,14 +41,39 @@ describe('UniversalAnalytics', () => { }); it('should excercise Tracker APIs', () => { const tracker: UniversalAnalytics.Tracker = ga.create('UA-65432-1', 'auto'); - const aString: string = tracker.get('aString'); - const aNumber: number = tracker.get('aNumber'); - const anObject: {} = tracker.get<{}>('anObject'); + + tracker.get('fieldName'); + + tracker.set('aString', 'aString'); + tracker.set('aNumber', 1); + tracker.set('anObject', {}); + tracker.set({ + several: 'values', + at: 'once' + }); + tracker.send('pageview'); + tracker.send('pageview', '/some-path'); tracker.send('pageview', {some: 'details'}); - tracker.set('aString', aString); - tracker.set('aNumber', aNumber); - tracker.set('anObject', anObject); + }); + + it('should exercise Model APIs', () => { + const tracker: UniversalAnalytics.Tracker = ga.create('UA-65432-1', 'auto'); + + tracker.set('sendHitTask', (gaHitModel: UniversalAnalytics.Model) => { + gaHitModel.get('hitPayload'); + + gaHitModel.set('hitCallback', () => console.log('hit sent'), true); + gaHitModel.set('hitCallback', () => console.log('hit sent')); + gaHitModel.set({ + hitPayload: 'a=1&b=2', + otherField: 3 + }); + gaHitModel.set({ + hitPayload: 'a=1&b=2', + otherField: 3 + }, null, false); + }); }); }); diff --git a/types/google.analytics/index.d.ts b/types/google.analytics/index.d.ts index c6d188d1cb..b0412a362f 100644 --- a/types/google.analytics/index.d.ts +++ b/types/google.analytics/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Analytics (Classic and Universal) // Project: https://developers.google.com/analytics/devguides/collection/gajs/, https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference -// Definitions by: Ronnie Haakon Hegelund , Pat Kujawa +// Definitions by: Ronnie Haakon Hegelund , Pat Kujawa , Tyler Murphy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Tracker { @@ -620,12 +620,17 @@ declare namespace UniversalAnalytics { } interface Tracker { - get(fieldName: string): T; - send(hitType: string, opt_fieldObject?: {}): void; - set(fieldName: string, value: string): void; - set(fieldName: string, value: {}): void; - set(fieldName: string, value: number): void; - set(fieldName: string, value: boolean): void; + get(fieldName: string): any; + set(fieldName: string, fieldValue: any): void; + set(fieldsObject: {}): void; + send(hitType: string, ...fields: any[]): void; + send(hitType: string, fieldsObject: {}): void; + } + + interface Model { + get(fieldName: string): any; + set(fieldName: string, fieldValue: any, temporary?: boolean): void; + set(fields: {}, fieldValue?: null, temporary?: boolean): void; } } diff --git a/types/google.picker/index.d.ts b/types/google.picker/index.d.ts index 0341811917..11397695a2 100644 --- a/types/google.picker/index.d.ts +++ b/types/google.picker/index.d.ts @@ -146,6 +146,9 @@ declare namespace google { // For photo uploads, controls whether per-photo selection (as opposed to per-album) selection is enabled. SIMPLE_UPLOAD_ENABLED: string; + + // Whether Team Drive items should be included in results. + SUPPORT_TEAM_DRIVES: string; }; export var ViewId:{ diff --git a/types/google.visualization/index.d.ts b/types/google.visualization/index.d.ts index de893bbdc9..a94ca8dc90 100644 --- a/types/google.visualization/index.d.ts +++ b/types/google.visualization/index.d.ts @@ -456,8 +456,8 @@ declare namespace google { maxTextLines?: number; minTextSpacing?: number; showTextEvery?: number; - maxValue?: number; - minValue?: number; + maxValue?: number | Date | number[]; + minValue?: number | Date | number[]; viewWindowMode?: string; viewWindow?: ChartViewWindow; } @@ -468,8 +468,8 @@ declare namespace google { } export interface ChartViewWindow { - max?: number; - min?: number; + max?: number | Date | number[]; + min?: number | Date | number[]; } export interface ChartTooltip { @@ -645,6 +645,7 @@ declare namespace google { interpolateNulls?: boolean; legend?: ChartLegend | 'none'; lineWidth?: number; + min?: number; orientation?: string; pointSize?: number; reverseCategories?: boolean; @@ -1009,7 +1010,7 @@ declare namespace google { export interface TableOptions { allowHtml?: boolean; alternatingRowStyle?: boolean; - cssClassName?: CssClassNames; + cssClassNames?: CssClassNames; firstRowNumber?: number; height?: string; page?: string; diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 66ddb31f5d..5e977257b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Google Maps JavaScript API 3.29 +// Type definitions for Google Maps JavaScript API 3.30 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello , Sven Kreiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -2697,7 +2697,7 @@ declare namespace google.maps { * Accepted values are 'marker', 'polygon', 'polyline', 'rectangle', 'circle', or null. A drawing mode * of null means that the user can interact with the map as normal, and clicks do not draw anything. */ - drawingMode?: OverlayType; + drawingMode?: OverlayType | null; /** * The Map to which the DrawingManager is attached, which is the Map on which the overlays created * will be placed. diff --git a/types/got/index.d.ts b/types/got/index.d.ts index b8b1e362e1..14724b8eda 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: BendingBender // Linus Unnebäck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// diff --git a/types/graceful-fs/index.d.ts b/types/graceful-fs/index.d.ts index 2b31db0668..69e7a5dce9 100644 --- a/types/graceful-fs/index.d.ts +++ b/types/graceful-fs/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Bart van der Schoor // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/graphql-date/index.d.ts b/types/graphql-date/index.d.ts index 35ad44f7e1..4615d424a1 100644 --- a/types/graphql-date/index.d.ts +++ b/types/graphql-date/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/tjmehta/graphql-date // Definitions by: Eric Naeseth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { GraphQLScalarType } from 'graphql'; diff --git a/types/graphql-relay/index.d.ts b/types/graphql-relay/index.d.ts index 7c0d9965a8..2318a527e4 100644 --- a/types/graphql-relay/index.d.ts +++ b/types/graphql-relay/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/graphql/graphql-relay-js // Definitions by: Arvitaly , nitintutlani , Grelinfo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { GraphQLBoolean, diff --git a/types/graphql-type-json/index.d.ts b/types/graphql-type-json/index.d.ts index c9549b946d..2b10599e0e 100644 --- a/types/graphql-type-json/index.d.ts +++ b/types/graphql-type-json/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/taion/graphql-type-json#readme // Definitions by: Pavel Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + import { GraphQLScalarType } from "graphql"; declare const GraphQLJSON: GraphQLScalarType; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 6d02b82124..c8ee7d9215 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -28,11 +28,13 @@ export interface ExecutionContext { /** * The result of execution. `data` is the result of executing the - * query, `errors` is null if no errors occurred, and is a + * query, `extensions` represents additional metadata, `errors` is + * null if no errors occurred, and is a * non-empty array if an error occurred. */ export interface ExecutionResult { data?: { [key: string]: any }; + extensions?: { [key: string]: any }; errors?: GraphQLError[]; } diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index b65245a33e..74d9224242 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -8,6 +8,7 @@ // Mikhail Novikov // Ivan Goncharov // Hagai Cohen +// Ricardo Portugal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index 7f84c875fb..52df7bd46c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -455,6 +455,7 @@ export class GraphQLEnumType { constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; + isValidValue(value: any): boolean; serialize(value: any): string; parseValue(value: any): any; parseLiteral(valueNode: ValueNode): any; diff --git a/types/guid/guid-tests.ts b/types/guid/guid-tests.ts new file mode 100644 index 0000000000..52e0a738d1 --- /dev/null +++ b/types/guid/guid-tests.ts @@ -0,0 +1,18 @@ +import guid = require('guid'); + +// $ExpectType object +guid.create(); + +// $ExpectType string +guid.raw(); + +const newRawGuid = guid.raw(); + +// $ExpectType boolean +guid.isGuid(newRawGuid); + +// $ExpectType string +guid.EMPTY; + +// $ExpectType object +guid(guid.create()); diff --git a/types/guid/index.d.ts b/types/guid/index.d.ts new file mode 100644 index 0000000000..6025e90bf1 --- /dev/null +++ b/types/guid/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for guid 1.0 +// Project: https://github.com/dandean/guid +// Definitions by: Marc-Andre Roy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = guid; + +declare function guid(guid: object): object; + +declare namespace guid { + const EMPTY: string; + + const prototype: { + }; + + function create(): object; + + function isGuid(value: string): boolean; + + function raw(): string; +} diff --git a/types/guid/tsconfig.json b/types/guid/tsconfig.json new file mode 100644 index 0000000000..17563577fd --- /dev/null +++ b/types/guid/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "guid-tests.ts" + ] +} diff --git a/types/guid/tslint.json b/types/guid/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/guid/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-angular-templatecache/tsconfig.json b/types/gulp-angular-templatecache/tsconfig.json index b494e68ba8..3971eae080 100644 --- a/types/gulp-angular-templatecache/tsconfig.json +++ b/types/gulp-angular-templatecache/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-autoprefixer/tsconfig.json b/types/gulp-autoprefixer/tsconfig.json index dfaa5a3f0e..52fd74103c 100644 --- a/types/gulp-autoprefixer/tsconfig.json +++ b/types/gulp-autoprefixer/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-batch/tsconfig.json b/types/gulp-batch/tsconfig.json index bb64157b23..8b5bce2f98 100644 --- a/types/gulp-batch/tsconfig.json +++ b/types/gulp-batch/tsconfig.json @@ -16,11 +16,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-cache/tsconfig.json b/types/gulp-cache/tsconfig.json index 0012ddcd48..e947f63db5 100644 --- a/types/gulp-cache/tsconfig.json +++ b/types/gulp-cache/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-cached/tsconfig.json b/types/gulp-cached/tsconfig.json index 7195fa2007..cdec085a2b 100644 --- a/types/gulp-cached/tsconfig.json +++ b/types/gulp-cached/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-changed/tsconfig.json b/types/gulp-changed/tsconfig.json index c3bf70b010..d04c43b32e 100644 --- a/types/gulp-changed/tsconfig.json +++ b/types/gulp-changed/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-cheerio/tsconfig.json b/types/gulp-cheerio/tsconfig.json index 227362df78..be78d9969c 100644 --- a/types/gulp-cheerio/tsconfig.json +++ b/types/gulp-cheerio/tsconfig.json @@ -13,11 +13,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-clean-dest/gulp-clean-dest-tests.ts b/types/gulp-clean-dest/gulp-clean-dest-tests.ts new file mode 100644 index 0000000000..22a14f7487 --- /dev/null +++ b/types/gulp-clean-dest/gulp-clean-dest-tests.ts @@ -0,0 +1,10 @@ +import cleanDest = require("gulp-clean-dest"); + +const someDir = "."; + +// $ExpectType ReadWriteStream +cleanDest(someDir); +cleanDest(someDir, {}); +cleanDest(someDir, { cwd: someDir }); +cleanDest(someDir, { extension: ".ts" }); +cleanDest(someDir, { cwd: someDir, extension: ".ts" }); diff --git a/types/gulp-clean-dest/index.d.ts b/types/gulp-clean-dest/index.d.ts new file mode 100644 index 0000000000..bbb33abad0 --- /dev/null +++ b/types/gulp-clean-dest/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for gulp-clean-dest 0.2 +// Project: https://github.com/clark800/gulp-clean-dest +// Definitions by: Andrey Lalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace gulpCleanDest { + interface Options { + /** + * The working directory the folder is relative to. + */ + cwd?: string; + + /** + * Extension of the destination files. Useful if it differs from the original. + */ + extension?: string; + } +} + +/** + * Removes files from the dest directory prior to building. + * @param destination The name of the dest directory + * @param options Options for the cleaning process + */ +declare function gulpCleanDest(destination: string, options?: gulpCleanDest.Options): NodeJS.ReadWriteStream; + +export = gulpCleanDest; diff --git a/types/gulp-clean-dest/tsconfig.json b/types/gulp-clean-dest/tsconfig.json new file mode 100644 index 0000000000..777c860568 --- /dev/null +++ b/types/gulp-clean-dest/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-clean-dest-tests.ts" + ] +} diff --git a/types/gulp-clean-dest/tslint.json b/types/gulp-clean-dest/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-clean-dest/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-coffeeify/tsconfig.json b/types/gulp-coffeeify/tsconfig.json index 87113d7415..241ff2e5f8 100644 --- a/types/gulp-coffeeify/tsconfig.json +++ b/types/gulp-coffeeify/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-coffeelint/tsconfig.json b/types/gulp-coffeelint/tsconfig.json index 6a570592f3..94e2edb626 100644 --- a/types/gulp-coffeelint/tsconfig.json +++ b/types/gulp-coffeelint/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-concat/tsconfig.json b/types/gulp-concat/tsconfig.json index 0be8e7ed81..b28024194c 100644 --- a/types/gulp-concat/tsconfig.json +++ b/types/gulp-concat/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-connect/index.d.ts b/types/gulp-connect/index.d.ts index f023c2bff1..e099f62a39 100644 --- a/types/gulp-connect/index.d.ts +++ b/types/gulp-connect/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/avevlad/gulp-connect#readme // Definitions by: Andre Wiggins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as http from "http"; import * as https from "https"; diff --git a/types/gulp-copy/tsconfig.json b/types/gulp-copy/tsconfig.json index cc162d9266..0c92078d28 100644 --- a/types/gulp-copy/tsconfig.json +++ b/types/gulp-copy/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-csso/tsconfig.json b/types/gulp-csso/tsconfig.json index 79361ceb1b..d0e22a2035 100644 --- a/types/gulp-csso/tsconfig.json +++ b/types/gulp-csso/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-debug/tsconfig.json b/types/gulp-debug/tsconfig.json index 8302ca5c8b..3dbd5e8109 100644 --- a/types/gulp-debug/tsconfig.json +++ b/types/gulp-debug/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-dtsm/tsconfig.json b/types/gulp-dtsm/tsconfig.json index 3fd7d615a4..dd1ca59de4 100644 --- a/types/gulp-dtsm/tsconfig.json +++ b/types/gulp-dtsm/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-espower/tsconfig.json b/types/gulp-espower/tsconfig.json index 7418c01526..cf469c3b13 100644 --- a/types/gulp-espower/tsconfig.json +++ b/types/gulp-espower/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-file-include/tsconfig.json b/types/gulp-file-include/tsconfig.json index 5fe64f435c..ab226efcb3 100644 --- a/types/gulp-file-include/tsconfig.json +++ b/types/gulp-file-include/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-filter/tsconfig.json b/types/gulp-filter/tsconfig.json index f68c124ec5..f4f7d56d52 100644 --- a/types/gulp-filter/tsconfig.json +++ b/types/gulp-filter/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-flatten/tsconfig.json b/types/gulp-flatten/tsconfig.json index 2c189387f7..ab4f9a894a 100644 --- a/types/gulp-flatten/tsconfig.json +++ b/types/gulp-flatten/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-gh-pages/tsconfig.json b/types/gulp-gh-pages/tsconfig.json index 76784cfd3d..1ea7bf2217 100644 --- a/types/gulp-gh-pages/tsconfig.json +++ b/types/gulp-gh-pages/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-gzip/tsconfig.json b/types/gulp-gzip/tsconfig.json index f72b05fb7e..4f3f5f8d77 100644 --- a/types/gulp-gzip/tsconfig.json +++ b/types/gulp-gzip/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-help-doc/tsconfig.json b/types/gulp-help-doc/tsconfig.json index 07185baa30..b6f16b60a9 100644 --- a/types/gulp-help-doc/tsconfig.json +++ b/types/gulp-help-doc/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-help/index.d.ts b/types/gulp-help/index.d.ts index f32258a589..3e726363b4 100644 --- a/types/gulp-help/index.d.ts +++ b/types/gulp-help/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/chmontgomery/gulp-help // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/gulp-help/tsconfig.json b/types/gulp-help/tsconfig.json index e8247d3ae3..a174bbab6e 100644 --- a/types/gulp-help/tsconfig.json +++ b/types/gulp-help/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-html-replace/tsconfig.json b/types/gulp-html-replace/tsconfig.json index 0c5f9d408a..fcf17ed178 100644 --- a/types/gulp-html-replace/tsconfig.json +++ b/types/gulp-html-replace/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-htmlmin/tsconfig.json b/types/gulp-htmlmin/tsconfig.json index f45a7a0721..022acde96e 100644 --- a/types/gulp-htmlmin/tsconfig.json +++ b/types/gulp-htmlmin/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-if/tsconfig.json b/types/gulp-if/tsconfig.json index c78250c104..bb2544820b 100644 --- a/types/gulp-if/tsconfig.json +++ b/types/gulp-if/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-inject/tsconfig.json b/types/gulp-inject/tsconfig.json index 1d5bd5080b..aacadf6415 100644 --- a/types/gulp-inject/tsconfig.json +++ b/types/gulp-inject/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-insert/tsconfig.json b/types/gulp-insert/tsconfig.json index aca1a98ef4..6feda660ed 100644 --- a/types/gulp-insert/tsconfig.json +++ b/types/gulp-insert/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-install/tsconfig.json b/types/gulp-install/tsconfig.json index d5a0bdce77..e1b6063ac9 100644 --- a/types/gulp-install/tsconfig.json +++ b/types/gulp-install/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-istanbul/tsconfig.json b/types/gulp-istanbul/tsconfig.json index 837285ca19..133f0cd935 100644 --- a/types/gulp-istanbul/tsconfig.json +++ b/types/gulp-istanbul/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-jade/tsconfig.json b/types/gulp-jade/tsconfig.json index 87dca8e4b2..7e924cb11b 100644 --- a/types/gulp-jade/tsconfig.json +++ b/types/gulp-jade/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-jasmine-browser/tsconfig.json b/types/gulp-jasmine-browser/tsconfig.json index 06b97335ea..55990f3261 100644 --- a/types/gulp-jasmine-browser/tsconfig.json +++ b/types/gulp-jasmine-browser/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-jasmine/gulp-jasmine-tests.ts b/types/gulp-jasmine/gulp-jasmine-tests.ts new file mode 100644 index 0000000000..e40f187004 --- /dev/null +++ b/types/gulp-jasmine/gulp-jasmine-tests.ts @@ -0,0 +1,20 @@ +import gulpJasmine = require("gulp-jasmine"); +import jasmine = require("jasmine"); + +const dummyReporter: jasmine.CustomReporter = {}; + +gulpJasmine(); // $ExpectType ReadWriteStream +gulpJasmine({}); +gulpJasmine({ + verbose: true, + includeStackTrace: true, + reporter: dummyReporter, + timeout: 1000, + errorOnFail: false, + config: {} +}); +gulpJasmine({ reporter: [dummyReporter, dummyReporter] }); +const readonlyDummyReporters: ReadonlyArray = [ + dummyReporter, dummyReporter +]; +gulpJasmine({ reporter: readonlyDummyReporters }); diff --git a/types/gulp-jasmine/index.d.ts b/types/gulp-jasmine/index.d.ts new file mode 100644 index 0000000000..f69fb865e6 --- /dev/null +++ b/types/gulp-jasmine/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for gulp-jasmine 2.4 +// Project: https://github.com/sindresorhus/gulp-jasmine#readme +// Definitions by: Andrey Lalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +interface JasmineOptions { + /** + * Display spec names in default reporter. + */ + verbose?: boolean; + + /** + * Include stack traces in failures in default reporter. + * @default false + */ + includeStackTrace?: boolean; + + /** + * Reporter(s) to use. + */ + reporter?: jasmine.CustomReporter | ReadonlyArray; + + /** + * Time to wait in milliseconds before a test automatically fails. + * @default 5000 + */ + timeout?: number; + + /** + * Stops the stream on failed tests. + * @default true + */ + errorOnFail?: boolean; + + /** + * Passes the config to Jasmine's loadConfig method. + */ + config?: object; +} + +/** + * Executes Jasmine tests. Emits a 'jasmineDone' event on success. + * @param options Optional options for the execution of the Jasmine test + */ +declare function gulpJasmine(options?: JasmineOptions): NodeJS.ReadWriteStream; +export = gulpJasmine; diff --git a/types/gulp-jasmine/tsconfig.json b/types/gulp-jasmine/tsconfig.json new file mode 100644 index 0000000000..d44751f20b --- /dev/null +++ b/types/gulp-jasmine/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-jasmine-tests.ts" + ] +} diff --git a/types/gulp-jasmine/tslint.json b/types/gulp-jasmine/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-jasmine/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-json-editor/tsconfig.json b/types/gulp-json-editor/tsconfig.json index 1375d471be..4f224b2a01 100644 --- a/types/gulp-json-editor/tsconfig.json +++ b/types/gulp-json-editor/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-jspm/tsconfig.json b/types/gulp-jspm/tsconfig.json index 4c6b72f8dc..b612a0a146 100644 --- a/types/gulp-jspm/tsconfig.json +++ b/types/gulp-jspm/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-less/tsconfig.json b/types/gulp-less/tsconfig.json index f171058365..e4c00666f5 100644 --- a/types/gulp-less/tsconfig.json +++ b/types/gulp-less/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-load-plugins/tsconfig.json b/types/gulp-load-plugins/tsconfig.json index ba1a293ff2..880ad1acd1 100644 --- a/types/gulp-load-plugins/tsconfig.json +++ b/types/gulp-load-plugins/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-minify-css/tsconfig.json b/types/gulp-minify-css/tsconfig.json index d819c27e96..ccb2e4b319 100644 --- a/types/gulp-minify-css/tsconfig.json +++ b/types/gulp-minify-css/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-minify-html/tsconfig.json b/types/gulp-minify-html/tsconfig.json index 76d980ea8d..80ef59bff4 100644 --- a/types/gulp-minify-html/tsconfig.json +++ b/types/gulp-minify-html/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-mocha/tsconfig.json b/types/gulp-mocha/tsconfig.json index 273fda23a6..52b200e921 100644 --- a/types/gulp-mocha/tsconfig.json +++ b/types/gulp-mocha/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-newer/tsconfig.json b/types/gulp-newer/tsconfig.json index 6b5366c6c6..c139e12412 100644 --- a/types/gulp-newer/tsconfig.json +++ b/types/gulp-newer/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-ng-annotate/tsconfig.json b/types/gulp-ng-annotate/tsconfig.json index 63cd5003e0..1b7db8f980 100644 --- a/types/gulp-ng-annotate/tsconfig.json +++ b/types/gulp-ng-annotate/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-nodemon/tsconfig.json b/types/gulp-nodemon/tsconfig.json index 46bb88dd05..af6e7a7991 100644 --- a/types/gulp-nodemon/tsconfig.json +++ b/types/gulp-nodemon/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-plumber/tsconfig.json b/types/gulp-plumber/tsconfig.json index 2ba3904c26..ad53d6fde5 100644 --- a/types/gulp-plumber/tsconfig.json +++ b/types/gulp-plumber/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-protractor/tsconfig.json b/types/gulp-protractor/tsconfig.json index 26c6e1555d..bb39acdbdc 100644 --- a/types/gulp-protractor/tsconfig.json +++ b/types/gulp-protractor/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-remember/tsconfig.json b/types/gulp-remember/tsconfig.json index b4aab06a9a..02070e1b82 100644 --- a/types/gulp-remember/tsconfig.json +++ b/types/gulp-remember/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-rename/tsconfig.json b/types/gulp-rename/tsconfig.json index 41e681e145..b9b34366ee 100644 --- a/types/gulp-rename/tsconfig.json +++ b/types/gulp-rename/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-replace/tsconfig.json b/types/gulp-replace/tsconfig.json index dc8f1136a6..5d188a1919 100644 --- a/types/gulp-replace/tsconfig.json +++ b/types/gulp-replace/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-rev-replace/tsconfig.json b/types/gulp-rev-replace/tsconfig.json index 3b2af8ba17..c9a020605c 100644 --- a/types/gulp-rev-replace/tsconfig.json +++ b/types/gulp-rev-replace/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-rev/tsconfig.json b/types/gulp-rev/tsconfig.json index 067b8c92f9..fac8396ef8 100644 --- a/types/gulp-rev/tsconfig.json +++ b/types/gulp-rev/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-ruby-sass/tsconfig.json b/types/gulp-ruby-sass/tsconfig.json index 75580fe986..947482e45c 100644 --- a/types/gulp-ruby-sass/tsconfig.json +++ b/types/gulp-ruby-sass/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-sass/tsconfig.json b/types/gulp-sass/tsconfig.json index efe0eabef2..311d0e2615 100644 --- a/types/gulp-sass/tsconfig.json +++ b/types/gulp-sass/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-shell/tsconfig.json b/types/gulp-shell/tsconfig.json index 98b9e954ff..d9797a8f28 100644 --- a/types/gulp-shell/tsconfig.json +++ b/types/gulp-shell/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-size/tsconfig.json b/types/gulp-size/tsconfig.json index f8cd52f4a8..2d84cb001c 100644 --- a/types/gulp-size/tsconfig.json +++ b/types/gulp-size/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-sort/tsconfig.json b/types/gulp-sort/tsconfig.json index 0292a80e42..df1ddc44e4 100644 --- a/types/gulp-sort/tsconfig.json +++ b/types/gulp-sort/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-sourcemaps/tsconfig.json b/types/gulp-sourcemaps/tsconfig.json index f5120afcf2..198b428937 100644 --- a/types/gulp-sourcemaps/tsconfig.json +++ b/types/gulp-sourcemaps/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-strip-debug/tsconfig.json b/types/gulp-strip-debug/tsconfig.json index 6fbe80a409..ad5d90ca69 100644 --- a/types/gulp-strip-debug/tsconfig.json +++ b/types/gulp-strip-debug/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-svg-sprite/tsconfig.json b/types/gulp-svg-sprite/tsconfig.json index 7e048c457d..ed703e4c09 100644 --- a/types/gulp-svg-sprite/tsconfig.json +++ b/types/gulp-svg-sprite/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-task-listing/tsconfig.json b/types/gulp-task-listing/tsconfig.json index 28850e65d1..6d99b2f3f2 100644 --- a/types/gulp-task-listing/tsconfig.json +++ b/types/gulp-task-listing/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-tsd/tsconfig.json b/types/gulp-tsd/tsconfig.json index b935f8e5e5..692c21e642 100644 --- a/types/gulp-tsd/tsconfig.json +++ b/types/gulp-tsd/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-tslint/tsconfig.json b/types/gulp-tslint/tsconfig.json index 117173c83d..9ffec0b2cc 100644 --- a/types/gulp-tslint/tsconfig.json +++ b/types/gulp-tslint/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-typedoc/tsconfig.json b/types/gulp-typedoc/tsconfig.json index 5fce39a6e5..04b9015fc3 100644 --- a/types/gulp-typedoc/tsconfig.json +++ b/types/gulp-typedoc/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-useref/tsconfig.json b/types/gulp-useref/tsconfig.json index ee962cd194..cdb7922c57 100644 --- a/types/gulp-useref/tsconfig.json +++ b/types/gulp-useref/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-util/tsconfig.json b/types/gulp-util/tsconfig.json index 66cca3e125..f383866019 100644 --- a/types/gulp-util/tsconfig.json +++ b/types/gulp-util/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-watch/tsconfig.json b/types/gulp-watch/tsconfig.json index 9dc56e0f0c..079cb9d569 100644 --- a/types/gulp-watch/tsconfig.json +++ b/types/gulp-watch/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp/v3/index.d.ts b/types/gulp/v3/index.d.ts index 4abdba21ed..98a26d040d 100644 --- a/types/gulp/v3/index.d.ts +++ b/types/gulp/v3/index.d.ts @@ -2,6 +2,7 @@ // Project: http://gulpjs.com // Definitions by: Drew Noakes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/gulp/v3/tsconfig.json b/types/gulp/v3/tsconfig.json index 1a7d4547b7..31412b46c3 100644 --- a/types/gulp/v3/tsconfig.json +++ b/types/gulp/v3/tsconfig.json @@ -15,9 +15,6 @@ "paths": { "gulp": [ "gulp/v3" - ], - "q": [ - "q/v0" ] }, "types": [], diff --git a/types/gzip-size/gzip-size-tests.ts b/types/gzip-size/gzip-size-tests.ts index f07d99bd50..70ea15b5e6 100644 --- a/types/gzip-size/gzip-size-tests.ts +++ b/types/gzip-size/gzip-size-tests.ts @@ -1,7 +1,16 @@ +import fs = require('fs'); import gzipSize = require('gzip-size'); const string = 'Lorem ipsum dolor sit amet.'; console.log(string.length); +gzipSize(string).then(size => console.log(size)); + console.log(gzipSize.sync(string)); + +const stream = fs.createReadStream("index.d.ts"); +const gstream = stream.pipe(gzipSize.stream()).on("gzip-size", size => console.log(size)); +console.log(gstream.gzipSize); // Could be a number or undefined. Recommended to use "gzip-size" event instead + +gzipSize.file("index.d.ts").then(size => console.log(size)); diff --git a/types/gzip-size/index.d.ts b/types/gzip-size/index.d.ts index 12b1899b54..66251e0da8 100644 --- a/types/gzip-size/index.d.ts +++ b/types/gzip-size/index.d.ts @@ -1,13 +1,54 @@ -// Type definitions for gzip-size 3.0 +// Type definitions for gzip-size 4.1 // Project: https://github.com/sindresorhus/gzip-size // Definitions by: York Yao +// Jimi van der Woning +// Andre Wiggins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function gzipSize(input: string | Buffer, callback: (error: Error, size: number) => void): string; -export = gzipSize; -declare namespace gzipSize { - function sync(input: string | Buffer): number; - function stream(): NodeJS.ReadWriteStream; +import * as stream from 'stream'; +import * as zlib from 'zlib'; + +interface GzipSizeStream extends stream.PassThrough { + on(event: string, listener: (...args: any[]) => void): this; + on(event: "gzip-size", listener: (size: number) => void): this; + + /** + * Contains the gzip size of the stream after it is finished. + * Since this happens asynchronously, it is recommended you use + * the `.on("gzip-size", size => console.log(size))` method instead + */ + gzipSize?: number; } + +/** + * Returns a Promise for the size. + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ +declare function gzipSize(input: string | Buffer, options?: zlib.ZlibOptions): Promise; + +declare namespace gzipSize { + /** + * Returns the size synchronously + * @param input A string or Buffer to determine the gzip size of + * @param options Any zlib option + */ + function sync(input: string | Buffer, options?: zlib.ZlibOptions): number; + + /** + * Returns a stream.PassThrough. The stream emits a gzip-size event and has a gzipSize property. + * @param options Any zlib option + */ + function stream(options?: zlib.ZlibOptions): GzipSizeStream; + + /** + * Returns a Promise for the size of the file. + * @param path The path to the file + * @param options Any zlib option + */ + function file(path: string, options?: zlib.ZlibOptions): Promise; +} + +export = gzipSize; diff --git a/types/gzip-size/v3/gzip-size-tests.ts b/types/gzip-size/v3/gzip-size-tests.ts new file mode 100644 index 0000000000..f07d99bd50 --- /dev/null +++ b/types/gzip-size/v3/gzip-size-tests.ts @@ -0,0 +1,7 @@ +import gzipSize = require('gzip-size'); + +const string = 'Lorem ipsum dolor sit amet.'; + +console.log(string.length); + +console.log(gzipSize.sync(string)); diff --git a/types/gzip-size/v3/index.d.ts b/types/gzip-size/v3/index.d.ts new file mode 100644 index 0000000000..12b1899b54 --- /dev/null +++ b/types/gzip-size/v3/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for gzip-size 3.0 +// Project: https://github.com/sindresorhus/gzip-size +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function gzipSize(input: string | Buffer, callback: (error: Error, size: number) => void): string; +export = gzipSize; +declare namespace gzipSize { + function sync(input: string | Buffer): number; + function stream(): NodeJS.ReadWriteStream; +} diff --git a/types/gzip-size/v3/tsconfig.json b/types/gzip-size/v3/tsconfig.json new file mode 100644 index 0000000000..88a695711b --- /dev/null +++ b/types/gzip-size/v3/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "gzip-size": [ + "gzip-size/v3" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gzip-size-tests.ts" + ] +} diff --git a/types/gzip-size/v3/tslint.json b/types/gzip-size/v3/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gzip-size/v3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts index 881b75c0a8..aeb7652183 100644 --- a/types/h2o2/index.d.ts +++ b/types/h2o2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/catbox // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts index 07c3c8cc20..54d463c2b3 100644 --- a/types/hapi-auth-basic/index.d.ts +++ b/types/hapi-auth-basic/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/hapi-auth-basic // Definitions by: AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as Hapi from 'hapi'; diff --git a/types/hapi-auth-jwt2/index.d.ts b/types/hapi-auth-jwt2/index.d.ts index 4d5f6b2cd4..91e8ef931e 100644 --- a/types/hapi-auth-jwt2/index.d.ts +++ b/types/hapi-auth-jwt2/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/dwyl/hapi-auth-jwt2 // Definitions by: Warren Seymour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + import { Request, Response, PluginFunction } from 'hapi'; declare namespace hapiAuthJwt2 { diff --git a/types/hapi-decorators/index.d.ts b/types/hapi-decorators/index.d.ts index 4cd98beda8..473e28420f 100644 --- a/types/hapi-decorators/index.d.ts +++ b/types/hapi-decorators/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/knownasilya/hapi-decorators // Definitions by: Ken Howard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as hapi from 'hapi'; import * as Joi from 'joi'; diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index f996967691..a97a9f1edb 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/hapi // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/haversine/haversine-tests.ts b/types/haversine/haversine-tests.ts index 043d7d5898..5c068ea4b3 100644 --- a/types/haversine/haversine-tests.ts +++ b/types/haversine/haversine-tests.ts @@ -1,11 +1,11 @@ import haversine = require('haversine'); -const start: haversine.Coordinate = { +const start: haversine.CoordinateLongitudeLatitude = { longitude: 48.1548256, latitude: 11.4017529 }; -const end: haversine.Coordinate = { +const end: haversine.CoordinateLongitudeLatitude = { longitude: 52.5065133, latitude: 13.1445551 }; @@ -16,3 +16,51 @@ const options: haversine.Options = { }; haversine(start, end, options); + +const startShort: haversine.CoordinateLonLat = { + lon: 48.1548256, + lat: 11.4017529 +}; + +const endShort: haversine.CoordinateLonLat = { + lon: 52.5065133, + lat: 13.1445551 +}; + +const optionsShort: haversine.Options = { + format: '{lon,lat}' +}; + +haversine(startShort, endShort, optionsShort); + +const startLatLon: haversine.LatLonTuple = [11.4017529, 48.1548256]; + +const endLatLon: haversine.LatLonTuple = [13.1445551, 52.5065133]; + +const optionsLatLon: haversine.Options = { + format: '[lat,lon]' +}; + +haversine(startLatLon, endLatLon, optionsLatLon); + +const startGeoJSON = { + type: "Feature", + geometry: { + type: "LineString", + coordinates: startLatLon + } +}; + +const endGeoJSON = { + type: "Feature", + geometry: { + type: "LineString", + coordinates: endLatLon + } +}; + +const optionsGeoJSON: haversine.Options = { + format: 'geojson' +}; + +haversine(startGeoJSON, endGeoJSON, optionsGeoJSON); diff --git a/types/haversine/index.d.ts b/types/haversine/index.d.ts index 6fed860d8b..5f6d1e9173 100644 --- a/types/haversine/index.d.ts +++ b/types/haversine/index.d.ts @@ -1,14 +1,29 @@ -// Type definitions for haversine 1.0 +// Type definitions for haversine 1.1 // Project: https://github.com/njj/haversine // Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace haversine { - interface Coordinate { + interface CoordinateLongitudeLatitude { longitude: number; latitude: number; } + interface CoordinateLonLat { + lon: number; + lat: number; + } + + type LatLonTuple = [number, number]; + + interface GeoJSON { + geometry: { + coordinates: LatLonTuple + }; + } + + type Coordinate = (CoordinateLongitudeLatitude | CoordinateLonLat | LatLonTuple | GeoJSON); + interface Options { /** * Unit of measurement applied to result. Default: "km". @@ -18,6 +33,10 @@ declare namespace haversine { * If passed, will result in library returning boolean value of whether or not the start and end points are within that supplied threshold. Default: null. */ threshold?: number; + /** + * Format of coordinate arguments. + */ + format?: '[lat,lon]' | '[lon,lat]' | '{lon,lat}' | 'geojson'; } } diff --git a/types/heatmap.js/index.d.ts b/types/heatmap.js/index.d.ts index 60ee16c4f0..e6c0a4aec1 100644 --- a/types/heatmap.js/index.d.ts +++ b/types/heatmap.js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/pa7/heatmap.js/ // Definitions by: Yang Guan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Leaflet from "leaflet"; diff --git a/types/heredatalens/index.d.ts b/types/heredatalens/index.d.ts index 2dd5add457..cb9a4d7807 100644 --- a/types/heredatalens/index.d.ts +++ b/types/heredatalens/index.d.ts @@ -2,6 +2,7 @@ // Project: https://developer.here.com/ // Definitions by: Bernd Hacker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -140,7 +141,7 @@ declare namespace H.datalens { /** Column names */ columns: string[]; /** Rows of data */ - rows: [any[]]; + rows: any[][]; } } diff --git a/types/heremaps/heremaps-tests.ts b/types/heremaps/heremaps-tests.ts index 0856cd2616..9e92b92d72 100644 --- a/types/heremaps/heremaps-tests.ts +++ b/types/heremaps/heremaps-tests.ts @@ -179,3 +179,16 @@ pixelProjection.rescale(12); const point = pixelProjection.geoToPixel({ lat: 53, lng: 12 }); pixelProjection.xyToGeo(point.x, point.y); + +const engine = map.getEngine(); +engine.getAnimationDuration(); +engine.setAnimationDuration(1000); + +engine.getAnimationEase(); +engine.setAnimationEase(H.util.animation.ease.EASE_IN_QUAD); + +const engineListener = (e: Event) => { + console.log(e); +}; +engine.addEventListener('tap', engineListener); +engine.removeEventListener('tap', engineListener); diff --git a/types/heremaps/index.d.ts b/types/heremaps/index.d.ts index 0bda913919..8b68f11278 100644 --- a/types/heremaps/index.d.ts +++ b/types/heremaps/index.d.ts @@ -264,6 +264,12 @@ declare namespace H { * @param opt_scope {Object=} - An optional scope to call the callback in. */ addOnDisposeCallback(callback: () => void, opt_scope?: {}): void; + + /** + * This returns the map's render engine + * @return {H.map.render.p2d.RenderEngine} - map render engine + */ + getEngine(): H.map.render.p2d.RenderEngine; } namespace Map { @@ -3606,6 +3612,261 @@ declare namespace H { } } } + + namespace render { + /** + * This is an abstract class representing a render engine. Render engines are used to render the geographical position from a view model on the + * screen (viewport element). The rendered result may be different for different engines, because every engine uses its own capabilities and + * specific implementation to present the current view model data in best possible way. For example, 2D engines create a two-dimensional flat + * map composed of tiles, while 3D engines can generate panoramas displaying the same coordinates as a 'street view'. + */ + class RenderEngine extends H.util.EventTarget { + /** + * Constructor + * @param viewPort {H.map.ViewPort} - An object representing the map viewport + * @param viewModel {H.map.ViewModel} - An object representing a view of the map + * @param dataModel {H.map.DataModel} - An object encapsulating the data to be rendered on the map (layers and objects) + * @param options {H.map.render.RenderEngine.Options} - An object containing the render engine initialization options + */ + constructor(viewPort: H.map.ViewPort, viewModel: H.map.ViewModel, dataModel: H.map.DataModel, options: H.map.render.RenderEngine.Options); + + /** + * This method adds a listener for a specific event. + * Note that to prevent potential memory leaks, you must either call removeEventListener or dispose on the given object when you no longer need it. + * @param type {string} - The name of the event + * @param handler {!Function} - An event handler function + * @param opt_capture {boolean=} - true indicates that the method should listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - An object defining the scope for the handler function + */ + addEventListener(type: string, handler: (evt: Event) => void, opt_capture?: boolean, opt_scope?: {}): void; + + /** + * This method removes a previously added listener from the EventTarget instance. + * @param type {string} - The name of the event + * @param handler {!Function} - A previously added event handler + * @param opt_capture {boolean=} - true indicates that the method should listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - An object defining the scope for the handler function + */ + removeEventListener(type: string, handler: (evt: Event) => void, opt_capture?: boolean, opt_scope?: {}): void; + + /** + * This method dispatches an event on the EventTarget object. + * @param evt {H.util.Event|string} - An object representing the event or a string with the event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * This method removes listeners from the given object. Classes that extend EventTarget may need to override this method in order to remove + * references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds a callback which is triggered when the EventTarget object is being disposed. + * @param callback {!Function} - The callback function. + * @param opt_scope {Object=} - An optional scope for the callback function + */ + addOnDisposeCallback(callback: () => void, opt_scope?: {}): void; + } + + namespace RenderEngine { + /** + * An object containing the render engine initialization options + */ + interface Options { + [key: string]: string; + } + + /** + * This object defines the modifiers to use for H.map.ViewPort#startInteraction. + */ + enum InteractionModifiers { + /** changes zoom level during the interaction */ + ZOOM, + /** changes map center during the interaction */ + HEADING, + /** changes heading angle during the interaction */ + TILT, + /** changes tilt angle during the interaction */ + INCLINE, + /** changes incline angle during the interaction */ + COORD, + } + } + + /** + * The rendering states of the layer. + */ + enum RenderState { + /** + * Data loading/processing is still in progress, but there is nothing to render. In this state rendering engine might go to sleep mode after + * certain amount of time to prevent draining of battery on the user device. + */ + PENDING, + /** Data rendering or animation is in progress. */ + ACTIVE, + /** Data rendering or animation is done. */ + DONE, + } + + /** + * An object containing rendering parameters. + */ + interface RenderingParams { + /** + * The geographical area to render. Note that it is not the same as visible viewport. Specified bounds also include H.Map.Options#margin and + * optionally an additional margin in case of DOM node rendering for a better rendering experience. + * @type {H.geo.Rect} + */ + bounds: H.geo.Rect; + + /** + * The zoom level to render the data for. + * @type {number} + */ + zoom: number; + + /** + * The coordinates of the screen center in CSS pixels. + * @type {H.math.Point} + */ + screenCenter: H.math.Point; + + /** + * The coordinates relative to the screen center where the rendering has the highest priority. If the layer has to request and/or process data + * asynchronously, it's recommended to prioritize the rendering close to this center. + * @type {H.math.Point} + */ + priorityCenter: H.math.Point; + + /** + * The pixel projection to use to project geographical coordinates into screen coordinates and vice versa. + * @type {H.geo.PixelProjection} + */ + projection: H.geo.PixelProjection; + + /** + * Indicates whether only cached data should be considered. + * @type {boolean} + */ + cacheOnly: boolean; + + /** + * The size of the area to render. + * @type {H.math.Size} + */ + size: H.math.Size; + + /** + * The pixelRatio to use for over-sampling in cases of high-resolution displays. + * See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio. + * @type {number} + */ + pixelRatio: number; + } + + /** + * Contains functionality specific to 2D map rendering. + */ + namespace p2d { + /** + * This class implements a map render engine. It presents a geographic location (camera data from a view model) and renders all map layers in + * the order in which they are provided in a single 2D canvas element. + */ + class RenderEngine extends H.map.render.RenderEngine { + /** + * Constructor + * @param viewPort {H.map.ViewPort} - An object representing the map viewport + * @param viewModel {H.map.ViewModel} - An object representing a view of the map + * @param dataModel {H.map.DataModel} - An object encapsulating the data to be rendered on the map (layers and objects) + * @param options {H.map.render.RenderEngine.Options} - An object containing the render engine initialization options + */ + constructor(viewPort: H.map.ViewPort, viewModel: H.map.ViewModel, dataModel: H.map.DataModel, options: H.map.render.RenderEngine.Options); + + /** + * This method sets the length (duration) for all animations run by the render engine in milliseconds. + * @param duration {number} - A value indicating the duration of animations in milliseconds + */ + setAnimationDuration(duration: number): void; + + /** + * This method retrieves the current setting indicating the length of animations (duration) run by the the render engine in milliseconds. + * @return {number} + */ + getAnimationDuration(): number; + + /** + * This method sets a value indicating the easing to apply to animations run by the render engine. + * @param easeFunction {Function(number)} - A function that alters the progress ratio of an animation. It receives an argument indicating + * animation progress as a numeric value in the range between 0 and 1 and must return a numeric value in the same range. + */ + setAnimationEase(easeFunction: (progress: number) => number): void; + + /** + * This method retrieves the current setting representing the easing to be applied to animations. + * @return {Function(number) => number} - A numeric value in the range 0 to 1 + */ + getAnimationEase(): (progress: number) => number; + + /** + * This method resets animation settings on the render engine to defaults. + * Duration is set to 300ms and easing to H.util.animation.ease.EASE_OUT_QUAD. + */ + resetAnimationDefaults(): void; + + /** + * This method adds a listener for a specific event. + * Note that to prevent potential memory leaks, you must either call removeEventListener or dispose on the given object when you no longer need it. + * @param type {string} - The name of the event + * @param handler {!Function} - An event handler function + * @param opt_capture {boolean=} - true indicates that the method should listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - An object defining the scope for the handler function + */ + addEventListener(type: string, handler: (evt: Event) => void, opt_capture?: boolean, opt_scope?: {}): void; + + /** + * This method removes a previously added listener from the EventTarget instance. + * @param type {string} - The name of the event + * @param handler {!Function} - A previously added event handler + * @param opt_capture {boolean=} - true indicates that the method should listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - An object defining the scope for the handler function + */ + removeEventListener(type: string, handler: (evt: Event) => void, opt_capture?: boolean, opt_scope?: {}): void; + + /** + * This method dispatches an event on the EventTarget object. + * @param evt {H.util.Event|string} - An object representing the event or a string with the event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * This method removes listeners from the given object. Classes that extend EventTarget may need to override this method in order to remove + * references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds a callback which is triggered when the EventTarget object is being disposed. + * @param callback {!Function} - The callback function. + * @param opt_scope {Object=} - An optional scope for the callback function + */ + addOnDisposeCallback(callback: () => void, opt_scope?: {}): void; + } + + namespace RenderEngine { + interface Options { + /** Object describes how many cached zoom levels should be used as a base map background while base map tiles are */ + renderBaseBackground?: {}; + + /** The pixelRatio to use for over-sampling in cases of high-resolution displays */ + pixelRatio: number; + + /** optional */ + enableSubpixelRendering?: boolean; + } + } + } + } } /***** mapevents *****/ diff --git a/types/hex-rgba/hex-rgba-tests.ts b/types/hex-rgba/hex-rgba-tests.ts new file mode 100644 index 0000000000..f7ee8cf285 --- /dev/null +++ b/types/hex-rgba/hex-rgba-tests.ts @@ -0,0 +1,3 @@ +import hexToRgba = require('hex-rgba'); + +const rgba = hexToRgba('#1b2b34', 40); diff --git a/types/hex-rgba/index.d.ts b/types/hex-rgba/index.d.ts new file mode 100644 index 0000000000..ba4205a73f --- /dev/null +++ b/types/hex-rgba/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for hex-rgba 1.0 +// Project: https://github.com/developersoul/hex-rgba#readme +// Definitions by: Andrew Makarov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hexToRgba; + +declare function hexToRgba(hex: string, opacity: number): string; diff --git a/types/hex-rgba/tsconfig.json b/types/hex-rgba/tsconfig.json new file mode 100644 index 0000000000..82f2e3808e --- /dev/null +++ b/types/hex-rgba/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "hex-rgba-tests.ts" + ] +} diff --git a/types/hex-rgba/tslint.json b/types/hex-rgba/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hex-rgba/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hexo-bunyan/index.d.ts b/types/hexo-bunyan/index.d.ts index fb39ec6684..ea2df7a378 100644 --- a/types/hexo-bunyan/index.d.ts +++ b/types/hexo-bunyan/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/trentm/node-bunyan#readme // Definitions by: segayuu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import bunyan = require("bunyan"); diff --git a/types/hexo-fs/index.d.ts b/types/hexo-fs/index.d.ts index 25fd7d706b..46c7b99d64 100644 --- a/types/hexo-fs/index.d.ts +++ b/types/hexo-fs/index.d.ts @@ -2,7 +2,7 @@ // Project: http://hexo.io/ // Definitions by: segayuu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import Promise = require('bluebird'); import { diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 9b2087b651..f7f3759432 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -507,7 +507,7 @@ declare namespace Highcharts { * The actual text of the axis title. It can contain basic HTML text markup like , and spans with style. * @default xAxis: null, yAxis: 'Values' */ - text?: string; + text?: string | null; /** * Horizontal pixel offset of the title position. * @default 0 @@ -1021,9 +1021,9 @@ declare namespace Highcharts { */ tickmarkPlacement?: string; /** - * The axis title, showing next to the axis line. + * The axis title, showing next to the axis line. To disable the title, set the text to null. */ - title?: AxisTitle; + title?: AxisTitle | null; /** * The type of axis. Can be one of 'linear', 'logarithmic', 'datetime' or 'category'. In a datetime axis, the * numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a @@ -1036,7 +1036,7 @@ declare namespace Highcharts { * Datetime axis only. An array determining what time intervals the ticks are allowed to fall on. Each array item is * an array where the first value is the time unit and the second value another array of allowed multiples. */ - units?: [[string, [number]]]; + units?: Array<[string, number[]]>; /** * Whether axis, including axis title, line, ticks and labels, should be visible. * @default true @@ -1753,9 +1753,6 @@ declare namespace Highcharts { * @deprecated */ defaultSeriesType?: string; - /** - * - */ description?: string; /** * Event listeners for the chart. @@ -2043,7 +2040,7 @@ declare namespace Highcharts { * switchRowsAndColumns is set, the columns are interpreted as series. * @since 4.0 */ - columns?: Array<[string | number]>; + columns?: Array>; /** * The callback that is evaluated when the data is finished loading, optionally from an external source, and parsed. * The first argument passed is a finished chart options object, containing the series. These options can be @@ -3666,9 +3663,6 @@ declare namespace Highcharts { * @default 0.1 */ brightness?: number; - /** - * - */ color?: string | Gradient; /** * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the @@ -5272,6 +5266,9 @@ declare namespace Highcharts { * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) */ interface IndividualSeriesOptions { + size?: number | string; + innerSize?: number | string; + type?: string; /** * The main color or the series. In line type series it applies to the line and the point markers unless otherwise @@ -5614,7 +5611,7 @@ declare namespace Highcharts { * The title of the chart. To disable the title, set the text to null. * @default 'Chart title' */ - text?: string; + text?: string | null; /** * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the text. * @default false @@ -6581,7 +6578,7 @@ declare namespace Highcharts { * a subset is supported: absolute moveTo (M), absolute lineTo (L), absolute curveTo (C) and close (Z). * @param path An SVG path split up in array form. */ - path(path: [string | number]): ElementObject; + path(path: Array): ElementObject; /** * Add a rectangle. * @param x The x position of the rectangle's upper left corner. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index e96a0665e8..717e875362 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -1345,11 +1345,11 @@ function test_BoxPlot() { series: [{ name: 'Observations', data: [ - [760, 801, 848, 895, 965], - [733, 853, 939, 980, 1080], - [714, 762, 817, 870, 918], - [724, 802, 806, 871, 950], - [834, 836, 864, 882, 910] + 760, 801, 848, 895, 965, + 733, 853, 939, 980, 1080, + 714, 762, 817, 870, 918, + 724, 802, 806, 871, 950, + 834, 836, 864, 882, 910 ] }] }); diff --git a/types/highlight.js/index.d.ts b/types/highlight.js/index.d.ts index 7ae5d613fe..f96be1c06f 100644 --- a/types/highlight.js/index.d.ts +++ b/types/highlight.js/index.d.ts @@ -1,15 +1,19 @@ -// Type definitions for highlight.js v9.1.0 +// Type definitions for highlight.js v9.12 // Project: https://github.com/isagalaev/highlight.js -// Definitions by: Niklas Mollenhauer , Jeremy Hull +// Definitions by: Niklas Mollenhauer +// Jeremy Hull +// Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace hljs { + interface Node { } + export function highlight( name: string, value: string, ignore_illegals?: boolean, - continuation?: boolean) : IHighlightResult; + continuation?: ICompiledMode) : IHighlightResult; export function highlightAuto( value: string, languageSubset?: string[]) : IAutoHighlightResult; @@ -154,6 +158,6 @@ declare namespace hljs } } -declare module 'highlight.js' { - export = hljs; -} \ No newline at end of file + +export = hljs; +export as namespace hljs; diff --git a/types/highlight.js/tsconfig.json b/types/highlight.js/tsconfig.json index 5f5d2ae011..e3627e99ca 100644 --- a/types/highlight.js/tsconfig.json +++ b/types/highlight.js/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/history/index.d.ts b/types/history/index.d.ts index 528ab7ff21..eb15aaa0fc 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -18,7 +18,7 @@ export interface History { go(n: number): void; goBack(): void; goForward(): void; - block(prompt?: boolean): UnregisterCallback; + block(prompt?: boolean | string | TransitionPromptHook): UnregisterCallback; listen(listener: LocationListener): UnregisterCallback; createHref(location: LocationDescriptorObject): Href; } @@ -48,6 +48,7 @@ export namespace History { export type Pathname = string; export type Search = string; export type TransitionHook = (location: Location, callback: (result: any) => void) => any; + export type TransitionPromptHook = (location: Location, action: Action) => string | false | void; export type Hash = string; export type Href = string; } @@ -60,6 +61,7 @@ export type Path = History.Path; export type Pathname = History.Pathname; export type Search = History.Search; export type TransitionHook = History.TransitionHook; +export type TransitionPromptHook = History.TransitionPromptHook; export type Hash = History.Hash; export type Href = History.Href; diff --git a/types/holderjs/holderjs-tests.ts b/types/holderjs/holderjs-tests.ts new file mode 100644 index 0000000000..5a33d74aac --- /dev/null +++ b/types/holderjs/holderjs-tests.ts @@ -0,0 +1,7 @@ +import * as Holder from "holderjs"; + +const myImage = document.getElementById('myImage'); + +Holder.run({ + images: myImage +}); diff --git a/types/holderjs/index.d.ts b/types/holderjs/index.d.ts new file mode 100644 index 0000000000..a77d5cda60 --- /dev/null +++ b/types/holderjs/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for holderjs 2.9 +// Project: http://holderjs.com +// Definitions by: Soner Köksal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Options { + images: HTMLElement | null; +} + +export function run(options: Options): void; diff --git a/types/holderjs/tsconfig.json b/types/holderjs/tsconfig.json new file mode 100644 index 0000000000..6cf9415ee2 --- /dev/null +++ b/types/holderjs/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "holderjs-tests.ts" + ] +} diff --git a/types/holderjs/tslint.json b/types/holderjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/holderjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hpp/index.d.ts b/types/hpp/index.d.ts index 6328df7d70..18439ee488 100644 --- a/types/hpp/index.d.ts +++ b/types/hpp/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/analog-nico/hpp // Definitions by: Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as express from 'express'; diff --git a/types/html-webpack-plugin/html-webpack-plugin-tests.ts b/types/html-webpack-plugin/html-webpack-plugin-tests.ts index a84d19bea5..7a1e5f20bc 100644 --- a/types/html-webpack-plugin/html-webpack-plugin-tests.ts +++ b/types/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -19,6 +19,9 @@ const optionsArray: HtmlWebpackPlugin.Options[] = [ { arbitrary: 'data', }, + { + chunksSortMode: 'manual', + } ]; const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpackPlugin(options)); diff --git a/types/html-webpack-plugin/index.d.ts b/types/html-webpack-plugin/index.d.ts index b08a69faa5..dc23e020d7 100644 --- a/types/html-webpack-plugin/index.d.ts +++ b/types/html-webpack-plugin/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for html-webpack-plugin 2.28 +// Type definitions for html-webpack-plugin 2.30 // Project: https://github.com/ampedandwired/html-webpack-plugin -// Definitions by: Simon Hartcher , Benjamin Lim +// Definitions by: Simon Hartcher +// Benjamin Lim +// Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Plugin } from 'webpack'; @@ -35,9 +37,9 @@ declare namespace HtmlWebpackPlugin { cache?: boolean; /** * Allows to control how chunks should be sorted before they are included to the html. - * Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + * Allowed values: 'none' | 'auto' | 'dependency' |'manual' | {function} - default: 'auto' */ - chunksSortMode?: 'none' | 'auto' | 'dependency' | ChunkComparator; + chunksSortMode?: 'none' | 'auto' | 'dependency' | 'manual' | ChunkComparator; /** Allows you to add only some chunks (e.g. only the unit-test chunk) */ chunks?: string[]; /** Allows you to skip some chunks (e.g. don't add the unit-test chunk) */ diff --git a/types/http-assert/index.d.ts b/types/http-assert/index.d.ts index 4e9ca6657d..aac93be123 100644 --- a/types/http-assert/index.d.ts +++ b/types/http-assert/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jshttp/http-assert // Definitions by: jKey Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /** * @param status the status code diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index c14547a58f..91e12604f8 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/http-context/http-context-tests.ts b/types/http-context/http-context-tests.ts new file mode 100644 index 0000000000..1542f50e1e --- /dev/null +++ b/types/http-context/http-context-tests.ts @@ -0,0 +1,73 @@ +import http = require('http'); +import httpContext = require('http-context'); + +const context: httpContext.Context = httpContext(); +const request: httpContext.Request = context.request; +const response: httpContext.Response = context.response; + +let header: http.IncomingHttpHeaders = context.header; +header = context.headers; +header = request.header; +header = request.headers; +const headerString: string | string[] = header['Content-Type']; + +let url: string = context.url; +url = request.url; +context.accepts('html'); + +let href: string = context.href; +href = request.href; + +let method: string = context.method; +method = request.method; + +let path: string = context.path; +path = request.path; + +let query: {[param: string]: string | string[]} = context.query; +query = request.query; +const querySearch: string | string[] = query['search']; + +let queryString: string = context.querystring; +queryString = request.querystring; + +let search: string = context.search; +search = request.search; + +let host: string = context.host; +host = request.host; + +let hostname: string = context.hostname; +hostname = request.hostname; + +let fresh: boolean = context.fresh; +fresh = request.fresh; + +let idempotent: boolean = context.idempotent; +idempotent = request.idempotent; + +let protocol: string = context.protocol; +protocol = request.protocol; + +let secure: boolean = context.secure; +secure = request.secure; + +let subdomains: string[] = context.subdomains; +subdomains = request.subdomains; + +let accepts: string[] | string | false = context.accepts('text/html'); +accepts = request.accepts('text/html'); +accepts = request.accepts('text/html', 'text/txt'); +accepts = request.accepts(['text/html', 'text/txt']); + +let status: number = context.status; +status = response.status; + +let message: string = context.message; +message = response.message; + +let body: any = context.body; +body = response.body; + +let length: number = context.length; +length = response.length; diff --git a/types/http-context/index.d.ts b/types/http-context/index.d.ts new file mode 100644 index 0000000000..30aae4c99b --- /dev/null +++ b/types/http-context/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for http-context 1.1 +// Project: https://github.com/lapwinglabs/http-context#readme +// Definitions by: Matt Traynham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import accepts = require('accepts'); +import http = require('http'); + +export = HttpContext; + +declare function HttpContext(): HttpContext.Context; + +declare namespace HttpContext { + interface RequestJSON { + method: string; + url: string; + header: http.IncomingHttpHeaders; + } + + interface RequestDelegate { + header: http.IncomingHttpHeaders; + headers: http.IncomingHttpHeaders; + url: string; + href: string; + method: string; + path: string; + query: {[param: string]: string | string[]}; + querystring: string; + search: string; + host: string; + hostname: string; + fresh: boolean; + idempotent: boolean; + protocol: string; + secure: boolean; + subdomains: string[]; + accepts(types: string[]): string[] | string | false; + accepts(...types: string[]): string[] | string | false; + acceptsCharsets(charsets: string[]): string | false; + acceptsCharsets(...charsets: string[]): string | false; + acceptsEncodings(encodings: string[]): string | false; + acceptsEncodings(...encodings: string[]): string | false; + acceptsLanguages(languages: string[]): string | false; + acceptsLanguages(...languages: string[]): string | false; + is(types: string[]): string | false; + is(...types: string[]): string | false; + get(field: string): string; + } + + interface Request extends RequestDelegate { + request: http.IncomingMessage; + charset: string; + length: number; + type: string; + accept: accepts.Accepts; + inspect(): RequestJSON; + toJSON(): RequestJSON; + } + + interface ResponseJSON { + status: number; + message: string; + header: http.OutgoingHttpHeaders; + } + + interface ResponseDelegate { + status: number; + message: string; + body: any; + length: number; + headerSent: boolean; + type: string; + lastModified: string | Date; + etag: string; + writable: boolean; + vary(field: string): void; + redirect(url: string, alt: string): void; + attachment(filename: string): void; + set(field: string, val: string): void; + append(field: string, val: string[]): void; + append(field: string, ...val: string[]): void; + remove(field: string): void; + } + + interface Response extends ResponseDelegate { + response: http.OutgoingMessage; + header: http.OutgoingHttpHeaders; + is(types: string[]): string | false; + is(...types: string[]): string | false; + get(field: string): string; + inspect(): ResponseJSON; + toJSON(): ResponseJSON; + } + + interface Context extends RequestDelegate, ResponseDelegate { + request: Request; + response: Response; + } +} diff --git a/types/http-context/tsconfig.json b/types/http-context/tsconfig.json new file mode 100644 index 0000000000..51422e3199 --- /dev/null +++ b/types/http-context/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-context-tests.ts" + ] +} diff --git a/types/http-context/tslint.json b/types/http-context/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-context/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/http-proxy-agent/http-proxy-agent-tests.ts b/types/http-proxy-agent/http-proxy-agent-tests.ts new file mode 100644 index 0000000000..f730cd1bde --- /dev/null +++ b/types/http-proxy-agent/http-proxy-agent-tests.ts @@ -0,0 +1,12 @@ +import Agent = require('http-proxy-agent'); + +// $ExpectType HttpProxyAgent +new Agent('url'); +new Agent({}); +new Agent({ host: 'url' }); + +// $ExpectError +new Agent(); + +// $ExpectError +new Agent({ a: 1 }); diff --git a/types/http-proxy-agent/index.d.ts b/types/http-proxy-agent/index.d.ts new file mode 100644 index 0000000000..015508b5d1 --- /dev/null +++ b/types/http-proxy-agent/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for http-proxy-agent 2.0 +// Project: https://github.com/TooTallNate/node-http-proxy-agent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Agent } from 'http'; +import { Url } from 'url'; + +declare class HttpProxyAgent extends Agent { + constructor(options: string | Url); +} + +export = HttpProxyAgent; diff --git a/types/http-proxy-agent/tsconfig.json b/types/http-proxy-agent/tsconfig.json new file mode 100644 index 0000000000..626d4eaa4c --- /dev/null +++ b/types/http-proxy-agent/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-proxy-agent-tests.ts" + ] +} diff --git a/types/http-proxy-agent/tslint.json b/types/http-proxy-agent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-proxy-agent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index 370b3d1487..5db24429c9 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Zebulon McCorkle // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/hystrixjs/hystrixjs-tests.ts b/types/hystrixjs/hystrixjs-tests.ts index 676015be06..7ed7819fb7 100644 --- a/types/hystrixjs/hystrixjs-tests.ts +++ b/types/hystrixjs/hystrixjs-tests.ts @@ -4,7 +4,7 @@ import q = require('q'); var commandFactory = hystrixjs.commandFactory; var command = commandFactory - .getOrCreate('testCommand', 'testGroup') + .getOrCreate('testCommand', 'testGroup') .circuitBreakerSleepWindowInMilliseconds(5000) .errorHandler((error) => { return false; diff --git a/types/hystrixjs/index.d.ts b/types/hystrixjs/index.d.ts index b11305c13b..b49cd40ba4 100644 --- a/types/hystrixjs/index.d.ts +++ b/types/hystrixjs/index.d.ts @@ -2,8 +2,8 @@ // Project: https://bitbucket.org/igor_sechyn/hystrixjs // Definitions by: Igor Sechyn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -import * as Q from "q"; import * as RX from "rx"; export as namespace hystrixjs; @@ -22,7 +22,8 @@ export interface HystrixProperties { "hystrix.metrics.statistical.window.bucketsNumber"?: number, "hystrix.metrics.percentile.window.timeInMilliseconds"?: number, "hystrix.metrics.percentile.window.bucketsNumber"?: number, - "hystrix.request.volume.rejectionThreshold"?: number + "hystrix.request.volume.rejectionThreshold"?: number, + "hystrix.promise.implementation"?: PromiseConstructorLike, } export interface HystrixConfig { @@ -45,7 +46,39 @@ export interface HystrixConfig { } export interface Command { - execute(...args: any[]): Q.Promise; + execute(...args: any[]): PromiseLike +} + +export interface CommandA0 { + execute(): PromiseLike +} + +export interface CommandA1 { + execute(t: T): PromiseLike +} + +export interface CommandA2 { + execute(t: T, u: U): PromiseLike +} + +export interface CommandA3 { + execute(t: T, u: U, v: V): PromiseLike +} + +export interface CommandA4 { + execute(t: T, u: U, v: V, w: W): PromiseLike +} + +export interface CommandA5 { + execute(t: T, u: U, v: V, w: W, x: X): PromiseLike +} + +export interface CommandA6 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y): PromiseLike +} + +export interface CommandA7 { + execute(t: T, u: U, v: V, w: W, x: X, y: Y, z: Z): PromiseLike } export interface CommandBuilder { @@ -61,14 +94,174 @@ export interface CommandBuilder { percentileWindowNumberOfBuckets(value: number): CommandBuilder; percentileWindowLength(value: number): CommandBuilder; circuitBreakerErrorThresholdPercentage(value: number): CommandBuilder; - run(value: (args: any) => Q.Promise): CommandBuilder; - fallbackTo(value: (...args: any[]) => Q.Promise): CommandBuilder; context(value: any): CommandBuilder; - build(): Command; + run(value: (...args: any[]) => PromiseLike): CommandBuilder; + fallbackTo(value: (error: Error, args ?: any[]) => PromiseLike): CommandBuilder; + build() : Command; +} + +export interface CommandBuilderA0 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA0; + errorHandler(value: (error: any) => boolean): CommandBuilderA0; + timeout(value: number): CommandBuilderA0; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA0; + requestVolumeRejectionThreshold(value: number): CommandBuilderA0; + circuitBreakerForceOpened(value: boolean): CommandBuilderA0; + circuitBreakerForceClosed(value: boolean): CommandBuilderA0; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA0; + statisticalWindowLength(value: number): CommandBuilderA0; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA0; + percentileWindowLength(value: number): CommandBuilderA0; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA0; + context(value: any): CommandBuilderA0; + run(value: () => PromiseLike): CommandBuilderA0; + fallbackTo(value: (error: Error) => PromiseLike): CommandBuilderA0; + build() : CommandA0; +} + +export interface CommandBuilderA1 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA1; + errorHandler(value: (error: any) => boolean): CommandBuilderA1; + timeout(value: number): CommandBuilderA1; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA1; + requestVolumeRejectionThreshold(value: number): CommandBuilderA1; + circuitBreakerForceOpened(value: boolean): CommandBuilderA1; + circuitBreakerForceClosed(value: boolean): CommandBuilderA1; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA1; + statisticalWindowLength(value: number): CommandBuilderA1; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA1; + percentileWindowLength(value: number): CommandBuilderA1; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA1; + context(value: any): CommandBuilderA1; + run(value: (t: T) => PromiseLike): CommandBuilderA1; + fallbackTo(value: (error: Error, args : [T]) => PromiseLike): CommandBuilderA1; + build(): CommandA1; +} + +export interface CommandBuilderA2 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA2; + errorHandler(value: (error: any) => boolean): CommandBuilderA2; + timeout(value: number): CommandBuilderA2; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA2; + requestVolumeRejectionThreshold(value: number): CommandBuilderA2; + circuitBreakerForceOpened(value: boolean): CommandBuilderA2; + circuitBreakerForceClosed(value: boolean): CommandBuilderA2; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA2; + statisticalWindowLength(value: number): CommandBuilderA2; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA2; + percentileWindowLength(value: number): CommandBuilderA2; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA2; + context(value: any): CommandBuilderA2; + run(value: (t: T, u: U) => PromiseLike): CommandBuilderA2; + fallbackTo(value: (error: Error, args: [T, U]) => PromiseLike): CommandBuilderA2; + build(): CommandA2; +} + +export interface CommandBuilderA3 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA3; + errorHandler(value: (error: any) => boolean): CommandBuilderA3; + timeout(value: number): CommandBuilderA3; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA3; + requestVolumeRejectionThreshold(value: number): CommandBuilderA3; + circuitBreakerForceOpened(value: boolean): CommandBuilderA3; + circuitBreakerForceClosed(value: boolean): CommandBuilderA3; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA3; + statisticalWindowLength(value: number): CommandBuilderA3; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA3; + percentileWindowLength(value: number): CommandBuilderA3; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA3; + context(value: any): CommandBuilderA3; + run(value: (t: T, u: U, v: V) => PromiseLike): CommandBuilderA3; + fallbackTo(value: (error: Error, args: [T, U, V]) => PromiseLike): CommandBuilderA3; + build(): CommandA3; +} + +export interface CommandBuilderA4 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA4; + errorHandler(value: (error: any) => boolean): CommandBuilderA4; + timeout(value: number): CommandBuilderA4; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA4; + requestVolumeRejectionThreshold(value: number): CommandBuilderA4; + circuitBreakerForceOpened(value: boolean): CommandBuilderA4; + circuitBreakerForceClosed(value: boolean): CommandBuilderA4; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA4; + statisticalWindowLength(value: number): CommandBuilderA4; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA4; + percentileWindowLength(value: number): CommandBuilderA4; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA4; + context(value: any): CommandBuilderA4; + run(value: (t: T, u: U, v: V, w: W) => PromiseLike): CommandBuilderA4; + fallbackTo(value: (error: Error, args: [T, U, V, W]) => PromiseLike): CommandBuilderA4; + build(): CommandA4; +} + +export interface CommandBuilderA5 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA5; + errorHandler(value: (error: any) => boolean): CommandBuilderA5; + timeout(value: number): CommandBuilderA5; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA5; + requestVolumeRejectionThreshold(value: number): CommandBuilderA5; + circuitBreakerForceOpened(value: boolean): CommandBuilderA5; + circuitBreakerForceClosed(value: boolean): CommandBuilderA5; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA5; + statisticalWindowLength(value: number): CommandBuilderA5; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA5; + percentileWindowLength(value: number): CommandBuilderA5; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA5; + context(value: any): CommandBuilderA5; + run(value: (t: T, u: U, v: V, w: W, x: X) => PromiseLike): CommandBuilderA5; + fallbackTo(value: (error: Error, args: [T, U, V, W, X]) => PromiseLike): CommandBuilderA5; + build(): CommandA5; +} + +export interface CommandBuilderA6 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA6; + errorHandler(value: (error: any) => boolean): CommandBuilderA6; + timeout(value: number): CommandBuilderA6; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA6; + requestVolumeRejectionThreshold(value: number): CommandBuilderA6; + circuitBreakerForceOpened(value: boolean): CommandBuilderA6; + circuitBreakerForceClosed(value: boolean): CommandBuilderA6; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA6; + statisticalWindowLength(value: number): CommandBuilderA6; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA6; + percentileWindowLength(value: number): CommandBuilderA6; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA6; + context(value: any): CommandBuilderA6; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y) => PromiseLike): CommandBuilderA6; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y]) => PromiseLike): CommandBuilderA6; + build(): CommandA6; +} + +export interface CommandBuilderA7 { + circuitBreakerSleepWindowInMilliseconds(value: number): CommandBuilderA7; + errorHandler(value: (error: any) => boolean): CommandBuilderA7; + timeout(value: number): CommandBuilderA7; + circuitBreakerRequestVolumeThreshold(value: number): CommandBuilderA7; + requestVolumeRejectionThreshold(value: number): CommandBuilderA7; + circuitBreakerForceOpened(value: boolean): CommandBuilderA7; + circuitBreakerForceClosed(value: boolean): CommandBuilderA7; + statisticalWindowNumberOfBuckets(value: number): CommandBuilderA7; + statisticalWindowLength(value: number): CommandBuilderA7; + percentileWindowNumberOfBuckets(value: number): CommandBuilderA7; + percentileWindowLength(value: number): CommandBuilderA7; + circuitBreakerErrorThresholdPercentage(value: number): CommandBuilderA7; + context(value: any): CommandBuilderA7; + run(value: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z) => PromiseLike): CommandBuilderA7; + fallbackTo(value: (error: Error, args: [T, U, V, W, X, Y, Z]) => PromiseLike): CommandBuilderA7; + build(): CommandA7; } export interface CommandFactory { getOrCreate(commandKey: string, commandGroup?: string): CommandBuilder; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA0; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA1; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA2; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA3; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA4; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA5; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA6; + getOrCreate(commandKey: string, commandGroup?: string): CommandBuilderA7; resetCache(): void; } @@ -140,4 +333,4 @@ export var commandFactory: CommandFactory; export var metricsFactory: MetricsFactory; export var circuitFactory: CircuitFactory; export var hystrixSSEStream: HystrixSSEStream; -export var hystrixConfig: HystrixConfig; \ No newline at end of file +export var hystrixConfig: HystrixConfig; diff --git a/types/hystrixjs/tsconfig.json b/types/hystrixjs/tsconfig.json index 0cf5de7b81..480476e8d1 100644 --- a/types/hystrixjs/tsconfig.json +++ b/types/hystrixjs/tsconfig.json @@ -13,11 +13,7 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, + "paths": {}, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true @@ -26,4 +22,4 @@ "index.d.ts", "hystrixjs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/i18n-js/i18n-js-tests.ts b/types/i18n-js/i18n-js-tests.ts new file mode 100644 index 0000000000..4f19dc4c02 --- /dev/null +++ b/types/i18n-js/i18n-js-tests.ts @@ -0,0 +1,81 @@ +/** + * Test suite created by Yuya Tanaka + * Created by using code examples from https://github.com/fnando/i18n-js + */ + +import I18n = require("i18n-js"); + +I18n.defaultLocale = "pt-BR"; +I18n.locale = "pt-BR"; +I18n.currentLocale() === "pt-BR"; + +I18n.t("some.scoped.translation"); +I18n.t("some.scoped.translation", { locale: "fr" }); +I18n.t("hello", { name: "John Doe" }); +I18n.t("some.missing.scope", { defaultValue: "A default message" }); +I18n.t("noun", { defaultValue: "I'm a {{noun}}", noun: "Mac" }); +I18n.t("some.missing.scope", { defaults: [{ scope: "some.existing.scope" }] }); +I18n.t("some.missing.scope", { defaults: [{ message: "Some message" }] }); + +I18n.fallbacks = true; +I18n.locales.no = ["nb", "en"]; +I18n.locales.no = "nb"; +I18n.locales.no = locale => ["nb"]; + +I18n.missingBehaviour = "guess"; +I18n.missingTranslationPrefix = "EE: "; +I18n.missingTranslation = (scope, options) => "foobar"; +I18n.missingTranslation = (scope, options) => null; +I18n.missingTranslation = (scope, options) => undefined; + +I18n.t("inbox.counting", { count: 10 }); +I18n.pluralization["ru"] = count => { + const key = count % 10 === 1 && count % 100 !== 11 ? "one" + : [2, 3, 4].indexOf(count % 10) >= 0 && [12, 13, 14].indexOf(count % 100) < 0 ? "few" + : count % 10 === 0 || [5, 6, 7, 8, 9].indexOf(count % 10) >= 0 || [11, 12, 13, 14].indexOf(count % 100) >= 0 ? "many" + : "other"; + return [key]; +}; + +const options = { scope: "activerecord.attributes.user" }; +I18n.t("name", options); +I18n.t(["greetings", "hello"]); + +I18n.l("currency", 1990.99); +I18n.l("number", 1990.99); +I18n.l("percentage", 123.45); + +I18n.toNumber(1000); +I18n.toCurrency(1000); +I18n.toPercentage(100); + +I18n.toNumber(1000, { precision: 0 }); +I18n.toNumber(1000, { delimiter: ".", separator: "," }); +I18n.toNumber(1000, { delimiter: ".", precision: 0 }); + +I18n.toCurrency(1000, { precision: 0 }); + +I18n.toHumanSize(1234); + +I18n.l("date.formats.short", "2009-09-18"); +I18n.l("time.formats.short", "2009-09-18 23:12:43"); +I18n.l("time.formats.short", "2009-11-09T18:10:34"); +I18n.l("time.formats.short", "2009-11-09T18:10:34Z"); +I18n.l("date.formats.short", 1251862029000); +I18n.l("date.formats.short", "09/18/2009"); +I18n.l("date.formats.short", (new Date())); + +I18n.l("date.formats.ordinal_day", "2009-09-18", { day: "18th" }); + +I18n.strftime(new Date(), "%d/%m/%Y"); + +const point_in_number = 1000; +I18n.t("point", { count: point_in_number, formatted_number: I18n.toNumber(point_in_number) }); + +I18n.translations = {}; +I18n.translations["en"] = { + message: "Some special message for you" +}; +I18n.translations["pt-BR"] = { + message: "Uma mensagem especial para você" +}; diff --git a/types/i18n-js/index.d.ts b/types/i18n-js/index.d.ts new file mode 100644 index 0000000000..4800125087 --- /dev/null +++ b/types/i18n-js/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for i18n-js 3.0 +// Project: https://github.com/fnando/i18n-js +// Definitions by: Yuya Tanaka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// tslint:disable-next-line:export-just-namespace +export = I18n; +export as namespace I18n; + +declare namespace I18n { + type Scope = string | string[]; + + let defaultLocale: string; + let locale: string; + let defaultSeparator: string; + let placeholder: RegExp; + let fallbacks: boolean; + let missingBehaviour: "message" | "guess"; + let missingTranslationPrefix: string; + + // tslint:disable-next-line prefer-declare-function + let missingTranslation: (scope: string, options?: TranslateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let missingPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + // tslint:disable-next-line prefer-declare-function + let nullPlaceholder: (placeholder: string, message: string, options?: InterpolateOptions) => string | null | undefined; + + let translations: { [locale: string]: object }; + let locales: { [key: string]: string | string[] | ((locale: string) => string | string[]) }; + let pluralization: { [locale: string]: (count: number) => string[] }; + + function reset(): void; + + function currentLocale(): string; + + interface InterpolateOptions { + [key: string]: any; // interpolation + } + + interface TranslateOptions extends InterpolateOptions { + scope?: Scope; + message?: string; + defaults?: Array<{ message: string } | { scope: Scope }>; + defaultValue?: string; + } + function translate(scope: Scope, options?: TranslateOptions): string; + function t(scope: Scope, options?: TranslateOptions): string; + + function localize(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function localize(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + function l(scope: "currency" | "number" | "percentage", value: number, options?: InterpolateOptions): string; + function l(scope: Scope, value: string | number | Date, options?: InterpolateOptions): string; + + interface ToNumberOptions { + precision?: number; + separator?: string; + delimiter?: string; + strip_insignificant_zeros?: boolean; + } + function toNumber(num: number, options?: ToNumberOptions): string; + + type ToPercentageOptions = ToNumberOptions; + function toPercentage(num: number, options?: ToPercentageOptions): string; + + interface ToCurrencyOptions extends ToNumberOptions { + format?: string; + unit?: string; + sign_first?: boolean; + } + function toCurrency(num: number, options?: ToCurrencyOptions): string; + + interface ToHumanSizeOptions extends ToNumberOptions { + format?: string; + } + function toHumanSize(num: number, options?: ToHumanSizeOptions): string; + + function strftime(date: Date, format: string): string; +} diff --git a/types/i18n-js/tsconfig.json b/types/i18n-js/tsconfig.json new file mode 100644 index 0000000000..4a9e4d110b --- /dev/null +++ b/types/i18n-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "i18n-js-tests.ts" + ] +} diff --git a/types/i18n-js/tslint.json b/types/i18n-js/tslint.json new file mode 100644 index 0000000000..299e93b32f --- /dev/null +++ b/types/i18n-js/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "indent": [true, "spaces", 4], + "quotemark": [true, "double", "avoid-escape"] + } +} diff --git a/types/i18n/index.d.ts b/types/i18n/index.d.ts index 0ddc39ffbf..ee0f3d584f 100644 --- a/types/i18n/index.d.ts +++ b/types/i18n/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Maxime LUCE // FindQ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 declare namespace i18n { interface ConfigurationOptions { diff --git a/types/i18next-browser-languagedetector/index.d.ts b/types/i18next-browser-languagedetector/index.d.ts index 1e85fd81e4..6eec150445 100644 --- a/types/i18next-browser-languagedetector/index.d.ts +++ b/types/i18next-browser-languagedetector/index.d.ts @@ -2,6 +2,7 @@ // Project: http://i18next.com/ // Definitions by: Cyril Schumacher , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace i18nextBrowserLanguageDetector { interface DetectorOptions { diff --git a/types/i18next-browser-languagedetector/v0/index.d.ts b/types/i18next-browser-languagedetector/v0/index.d.ts index 0bf62f8ace..9d8f58a52a 100644 --- a/types/i18next-browser-languagedetector/v0/index.d.ts +++ b/types/i18next-browser-languagedetector/v0/index.d.ts @@ -2,6 +2,7 @@ // Project: http://i18next.com/ // Definitions by: Cyril Schumacher , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as i18next from "i18next"; diff --git a/types/i18next-xhr-backend/index.d.ts b/types/i18next-xhr-backend/index.d.ts index a3190ca878..c4e8a41b4a 100644 --- a/types/i18next-xhr-backend/index.d.ts +++ b/types/i18next-xhr-backend/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/i18next/i18next-xhr-backend // Definitions by: Jan Mühlemann , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace I18NextXhrBackend { type LoadPathOption = string | ((lngs: string[], namespaces: string[]) => string); diff --git a/types/ignite-ui/index.d.ts b/types/ignite-ui/index.d.ts index f4125c44cb..bff55ec33d 100644 --- a/types/ignite-ui/index.d.ts +++ b/types/ignite-ui/index.d.ts @@ -26081,8 +26081,6 @@ interface IgNumericEditor { */ toUpper?: any; - /** - */ textMode?: any; /** @@ -26636,8 +26634,6 @@ interface IgCurrencyEditor { */ toUpper?: any; - /** - */ textMode?: any; /** @@ -27068,8 +27064,6 @@ interface IgPercentEditor { */ toUpper?: any; - /** - */ textMode?: any; /** @@ -27429,8 +27423,6 @@ interface IgMaskEditor { */ dropDownOnReadOnly?: boolean; - /** - */ textMode?: any; /** @@ -27928,8 +27920,6 @@ interface IgDateEditor { */ dropDownOrientation?: string; - /** - */ textMode?: any; /** @@ -28450,8 +28440,6 @@ interface IgDatePicker { */ dropDownOrientation?: string; - /** - */ textMode?: any; /** @@ -30868,12 +30856,8 @@ interface JQuery { */ igNumericEditor(optionLiteral: 'option', optionName: "toUpper", optionValue: any): void; - /** - */ igNumericEditor(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igNumericEditor(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** @@ -31777,12 +31761,8 @@ interface JQuery { */ igCurrencyEditor(optionLiteral: 'option', optionName: "toUpper", optionValue: any): void; - /** - */ igCurrencyEditor(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igCurrencyEditor(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** @@ -32563,12 +32543,8 @@ interface JQuery { */ igPercentEditor(optionLiteral: 'option', optionName: "toUpper", optionValue: any): void; - /** - */ igPercentEditor(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igPercentEditor(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** @@ -33206,12 +33182,8 @@ interface JQuery { */ igMaskEditor(optionLiteral: 'option', optionName: "dropDownOnReadOnly", optionValue: boolean): void; - /** - */ igMaskEditor(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igMaskEditor(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** @@ -34144,12 +34116,8 @@ interface JQuery { */ igDateEditor(optionLiteral: 'option', optionName: "dropDownOrientation", optionValue: string): void; - /** - */ igDateEditor(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igDateEditor(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** @@ -35092,12 +35060,8 @@ interface JQuery { */ igDatePicker(optionLiteral: 'option', optionName: "dropDownOrientation", optionValue: string): void; - /** - */ igDatePicker(optionLiteral: 'option', optionName: "textMode"): any; - /** - */ igDatePicker(optionLiteral: 'option', optionName: "textMode", optionValue: any): void; /** diff --git a/types/iltorb/iltorb-tests.ts b/types/iltorb/iltorb-tests.ts new file mode 100644 index 0000000000..5c30fcd3b5 --- /dev/null +++ b/types/iltorb/iltorb-tests.ts @@ -0,0 +1,36 @@ +import { createReadStream, createWriteStream } from 'fs'; +import * as br from 'iltorb'; + +const opts: br.BrotliEncodeParams = { + disable_literal_context_modeling: false, + lgblock: 0, + lgwin: 22, + mode: 0, + quality: 11, + size_hint: 0 +}; + +const onCompress = (err1: Error | null | undefined, compressed: Buffer) => { + br.decompress(compressed, (err2: Error | null | undefined, decompressed: Buffer) => { + console.log(decompressed.toString()); + }); +}; + +br.compress(Buffer.from('foo', 'utf8'), onCompress); + +br.compress(Buffer.from('foo', 'utf8'), opts, onCompress); + +createReadStream(__filename) + .pipe(br.compressStream()) + .pipe(createWriteStream('foo.ts')); + +createReadStream(__dirname) + .pipe(br.compressStream(opts)) + .pipe(createWriteStream('bar.ts')); + +createReadStream('bar.ts') + .pipe(br.decompressStream()) + .pipe(createWriteStream('qux.ts')); + +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'))); +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'), opts)); diff --git a/types/iltorb/index.d.ts b/types/iltorb/index.d.ts new file mode 100644 index 0000000000..bd6cd88fb7 --- /dev/null +++ b/types/iltorb/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for iltorb 2.0 +// Project: https://github.com/MayhemYDG/iltorb +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +export interface BrotliEncodeParams { + disable_literal_context_modeling?: boolean; + lgblock?: number; + lgwin?: number; + mode?: number; + quality?: number; + size_hint?: number; +} + +export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => void; + +export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void; +export function compress(buffer: Buffer, callback: IltorbCallback): void; + +export function decompress(buffer: Buffer, callback: IltorbCallback): void; + +export function compressSync(buffer: Buffer, options?: BrotliEncodeParams): Buffer; +export function decompressSync(buffer: Buffer): Buffer; + +export function compressStream(options?: BrotliEncodeParams): Transform; +export function decompressStream(): Transform; diff --git a/types/iltorb/tsconfig.json b/types/iltorb/tsconfig.json new file mode 100644 index 0000000000..c12ff988ba --- /dev/null +++ b/types/iltorb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iltorb-tests.ts" + ] +} diff --git a/types/iltorb/tslint.json b/types/iltorb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/iltorb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index 1af500c7cf..e74d1a4ce9 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/inert/ // Definitions by: Steve Ognibene , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as hapi from 'hapi'; diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 8353b4e563..ec1dbe3512 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ioredis +// Type definitions for ioredis 3.2 // Project: https://github.com/luin/ioredis -// Definitions by: York Yao +// Definitions by: York Yao // Christopher Eck // Yoga Aliarham +// Ebrahim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== @@ -13,635 +14,738 @@ /// interface RedisStatic { - new (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - new (options: IORedis.RedisOptions): IORedis.Redis; - new (url: string): IORedis.Redis; + new(port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(host?: string, options?: IORedis.RedisOptions): IORedis.Redis; + new(options?: IORedis.RedisOptions): IORedis.Redis; (port?: number, host?: string, options?: IORedis.RedisOptions): IORedis.Redis; (host?: string, options?: IORedis.RedisOptions): IORedis.Redis; - (options: IORedis.RedisOptions): IORedis.Redis; - (url: string): IORedis.Redis; + (options?: IORedis.RedisOptions): IORedis.Redis; Cluster: IORedis.Cluster; + Command: IORedis.Command; } declare var IORedis: RedisStatic; export = IORedis; -declare module IORedis { - interface Commander { - new (): Commander; - getBuiltinCommands(): string[]; - createBuiltinCommand(commandName: string): {}; - defineCommand(name: string, definition: { - numberOfKeys?: number; - lua?: string; - }): any; - sendCommand(): void; +declare class Commander { + getBuiltinCommands(): string[]; + createBuiltinCommand(commandName: string): {}; + defineCommand(name: string, definition: { + numberOfKeys?: number; + lua?: string; + }): any; + sendCommand(): void; +} + +declare namespace IORedis { + interface Command { + setArgumentTransformer(name: string, fn: (args: any[]) => any[]): void; + setReplyTransformer(name: string, fn: (result: any) => any): void; } interface Redis extends NodeJS.EventEmitter, Commander { status: string; - connect(callback?: Function): Promise; + connect(callback?: () => void): Promise; disconnect(): void; duplicate(): Redis; - monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise; send_command(command: string, ...args: any[]): any; - auth(password: string, callback?: ResCallbackT): any; - ping(callback?: ResCallbackT): any; - append(key: string, value: string, callback?: ResCallbackT): any; - bitcount(key: string, callback?: ResCallbackT): any; - bitcount(key: string, start: number, end: number, callback?: ResCallbackT): any; - set(key: string, value: string, callback?: ResCallbackT): any; - get(key: string, callback?: ResCallbackT): any; - exists(key: string, value: string, callback?: ResCallbackT): any; - publish(channel: string, value: any): any; - subscribe(channel: string): any; - get(args: any[], callback?: ResCallbackT): any; - get(...args: any[]): any; - getBuffer(key: string, callback?: ResCallbackT): any; - set(args: any[], callback?: ResCallbackT): any; - set(...args: any[]): any; - setnx(args: any[], callback?: ResCallbackT): any; - setnx(...args: any[]): any; - setex(args: any[], callback?: ResCallbackT): any; - setex(...args: any[]): any; - psetex(args: any[], callback?: ResCallbackT): any; - psetex(...args: any[]): any; - append(args: any[], callback?: ResCallbackT): any; - append(...args: any[]): any; - strlen(args: any[], callback?: ResCallbackT): any; - strlen(...args: any[]): any; - del(args: any[], callback?: ResCallbackT): any; - del(...args: any[]): any; - exists(args: any[], callback?: ResCallbackT): any; - exists(...args: any[]): any; - setbit(args: any[], callback?: ResCallbackT): any; - setbit(...args: any[]): any; - getbit(args: any[], callback?: ResCallbackT): any; - getbit(...args: any[]): any; - setrange(args: any[], callback?: ResCallbackT): any; - setrange(...args: any[]): any; - getrange(args: any[], callback?: ResCallbackT): any; - getrange(...args: any[]): any; - substr(args: any[], callback?: ResCallbackT): any; - substr(...args: any[]): any; - incr(args: any[], callback?: ResCallbackT): any; - incr(...args: any[]): any; - decr(args: any[], callback?: ResCallbackT): any; - decr(...args: any[]): any; - mget(args: any[], callback?: ResCallbackT): any; - mget(...args: any[]): any; - rpush(...args: any[]): any; - lpush(args: any[], callback?: ResCallbackT): any; - lpush(...args: any[]): any; - rpushx(args: any[], callback?: ResCallbackT): any; - rpushx(...args: any[]): any; - lpushx(args: any[], callback?: ResCallbackT): any; - lpushx(...args: any[]): any; - linsert(args: any[], callback?: ResCallbackT): any; - linsert(...args: any[]): any; - rpop(args: any[], callback?: ResCallbackT): any; - rpop(...args: any[]): any; - lpop(args: any[], callback?: ResCallbackT): any; - lpop(...args: any[]): any; - brpop(args: any[], callback?: ResCallbackT): any; - brpop(...args: any[]): any; - brpoplpush(args: any[], callback?: ResCallbackT): any; - brpoplpush(...args: any[]): any; - blpop(args: any[], callback?: ResCallbackT): any; - blpop(...args: any[]): any; - llen(args: any[], callback?: ResCallbackT): any; - llen(...args: any[]): any; - lindex(args: any[], callback?: ResCallbackT): any; - lindex(...args: any[]): any; - lset(args: any[], callback?: ResCallbackT): any; - lset(...args: any[]): any; - lrange(args: any[], callback?: ResCallbackT): any; - lrange(...args: any[]): any; - ltrim(args: any[], callback?: ResCallbackT): any; - ltrim(...args: any[]): any; - lrem(args: any[], callback?: ResCallbackT): any; - lrem(...args: any[]): any; - rpoplpush(args: any[], callback?: ResCallbackT): any; - rpoplpush(...args: any[]): any; - sadd(args: any[], callback?: ResCallbackT): any; - sadd(...args: any[]): any; - srem(args: any[], callback?: ResCallbackT): any; - srem(...args: any[]): any; - smove(args: any[], callback?: ResCallbackT): any; - smove(...args: any[]): any; - sismember(args: any[], callback?: ResCallbackT): any; - sismember(...args: any[]): any; - scard(args: any[], callback?: ResCallbackT): any; - scard(...args: any[]): any; - spop(args: any[], callback?: ResCallbackT): any; - spop(...args: any[]): any; - srandmember(args: any[], callback?: ResCallbackT): any; - srandmember(...args: any[]): any; - sinter(args: any[], callback?: ResCallbackT): any; - sinter(...args: any[]): any; - sinterstore(args: any[], callback?: ResCallbackT): any; - sinterstore(...args: any[]): any; - sunion(args: any[], callback?: ResCallbackT): any; - sunion(...args: any[]): any; - sunionstore(args: any[], callback?: ResCallbackT): any; - sunionstore(...args: any[]): any; - sdiff(args: any[], callback?: ResCallbackT): any; - sdiff(...args: any[]): any; - sdiffstore(args: any[], callback?: ResCallbackT): any; - sdiffstore(...args: any[]): any; - smembers(args: any[], callback?: ResCallbackT): any; - smembers(...args: any[]): any; - zadd(args: any[], callback?: ResCallbackT): any; - zadd(...args: any[]): any; - zincrby(args: any[], callback?: ResCallbackT): any; - zincrby(...args: any[]): any; - zrem(args: any[], callback?: ResCallbackT): any; - zrem(...args: any[]): any; - zremrangebyscore(args: any[], callback?: ResCallbackT): any; - zremrangebyscore(...args: any[]): any; - zremrangebyrank(args: any[], callback?: ResCallbackT): any; - zremrangebyrank(...args: any[]): any; - zunionstore(args: any[], callback?: ResCallbackT): any; - zunionstore(...args: any[]): any; - zinterstore(args: any[], callback?: ResCallbackT): any; - zinterstore(...args: any[]): any; - zrange(args: any[], callback?: ResCallbackT): any; - zrange(...args: any[]): any; - zrangebyscore(args: any[], callback?: ResCallbackT): any; - zrangebyscore(...args: any[]): any; - zrevrangebyscore(args: any[], callback?: ResCallbackT): any; - zrevrangebyscore(...args: any[]): any; - zcount(args: any[], callback?: ResCallbackT): any; - zcount(...args: any[]): any; - zrevrange(args: any[], callback?: ResCallbackT): any; - zrevrange(...args: any[]): any; - zcard(args: any[], callback?: ResCallbackT): any; - zcard(...args: any[]): any; - zscore(args: any[], callback?: ResCallbackT): any; - zscore(...args: any[]): any; - zrank(args: any[], callback?: ResCallbackT): any; - zrank(...args: any[]): any; - zrevrank(args: any[], callback?: ResCallbackT): any; - zrevrank(...args: any[]): any; - hset(args: any[], callback?: ResCallbackT): any; - hset(...args: any[]): any; - hsetnx(args: any[], callback?: ResCallbackT): any; - hsetnx(...args: any[]): any; - hget(args: any[], callback?: ResCallbackT): any; - hget(...args: any[]): any; - hmset(args: any[], callback?: ResCallbackT): any; - hmset(key: string, hash: any, callback?: ResCallbackT): any; - hmset(...args: any[]): any; - hmget(args: any[], callback?: ResCallbackT): any; - hmget(...args: any[]): any; - hincrby(args: any[], callback?: ResCallbackT): any; - hincrby(...args: any[]): any; - hincrbyfloat(args: any[], callback?: ResCallbackT): any; - hincrbyfloat(...args: any[]): any; - hdel(args: any[], callback?: ResCallbackT): any; - hdel(...args: any[]): any; - hlen(args: any[], callback?: ResCallbackT): any; - hlen(...args: any[]): any; - hkeys(args: any[], callback?: ResCallbackT): any; - hkeys(...args: any[]): any; - hvals(args: any[], callback?: ResCallbackT): any; - hvals(...args: any[]): any; - hgetall(args: any[], callback?: ResCallbackT): any; - hgetall(...args: any[]): any; - hgetall(key: string, callback?: ResCallbackT): any; - hexists(args: any[], callback?: ResCallbackT): any; - hexists(...args: any[]): any; - incrby(args: any[], callback?: ResCallbackT): any; - incrby(...args: any[]): any; - incrbyfloat(args: any[], callback?: ResCallbackT): any; - incrbyfloat(...args: any[]): any; - decrby(args: any[], callback?: ResCallbackT): any; - decrby(...args: any[]): any; - getset(args: any[], callback?: ResCallbackT): any; - getset(...args: any[]): any; - mset(args: any[], callback?: ResCallbackT): any; - mset(...args: any[]): any; - msetnx(args: any[], callback?: ResCallbackT): any; - msetnx(...args: any[]): any; - randomkey(args: any[], callback?: ResCallbackT): any; - randomkey(...args: any[]): any; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): void; - move(args: any[], callback?: ResCallbackT): any; - move(...args: any[]): any; - rename(args: any[], callback?: ResCallbackT): any; - rename(...args: any[]): any; - renamenx(args: any[], callback?: ResCallbackT): any; - renamenx(...args: any[]): any; - expire(args: any[], callback?: ResCallbackT): any; - expire(...args: any[]): any; - pexpire(args: any[], callback?: ResCallbackT): any; - pexpire(...args: any[]): any; - expireat(args: any[], callback?: ResCallbackT): any; - expireat(...args: any[]): any; - pexpireat(args: any[], callback?: ResCallbackT): any; - pexpireat(...args: any[]): any; - keys(args: any[], callback?: ResCallbackT): any; - keys(...args: any[]): any; - dbsize(args: any[], callback?: ResCallbackT): any; - dbsize(...args: any[]): any; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): any; - ping(...args: any[]): any; - echo(args: any[], callback?: ResCallbackT): any; - echo(...args: any[]): any; - save(args: any[], callback?: ResCallbackT): any; - save(...args: any[]): any; - bgsave(args: any[], callback?: ResCallbackT): any; - bgsave(...args: any[]): any; - bgrewriteaof(args: any[], callback?: ResCallbackT): any; - bgrewriteaof(...args: any[]): any; - shutdown(args: any[], callback?: ResCallbackT): any; - shutdown(...args: any[]): any; - lastsave(args: any[], callback?: ResCallbackT): any; - lastsave(...args: any[]): any; - type(args: any[], callback?: ResCallbackT): any; - type(...args: any[]): any; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): any; - exec(...args: any[]): any; - discard(args: any[], callback?: ResCallbackT): any; - discard(...args: any[]): any; - sync(args: any[], callback?: ResCallbackT): any; - sync(...args: any[]): any; - flushdb(args: any[], callback?: ResCallbackT): any; - flushdb(...args: any[]): any; - flushall(args: any[], callback?: ResCallbackT): any; - flushall(...args: any[]): any; - sort(args: any[], callback?: ResCallbackT): any; - sort(...args: any[]): any; - info(args: any[], callback?: ResCallbackT): any; - info(...args: any[]): any; - time(args: any[], callback?: ResCallbackT): any; - time(...args: any[]): any; - monitor(args: any[], callback?: ResCallbackT): any; - monitor(...args: any[]): any; - ttl(args: any[], callback?: ResCallbackT): any; - ttl(...args: any[]): any; - persist(args: any[], callback?: ResCallbackT): any; - persist(...args: any[]): any; - slaveof(args: any[], callback?: ResCallbackT): any; - slaveof(...args: any[]): any; - debug(args: any[], callback?: ResCallbackT): any; + + bitcount(key: string, callback: (err: Error, res: number) => void): void; + bitcount(key: string, start: number, end: number, callback: (err: Error, res: number) => void): void; + bitcount(key: string): Promise; + bitcount(key: string, start: number, end: number): Promise; + + get(key: string, callback: (err: Error, res: string) => void): void; + get(key: string): Promise; + getBuffer(key: string, callback: (err: Error, res: Buffer) => void): void; + getBuffer(key: string): Promise; + + set(key: string, value: any, ...args: any[]): any; + + setnx(key: string, value: any, callback: (err: Error, res: any) => void): void; + setnx(key: string, value: any): Promise; + + setex(key: string, seconds: number, value: any, callback: (err: Error, res: any) => void): void; + setex(key: string, seconds: number, value: any): Promise; + + psetex(key: string, milliseconds: number, value: any, callback: (err: Error, res: any) => void): void; + psetex(key: string, milliseconds: number, value: any): Promise; + + append(key: string, value: any, callback: (err: Error, res: number) => void): void; + append(key: string, value: any): Promise; + + strlen(key: string, callback: (err: Error, res: number) => void): void; + strlen(key: string): Promise; + + del(key: string, ...keys: string[]): any; + + exists(key: string, ...keys: string[]): any; + + setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setbit(key: string, offset: number, value: any): Promise; + + getbit(key: string, offset: number, callback: (err: Error, res: number) => void): void; + getbit(key: string, offset: number): Promise; + + setrange(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; + setrange(key: string, offset: number, value: any): Promise; + + getrange(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + getrange(key: string, start: number, end: number): Promise; + + substr(key: string, start: number, end: number, callback: (err: Error, res: string) => void): void; + substr(key: string, start: number, end: number): Promise; + + incr(key: string, callback: (err: Error, res: number) => void): void; + incr(key: string): Promise; + + decr(key: string, callback: (err: Error, res: number) => void): void; + decr(key: string): Promise; + + mget(key: string, ...keys: string[]): any; + + rpush(key: string, value: any, ...values: string[]): any; + + lpush(key: string, value: any, ...values: string[]): any; + + rpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + rpushx(key: string, value: any): Promise; + + lpushx(key: string, value: any, callback: (err: Error, res: number) => void): void; + lpushx(key: string, value: any): Promise; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback: (err: Error, res: number) => void): void; + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any): Promise; + + rpop(key: string, callback: (err: Error, res: string) => void): void; + rpop(key: string): Promise; + + lpop(key: string, callback: (err: Error, res: string) => void): void; + lpop(key: string): Promise; + + brpop(key: string, ...keys: string[]): any; + + blpop(key: string, ...keys: string[]): any; + + brpoplpush(source: string, destination: string, timeout: number, callback: (err: Error, res: any) => void): void; + brpoplpush(source: string, destination: string, timeout: number): Promise; + + llen(key: string, callback: (err: Error, res: number) => void): void; + llen(key: string): Promise; + + lindex(key: string, index: number, callback: (err: Error, res: string) => void): void; + lindex(key: string, index: number): Promise; + + lset(key: string, index: number, value: any, callback: (err: Error, res: any) => void): void; + lset(key: string, index: number, value: any): Promise; + + lrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + lrange(key: string, start: number, stop: number): Promise; + + ltrim(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + ltrim(key: string, start: number, stop: number): Promise; + + lrem(key: string, count: number, value: any, callback: (err: Error, res: number) => void): void; + lrem(key: string, count: number, value: any): Promise; + + rpoplpush(source: string, destination: string, callback: (err: Error, res: string) => void): void; + rpoplpush(source: string, destination: string): Promise; + + sadd(key: string, ...members: any[]): any; + + srem(key: string, ...members: any[]): any; + + smove(source: string, destination: string, member: string, callback: (err: Error, res: string) => void): void; + smove(source: string, destination: string, member: string): Promise; + + sismember(key: string, member: string, callback: (err: Error, res: 1 | 0) => void): void; + sismember(key: string, member: string): Promise<1 | 0>; + + scard(key: string, callback: (err: Error, res: number) => void): void; + scard(key: string): Promise; + + spop(key: string, callback: (err: Error, res: any) => void): void; + spop(key: string, count: number, callback: (err: Error, res: any) => void): void; + spop(key: string, count?: number): Promise; + + srandmember(key: string, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count: number, callback: (err: Error, res: any) => void): void; + srandmember(key: string, count?: number): Promise; + + sinter(key: string, ...keys: string[]): any; + + sinterstore(destination: string, key: string, ...keys: string[]): any; + + sunion(key: string, ...keys: string[]): any; + + sunionstore(destination: string, key: string, ...keys: string[]): any; + + sdiff(key: string, ...keys: string[]): any; + + sdiffstore(destination: string, key: string, ...keys: string[]): any; + + smembers(key: string, callback: (err: Error, res: any) => void): void; + smembers(key: string): Promise; + + zadd(key: string, ...args: string[]): any; + + zincrby(key: string, increment: number, member: string, callback: (err: Error, res: any) => void): void; + zincrby(key: string, increment: number, member: string): Promise; + + zrem(key: string, member: string, ...members: any[]): any; + + zremrangebyscore(key: string, min: number, max: number, callback: (err: Error, res: any) => void): void; + zremrangebyscore(key: string, min: number, max: number): Promise; + + zremrangebyrank(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zremrangebyrank(key: string, start: number, stop: number): Promise; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): any; + + zrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrevrange(key: string, start: number, stop: number, callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback: (err: Error, res: any) => void): void; + zrevrange(key: string, start: number, stop: number, withScores?: "WITHSCORES"): Promise; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): any; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): any; + + zcount(key: string, min: number, max: number, callback: (err: Error, res: number) => void): void; + zcount(key: string, min: number, max: number): Promise; + + zcard(key: string, callback: (err: Error, res: number) => void): void; + zcard(key: string): Promise; + + zscore(key: string, member: string, callback: (err: Error, res: number) => void): void; + zscore(key: string, member: string): Promise; + + zrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrank(key: string, member: string): Promise; + + zrevrank(key: string, member: string, callback: (err: Error, res: number) => void): void; + zrevrank(key: string, member: string): Promise; + + hset(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hset(key: string, field: string, value: any): Promise<0 | 1>; + + hsetnx(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetnx(key: string, field: string, value: any): Promise<0 | 1>; + + hget(key: string, field: string, callback: (err: Error, res: string) => void): void; + hget(key: string, field: string): Promise; + + hmset(key: string, field: string, value: any, ...args: string[]): any; + + hmget(key: string, field: string, ...fields: string[]): any; + + hincrby(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrby(key: string, field: string, increment: number): Promise; + + hincrbyfloat(key: string, field: string, increment: number, callback: (err: Error, res: number) => void): void; + hincrbyfloat(key: string, field: string, increment: number): Promise; + + hdel(key: string, field: string, ...fields: string[]): any; + + hlen(key: string, callback: (err: Error, res: number) => void): void; + hlen(key: string): Promise; + + hkeys(key: string, callback: (err: Error, res: any) => void): void; + hkeys(key: string): Promise; + + hvals(key: string, callback: (err: Error, res: any) => void): void; + hvals(key: string): Promise; + + hgetall(key: string, callback: (err: Error, res: any) => void): void; + hgetall(key: string): Promise; + + hexists(key: string, field: string, callback: (err: Error, res: 0 | 1) => void): void; + hexists(key: string, field: string): Promise<0 | 1>; + + incrby(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrby(key: string, increment: number): Promise; + + incrbyfloat(key: string, increment: number, callback: (err: Error, res: number) => void): void; + incrbyfloat(key: string, increment: number): Promise; + + decrby(key: string, decrement: number, callback: (err: Error, res: number) => void): void; + decrby(key: string, decrement: number): Promise; + + getset(key: string, value: any, callback: (err: Error, res: string) => void): void; + getset(key: string, value: any): Promise; + + mset(key: string, value: any, ...args: string[]): any; + + msetnx(key: string, value: any, ...args: string[]): any; + + randomkey(callback: (err: Error, res: string) => void): void; + randomkey(): Promise; + + select(index: number, callback: (err: Error, res: string) => void): void; + select(index: number): Promise; + + move(key: string, db: string, callback: (err: Error, res: 0 | 1) => void): void; + move(key: string, db: string): Promise<0 | 1>; + + rename(key: string, newkey: string, callback: (err: Error, res: string) => void): void; + rename(key: string, newkey: string): Promise; + + renamenx(key: string, newkey: string, callback: (err: Error, res: 0 | 1) => void): void; + renamenx(key: string, newkey: string): Promise<0 | 1>; + + expire(key: string, seconds: number, callback: (err: Error, res: 0 | 1) => void): void; + expire(key: string, seconds: number): Promise<0 | 1>; + + pexpire(key: string, milliseconds: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpire(key: string, milliseconds: number): Promise<0 | 1>; + + expireat(key: string, timestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + expireat(key: string, timestamp: number): Promise<0 | 1>; + + pexpireat(key: string, millisecondsTimestamp: number, callback: (err: Error, res: 0 | 1) => void): void; + pexpireat(key: string, millisecondsTimestamp: number): Promise<0 | 1>; + + keys(pattern: string, callback: (err: Error, res: string[]) => void): void; + keys(pattern: string): Promise; + + dbsize(callback: (err: Error, res: number) => void): void; + dbsize(): Promise; + + auth(password: string, callback: (err: Error, res: string) => void): void; + auth(password: string): Promise; + + ping(callback: (err: Error, res: string) => void): void; + ping(message: string, callback: (err: Error, res: string) => void): void; + ping(message?: string): Promise; + + echo(message: string, callback: (err: Error, res: string) => void): void; + echo(message: string): Promise; + + save(callback: (err: Error, res: string) => void): void; + save(): Promise; + + bgsave(callback: (err: Error, res: string) => void): void; + bgsave(): Promise; + + bgrewriteaof(callback: (err: Error, res: string) => void): void; + bgrewriteaof(): Promise; + + shutdown(save: "SAVE" | "NOSAVE", callback: (err: Error, res: any) => void): void; + shutdown(save: "SAVE" | "NOSAVE"): Promise; + + lastsave(callback: (err: Error, res: number) => void): void; + lastsave(): Promise; + + type(key: string, callback: (err: Error, res: string) => void): void; + type(key: string): Promise; + + multi(commands?: string[][], options?: MultiOptions): Pipeline; + multi(options: { pipeline: false }): Promise; + + exec(callback: (err: Error, res: any) => void): void; + exec(): Promise; + + discard(callback: (err: Error, res: any) => void): void; + discard(): Promise; + + sync(callback: (err: Error, res: any) => void): void; + sync(): Promise; + + flushdb(callback: (err: Error, res: string) => void): void; + flushdb(): Promise; + + flushall(callback: (err: Error, res: string) => void): void; + flushall(): Promise; + + sort(key: string, ...args: string[]): any; + + info(callback: (err: Error, res: any) => void): void; + info(section: string, callback: (err: Error, res: any) => void): void; + info(section?: string): Promise; + + time(callback: (err: Error, res: any) => void): void; + time(): Promise; + + monitor(callback: (err: Error, res: NodeJS.EventEmitter) => void): void; + monitor(): Promise; + + ttl(key: string, callback: (err: Error, res: number) => void): void; + ttl(key: string): Promise; + + persist(key: string, callback: (err: Error, res: 0 | 1) => void): void; + persist(key: string): Promise<0 | 1>; + + slaveof(host: string, port: number, callback: (err: Error, res: string) => void): void; + slaveof(host: string, port: number): Promise; + debug(...args: any[]): any; - config(args: any[], callback?: ResCallbackT): any; + config(...args: any[]): any; - subscribe(args: any[], callback?: ResCallbackT): any; - subscribe(...args: any[]): any; - unsubscribe(args: any[], callback?: ResCallbackT): any; - unsubscribe(...args: any[]): any; - psubscribe(args: any[], callback?: ResCallbackT): any; - psubscribe(...args: any[]): any; - punsubscribe(args: any[], callback?: ResCallbackT): any; - punsubscribe(...args: any[]): any; - publish(args: any[], callback?: ResCallbackT): any; - publish(...args: any[]): any; - watch(args: any[], callback?: ResCallbackT): any; - watch(...args: any[]): any; - unwatch(args: any[], callback?: ResCallbackT): any; - unwatch(...args: any[]): any; - cluster(args: any[], callback?: ResCallbackT): any; + + subscribe(channel: string, ...channels: any[]): any; + + unsubscribe(...channels: string[]): any; + + psubscribe(pattern: string, ...patterns: string[]): any; + + punsubscribe(...patterns: string[]): any; + + publish(channel: string, message: string, callback: (err: Error, res: number) => void): void; + publish(channel: string, message: string): Promise; + + watch(key: string, ...keys: string[]): any; + + unwatch(callback: (err: Error, res: string) => void): void; + unwatch(): Promise; + cluster(...args: any[]): any; - restore(args: any[], callback?: ResCallbackT): any; + restore(...args: any[]): any; - migrate(args: any[], callback?: ResCallbackT): any; + migrate(...args: any[]): any; - dump(args: any[], callback?: ResCallbackT): any; - dump(...args: any[]): any; - object(args: any[], callback?: ResCallbackT): any; - object(...args: any[]): any; - client(args: any[], callback?: ResCallbackT): any; + + dump(key: string, callback: (err: Error, res: string) => void): void; + dump(key: string): Promise; + + object(subcommand: string, ...args: any[]): any; + client(...args: any[]): any; - eval(args: any[], callback?: ResCallbackT): any; + eval(...args: any[]): any; - evalsha(args: any[], callback?: ResCallbackT): any; + evalsha(...args: any[]): any; - script(args: any[], callback?: ResCallbackT): any; - script(key: string, callback?: ResCallbackT): any; + script(...args: any[]): any; - quit(args: any[], callback?: ResCallbackT): any; - quit(...args: any[]): any; - scan(args: any[], callback?: ResCallbackT): any; - scan(...args: any[]): any; - hscan(args: any[], callback?: ResCallbackT): any; - hscan(...args: any[]): any; - zscan(args: any[], callback?: ResCallbackT): any; - zscan(...args: any[]): any; - pfmerge(args: any[], callback?: ResCallbackT): any; - pfmerge(...args: any[]): any; - pfadd(args: any[], callback?: ResCallbackT): any; - pfadd(...args: any[]): any; - pfcount(args: any[], callback?: ResCallbackT): any; - pfcount(...args: any[]): any; - pipeline(): Pipeline; - pipeline(commands: string[][]): Pipeline; + quit(callback: (err: Error, res: string) => void): void; + quit(): Promise; - scanStream(options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - hscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; - zscanStream(key: string, options?: IORedis.ScanStreamOption): NodeJS.EventEmitter; + scan(cursor: number, ...args: any[]): any; + + hscan(key: string, cursor: number, ...args: any[]): any; + + zscan(key: string, cursor: number, ...args: any[]): any; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): any; + + pfadd(key: string, element: string, ...elements: string[]): any; + + pfcount(key: string, ...keys: string[]): any; + + pipeline(commands?: string[][]): Pipeline; + + scanStream(options?: ScanStreamOption): NodeJS.EventEmitter; + hscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; + zscanStream(key: string, options?: ScanStreamOption): NodeJS.EventEmitter; } interface Pipeline { - exec(callback?: ResCallbackT): any; + bitcount(key: string, callback?: (err: Error, res: number) => void): Pipeline; + bitcount(key: string, start: number, end: number, callback?: (err: Error, res: number) => void): Pipeline; + + get(key: string, callback?: (err: Error, res: string) => void): Pipeline; + getBuffer(key: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + + set(key: string, value: any, ...args: any[]): Pipeline; + + setnx(key: string, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + setex(key: string, seconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + psetex(key: string, milliseconds: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + append(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + strlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + del(key: string, ...keys: string[]): Pipeline; + + exists(key: string, ...keys: string[]): Pipeline; + + setbit(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getbit(key: string, offset: number, callback?: (err: Error, res: number) => void): Pipeline; + + setrange(key: string, offset: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + getrange(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + substr(key: string, start: number, end: number, callback?: (err: Error, res: string) => void): Pipeline; + + incr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + decr(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + mget(key: string, ...keys: string[]): Pipeline; + + rpush(key: string, value: any, ...values: string[]): Pipeline; + + lpush(key: string, value: any, ...values: string[]): Pipeline; + + rpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + lpushx(key: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + linsert(key: string, direction: "BEFORE" | "AFTER", pivot: string, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + lpop(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + brpop(key: string, ...keys: string[]): Pipeline; + + blpop(key: string, ...keys: string[]): Pipeline; + + brpoplpush(source: string, destination: string, timeout: number, callback?: (err: Error, res: any) => void): Pipeline; + + llen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + lindex(key: string, index: number, callback?: (err: Error, res: string) => void): Pipeline; + + lset(key: string, index: number, value: any, callback?: (err: Error, res: any) => void): Pipeline; + + lrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + ltrim(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + lrem(key: string, count: number, value: any, callback?: (err: Error, res: number) => void): Pipeline; + + rpoplpush(source: string, destination: string, callback?: (err: Error, res: string) => void): Pipeline; + + sadd(key: string, ...members: any[]): Pipeline; + + srem(key: string, ...members: any[]): Pipeline; + + smove(source: string, destination: string, member: string, callback?: (err: Error, res: string) => void): Pipeline; + + sismember(key: string, member: string, callback?: (err: Error, res: 1 | 0) => void): Pipeline; + + scard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + spop(key: string, callback?: (err: Error, res: any) => void): Pipeline; + spop(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + srandmember(key: string, callback?: (err: Error, res: any) => void): Pipeline; + srandmember(key: string, count: number, callback?: (err: Error, res: any) => void): Pipeline; + + sinter(key: string, ...keys: string[]): Pipeline; + + sinterstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sunion(key: string, ...keys: string[]): Pipeline; + + sunionstore(destination: string, key: string, ...keys: string[]): Pipeline; + + sdiff(key: string, ...keys: string[]): Pipeline; + + sdiffstore(destination: string, key: string, ...keys: string[]): Pipeline; + + smembers(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + zadd(key: string, ...args: string[]): Pipeline; + + zincrby(key: string, increment: number, member: string, callback?: (err: Error, res: any) => void): Pipeline; + + zrem(key: string, member: string, ...members: any[]): Pipeline; + + zremrangebyscore(key: string, min: number, max: number, callback?: (err: Error, res: any) => void): Pipeline; + + zremrangebyrank(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + + zunionstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zinterstore(destination: string, numkeys: number, key: string, ...args: string[]): Pipeline; + + zrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrevrange(key: string, start: number, stop: number, callback?: (err: Error, res: any) => void): Pipeline; + zrevrange(key: string, start: number, stop: number, withScores: "WITHSCORES", callback?: (err: Error, res: any) => void): Pipeline; + + zrangebyscore(key: string, min: number, max: number, ...args: string[]): Pipeline; + + zrevrangebyscore(key: string, max: number, min: number, ...args: string[]): Pipeline; + + zcount(key: string, min: number, max: number, callback?: (err: Error, res: number) => void): Pipeline; + + zcard(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + zscore(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + zrevrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; + + hset(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hsetnx(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + hget(key: string, field: string, callback?: (err: Error, res: string) => void): Pipeline; + + hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; + + hmget(key: string, field: string, ...fields: string[]): Pipeline; + + hincrby(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hincrbyfloat(key: string, field: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + hdel(key: string, field: string, ...fields: string[]): Pipeline; + + hlen(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + hkeys(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hvals(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hgetall(key: string, callback?: (err: Error, res: any) => void): Pipeline; + + hexists(key: string, field: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + incrby(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + incrbyfloat(key: string, increment: number, callback?: (err: Error, res: number) => void): Pipeline; + + decrby(key: string, decrement: number, callback?: (err: Error, res: number) => void): Pipeline; + + getset(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + + mset(key: string, value: any, ...args: string[]): Pipeline; + + msetnx(key: string, value: any, ...args: string[]): Pipeline; + + randomkey(callback?: (err: Error, res: string) => void): Pipeline; + + select(index: number, callback?: (err: Error, res: string) => void): Pipeline; + + move(key: string, db: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + rename(key: string, newkey: string, callback?: (err: Error, res: string) => void): Pipeline; + + renamenx(key: string, newkey: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expire(key: string, seconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpire(key: string, milliseconds: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + expireat(key: string, timestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + pexpireat(key: string, millisecondsTimestamp: number, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + keys(pattern: string, callback?: (err: Error, res: string[]) => void): Pipeline; + + dbsize(callback?: (err: Error, res: number) => void): Pipeline; + + auth(password: string, callback?: (err: Error, res: string) => void): Pipeline; + + ping(callback?: (err: Error, res: string) => void): Pipeline; + ping(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + echo(message: string, callback?: (err: Error, res: string) => void): Pipeline; + + save(callback?: (err: Error, res: string) => void): Pipeline; + + bgsave(callback?: (err: Error, res: string) => void): Pipeline; + + bgrewriteaof(callback?: (err: Error, res: string) => void): Pipeline; + + shutdown(save: "SAVE" | "NOSAVE", callback?: (err: Error, res: any) => void): Pipeline; + + lastsave(callback?: (err: Error, res: number) => void): Pipeline; + + type(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + multi(callback?: (err: Error, res: string) => void): Pipeline; + + exec(callback?: (err: Error, res: any) => void): Promise; + + discard(callback?: (err: Error, res: any) => void): Pipeline; + + sync(callback?: (err: Error, res: any) => void): Pipeline; + + flushdb(callback?: (err: Error, res: string) => void): Pipeline; + + flushall(callback?: (err: Error, res: string) => void): Pipeline; + + sort(key: string, ...args: string[]): Pipeline; + + info(callback?: (err: Error, res: any) => void): Pipeline; + info(section: string, callback?: (err: Error, res: any) => void): Pipeline; + + time(callback?: (err: Error, res: any) => void): Pipeline; + + monitor(callback?: (err: Error, res: NodeJS.EventEmitter) => void): Pipeline; + + ttl(key: string, callback?: (err: Error, res: number) => void): Pipeline; + + persist(key: string, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + + slaveof(host: string, port: number, callback?: (err: Error, res: string) => void): Pipeline; - get(args: any[], callback?: ResCallbackT): Pipeline; - get(...args: any[]): Pipeline; - set(args: any[], callback?: ResCallbackT): Pipeline; - set(...args: any[]): Pipeline; - setnx(args: any[], callback?: ResCallbackT): Pipeline; - setnx(...args: any[]): Pipeline; - setex(args: any[], callback?: ResCallbackT): Pipeline; - setex(...args: any[]): Pipeline; - psetex(args: any[], callback?: ResCallbackT): Pipeline; - psetex(...args: any[]): Pipeline; - append(args: any[], callback?: ResCallbackT): Pipeline; - append(...args: any[]): Pipeline; - strlen(args: any[], callback?: ResCallbackT): Pipeline; - strlen(...args: any[]): Pipeline; - del(args: any[], callback?: ResCallbackT): Pipeline; - del(...args: any[]): Pipeline; - exists(args: any[], callback?: ResCallbackT): Pipeline; - exists(...args: any[]): Pipeline; - setbit(args: any[], callback?: ResCallbackT): Pipeline; - setbit(...args: any[]): Pipeline; - getbit(args: any[], callback?: ResCallbackT): Pipeline; - getbit(...args: any[]): Pipeline; - setrange(args: any[], callback?: ResCallbackT): Pipeline; - setrange(...args: any[]): Pipeline; - getrange(args: any[], callback?: ResCallbackT): Pipeline; - getrange(...args: any[]): Pipeline; - substr(args: any[], callback?: ResCallbackT): Pipeline; - substr(...args: any[]): Pipeline; - incr(args: any[], callback?: ResCallbackT): Pipeline; - incr(...args: any[]): Pipeline; - decr(args: any[], callback?: ResCallbackT): Pipeline; - decr(...args: any[]): Pipeline; - mget(args: any[], callback?: ResCallbackT): Pipeline; - mget(...args: any[]): Pipeline; - rpush(...args: any[]): Pipeline; - lpush(args: any[], callback?: ResCallbackT): Pipeline; - lpush(...args: any[]): Pipeline; - rpushx(args: any[], callback?: ResCallbackT): Pipeline; - rpushx(...args: any[]): Pipeline; - lpushx(args: any[], callback?: ResCallbackT): Pipeline; - lpushx(...args: any[]): Pipeline; - linsert(args: any[], callback?: ResCallbackT): Pipeline; - linsert(...args: any[]): Pipeline; - rpop(args: any[], callback?: ResCallbackT): Pipeline; - rpop(...args: any[]): Pipeline; - lpop(args: any[], callback?: ResCallbackT): Pipeline; - lpop(...args: any[]): Pipeline; - brpop(args: any[], callback?: ResCallbackT): Pipeline; - brpop(...args: any[]): Pipeline; - brpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - brpoplpush(...args: any[]): Pipeline; - blpop(args: any[], callback?: ResCallbackT): Pipeline; - blpop(...args: any[]): Pipeline; - llen(args: any[], callback?: ResCallbackT): Pipeline; - llen(...args: any[]): Pipeline; - lindex(args: any[], callback?: ResCallbackT): Pipeline; - lindex(...args: any[]): Pipeline; - lset(args: any[], callback?: ResCallbackT): Pipeline; - lset(...args: any[]): Pipeline; - lrange(args: any[], callback?: ResCallbackT): Pipeline; - lrange(...args: any[]): Pipeline; - ltrim(args: any[], callback?: ResCallbackT): Pipeline; - ltrim(...args: any[]): Pipeline; - lrem(args: any[], callback?: ResCallbackT): Pipeline; - lrem(...args: any[]): Pipeline; - rpoplpush(args: any[], callback?: ResCallbackT): Pipeline; - rpoplpush(...args: any[]): Pipeline; - sadd(args: any[], callback?: ResCallbackT): Pipeline; - sadd(...args: any[]): Pipeline; - srem(args: any[], callback?: ResCallbackT): Pipeline; - srem(...args: any[]): Pipeline; - smove(args: any[], callback?: ResCallbackT): Pipeline; - smove(...args: any[]): Pipeline; - sismember(args: any[], callback?: ResCallbackT): Pipeline; - sismember(...args: any[]): Pipeline; - scard(args: any[], callback?: ResCallbackT): Pipeline; - scard(...args: any[]): Pipeline; - spop(args: any[], callback?: ResCallbackT): Pipeline; - spop(...args: any[]): Pipeline; - srandmember(args: any[], callback?: ResCallbackT): Pipeline; - srandmember(...args: any[]): Pipeline; - sinter(args: any[], callback?: ResCallbackT): Pipeline; - sinter(...args: any[]): Pipeline; - sinterstore(args: any[], callback?: ResCallbackT): Pipeline; - sinterstore(...args: any[]): Pipeline; - sunion(args: any[], callback?: ResCallbackT): Pipeline; - sunion(...args: any[]): Pipeline; - sunionstore(args: any[], callback?: ResCallbackT): Pipeline; - sunionstore(...args: any[]): Pipeline; - sdiff(args: any[], callback?: ResCallbackT): Pipeline; - sdiff(...args: any[]): Pipeline; - sdiffstore(args: any[], callback?: ResCallbackT): Pipeline; - sdiffstore(...args: any[]): Pipeline; - smembers(args: any[], callback?: ResCallbackT): Pipeline; - smembers(...args: any[]): Pipeline; - zadd(args: any[], callback?: ResCallbackT): Pipeline; - zadd(...args: any[]): Pipeline; - zincrby(args: any[], callback?: ResCallbackT): Pipeline; - zincrby(...args: any[]): Pipeline; - zrem(args: any[], callback?: ResCallbackT): Pipeline; - zrem(...args: any[]): Pipeline; - zremrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyscore(...args: any[]): Pipeline; - zremrangebyrank(args: any[], callback?: ResCallbackT): Pipeline; - zremrangebyrank(...args: any[]): Pipeline; - zunionstore(args: any[], callback?: ResCallbackT): Pipeline; - zunionstore(...args: any[]): Pipeline; - zinterstore(args: any[], callback?: ResCallbackT): Pipeline; - zinterstore(...args: any[]): Pipeline; - zrange(args: any[], callback?: ResCallbackT): Pipeline; - zrange(...args: any[]): Pipeline; - zrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrangebyscore(...args: any[]): Pipeline; - zrevrangebyscore(args: any[], callback?: ResCallbackT): Pipeline; - zrevrangebyscore(...args: any[]): Pipeline; - zcount(args: any[], callback?: ResCallbackT): Pipeline; - zcount(...args: any[]): Pipeline; - zrevrange(args: any[], callback?: ResCallbackT): Pipeline; - zrevrange(...args: any[]): Pipeline; - zcard(args: any[], callback?: ResCallbackT): Pipeline; - zcard(...args: any[]): Pipeline; - zscore(args: any[], callback?: ResCallbackT): Pipeline; - zscore(...args: any[]): Pipeline; - zrank(args: any[], callback?: ResCallbackT): Pipeline; - zrank(...args: any[]): Pipeline; - zrevrank(args: any[], callback?: ResCallbackT): Pipeline; - zrevrank(...args: any[]): Pipeline; - hset(args: any[], callback?: ResCallbackT): Pipeline; - hset(...args: any[]): Pipeline; - hsetnx(args: any[], callback?: ResCallbackT): Pipeline; - hsetnx(...args: any[]): Pipeline; - hget(args: any[], callback?: ResCallbackT): Pipeline; - hget(...args: any[]): Pipeline; - hmset(args: any[], callback?: ResCallbackT): Pipeline; - hmset(key: string, hash: any, callback?: ResCallbackT): Pipeline; - hmset(...args: any[]): Pipeline; - hmget(args: any[], callback?: ResCallbackT): Pipeline; - hmget(...args: any[]): Pipeline; - hincrby(args: any[], callback?: ResCallbackT): Pipeline; - hincrby(...args: any[]): Pipeline; - hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - hincrbyfloat(...args: any[]): Pipeline; - hdel(args: any[], callback?: ResCallbackT): Pipeline; - hdel(...args: any[]): Pipeline; - hlen(args: any[], callback?: ResCallbackT): Pipeline; - hlen(...args: any[]): Pipeline; - hkeys(args: any[], callback?: ResCallbackT): Pipeline; - hkeys(...args: any[]): Pipeline; - hvals(args: any[], callback?: ResCallbackT): Pipeline; - hvals(...args: any[]): Pipeline; - hgetall(args: any[], callback?: ResCallbackT): Pipeline; - hgetall(...args: any[]): Pipeline; - hgetall(key: string, callback?: ResCallbackT): Pipeline; - hexists(args: any[], callback?: ResCallbackT): Pipeline; - hexists(...args: any[]): Pipeline; - incrby(args: any[], callback?: ResCallbackT): Pipeline; - incrby(...args: any[]): Pipeline; - incrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; - incrbyfloat(...args: any[]): Pipeline; - decrby(args: any[], callback?: ResCallbackT): Pipeline; - decrby(...args: any[]): Pipeline; - getset(args: any[], callback?: ResCallbackT): Pipeline; - getset(...args: any[]): Pipeline; - mset(args: any[], callback?: ResCallbackT): Pipeline; - mset(...args: any[]): Pipeline; - msetnx(args: any[], callback?: ResCallbackT): Pipeline; - msetnx(...args: any[]): Pipeline; - randomkey(args: any[], callback?: ResCallbackT): Pipeline; - randomkey(...args: any[]): Pipeline; - select(args: any[], callback?: ResCallbackT): void; - select(...args: any[]): Pipeline; - move(args: any[], callback?: ResCallbackT): Pipeline; - move(...args: any[]): Pipeline; - rename(args: any[], callback?: ResCallbackT): Pipeline; - rename(...args: any[]): Pipeline; - renamenx(args: any[], callback?: ResCallbackT): Pipeline; - renamenx(...args: any[]): Pipeline; - expire(args: any[], callback?: ResCallbackT): Pipeline; - expire(...args: any[]): Pipeline; - pexpire(args: any[], callback?: ResCallbackT): Pipeline; - pexpire(...args: any[]): Pipeline; - expireat(args: any[], callback?: ResCallbackT): Pipeline; - expireat(...args: any[]): Pipeline; - pexpireat(args: any[], callback?: ResCallbackT): Pipeline; - pexpireat(...args: any[]): Pipeline; - keys(args: any[], callback?: ResCallbackT): Pipeline; - keys(...args: any[]): Pipeline; - dbsize(args: any[], callback?: ResCallbackT): Pipeline; - dbsize(...args: any[]): Pipeline; - auth(args: any[], callback?: ResCallbackT): void; - auth(...args: any[]): void; - ping(args: any[], callback?: ResCallbackT): Pipeline; - ping(...args: any[]): Pipeline; - echo(args: any[], callback?: ResCallbackT): Pipeline; - echo(...args: any[]): Pipeline; - save(args: any[], callback?: ResCallbackT): Pipeline; - save(...args: any[]): Pipeline; - bgsave(args: any[], callback?: ResCallbackT): Pipeline; - bgsave(...args: any[]): Pipeline; - bgrewriteaof(args: any[], callback?: ResCallbackT): Pipeline; - bgrewriteaof(...args: any[]): Pipeline; - shutdown(args: any[], callback?: ResCallbackT): Pipeline; - shutdown(...args: any[]): Pipeline; - lastsave(args: any[], callback?: ResCallbackT): Pipeline; - lastsave(...args: any[]): Pipeline; - type(args: any[], callback?: ResCallbackT): Pipeline; - type(...args: any[]): Pipeline; - multi(args: any[], callback?: ResCallbackT): Pipeline; - multi(...args: any[]): Pipeline; - exec(args: any[], callback?: ResCallbackT): Pipeline; - exec(...args: any[]): Pipeline; - discard(args: any[], callback?: ResCallbackT): Pipeline; - discard(...args: any[]): Pipeline; - sync(args: any[], callback?: ResCallbackT): Pipeline; - sync(...args: any[]): Pipeline; - flushdb(args: any[], callback?: ResCallbackT): Pipeline; - flushdb(...args: any[]): Pipeline; - flushall(args: any[], callback?: ResCallbackT): Pipeline; - flushall(...args: any[]): Pipeline; - sort(args: any[], callback?: ResCallbackT): Pipeline; - sort(...args: any[]): Pipeline; - info(args: any[], callback?: ResCallbackT): Pipeline; - info(...args: any[]): Pipeline; - time(args: any[], callback?: ResCallbackT): Pipeline; - time(...args: any[]): Pipeline; - monitor(args: any[], callback?: ResCallbackT): Pipeline; - monitor(...args: any[]): Pipeline; - ttl(args: any[], callback?: ResCallbackT): Pipeline; - ttl(...args: any[]): Pipeline; - persist(args: any[], callback?: ResCallbackT): Pipeline; - persist(...args: any[]): Pipeline; - slaveof(args: any[], callback?: ResCallbackT): Pipeline; - slaveof(...args: any[]): Pipeline; - debug(args: any[], callback?: ResCallbackT): Pipeline; debug(...args: any[]): Pipeline; - config(args: any[], callback?: ResCallbackT): Pipeline; + config(...args: any[]): Pipeline; - subscribe(args: any[], callback?: ResCallbackT): Pipeline; - subscribe(...args: any[]): Pipeline; - unsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - unsubscribe(...args: any[]): Pipeline; - psubscribe(args: any[], callback?: ResCallbackT): Pipeline; - psubscribe(...args: any[]): Pipeline; - punsubscribe(args: any[], callback?: ResCallbackT): Pipeline; - punsubscribe(...args: any[]): Pipeline; - publish(args: any[], callback?: ResCallbackT): Pipeline; - publish(...args: any[]): Pipeline; - watch(args: any[], callback?: ResCallbackT): Pipeline; - watch(...args: any[]): Pipeline; - unwatch(args: any[], callback?: ResCallbackT): Pipeline; - unwatch(...args: any[]): Pipeline; - cluster(args: any[], callback?: ResCallbackT): Pipeline; + + subscribe(channel: string, ...channels: any[]): Pipeline; + + unsubscribe(...channels: string[]): Pipeline; + + psubscribe(pattern: string, ...patterns: string[]): Pipeline; + + punsubscribe(...patterns: string[]): Pipeline; + + publish(channel: string, message: string, callback?: (err: Error, res: number) => void): Pipeline; + + watch(key: string, ...keys: string[]): Pipeline; + + unwatch(callback?: (err: Error, res: string) => void): Pipeline; + cluster(...args: any[]): Pipeline; - restore(args: any[], callback?: ResCallbackT): Pipeline; + restore(...args: any[]): Pipeline; - migrate(args: any[], callback?: ResCallbackT): Pipeline; + migrate(...args: any[]): Pipeline; - dump(args: any[], callback?: ResCallbackT): Pipeline; - dump(...args: any[]): Pipeline; - object(args: any[], callback?: ResCallbackT): Pipeline; - object(...args: any[]): Pipeline; - client(args: any[], callback?: ResCallbackT): Pipeline; + + dump(key: string, callback?: (err: Error, res: string) => void): Pipeline; + + object(subcommand: string, ...args: any[]): Pipeline; + client(...args: any[]): Pipeline; - eval(args: any[], callback?: ResCallbackT): Pipeline; + eval(...args: any[]): Pipeline; - evalsha(args: any[], callback?: ResCallbackT): Pipeline; + evalsha(...args: any[]): Pipeline; - quit(args: any[], callback?: ResCallbackT): Pipeline; - quit(...args: any[]): Pipeline; - scan(...args: any[]): Pipeline; - scan(args: any[], callback?: ResCallbackT): Pipeline; - hscan(...args: any[]): Pipeline; - hscan(args: any[], callback?: ResCallbackT): Pipeline; - zscan(...args: any[]): Pipeline; - zscan(args: any[], callback?: ResCallbackT): Pipeline; + + script(...args: any[]): Pipeline; + + quit(callback?: (err: Error, res: string) => void): Pipeline; + + scan(cursor: number, ...args: any[]): Pipeline; + + hscan(key: string, cursor: number, ...args: any[]): Pipeline; + + zscan(key: string, cursor: number, ...args: any[]): Pipeline; + + pfmerge(destkey: string, sourcekey: string, ...sourcekeys: string[]): Pipeline; + + pfadd(key: string, element: string, ...elements: string[]): Pipeline; + + pfcount(key: string, ...keys: string[]): Pipeline; } interface Cluster extends NodeJS.EventEmitter, Commander { - new (nodes: { host: string; port: number; }[], options?: IORedis.ClusterOptions): Redis; - connect(callback: Function): Promise; + new(nodes: Array<{ host: string; port: number; }>, options?: ClusterOptions): Redis; + connect(callback: () => void): Promise; disconnect(): void; nodes(role: string): Redis[]; } - interface ResCallbackT { - (err: Error, res: R): void; - } - interface RedisOptions { port?: number; host?: string; @@ -678,8 +782,8 @@ declare module IORedis { * When the return value isn't a number, ioredis will stop trying to reconnect. * Fixed in: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/15858 */ - retryStrategy?: (times: number) => number | false; - reconnectOnError?: (error: Error) => boolean; + retryStrategy?(times: number): number | false; + reconnectOnError?(error: Error): boolean; /** * By default, if there is no active connection to the Redis server, commands are added to a queue * and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means @@ -707,7 +811,7 @@ declare module IORedis { tls?: { ca: Buffer; }; - sentinels?: { host: string; port: number; }[]; + sentinels?: Array<{ host: string; port: number; }>; name?: string; /** * Enable READONLY mode for the connection. Only available for cluster mode. @@ -715,8 +819,9 @@ declare module IORedis { */ readOnly?: boolean; /** - * If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string: - */ + * If you are using the hiredis parser, it's highly recommended to enable this option. + * Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string + */ dropBufferSupport?: boolean; /** * Whether to show a friendly error stack. Will decrease the performance significantly. @@ -730,7 +835,7 @@ declare module IORedis { } interface ClusterOptions { - clusterRetryStrategy?: (times: number) => number; + clusterRetryStrategy?(times: number): number; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; @@ -740,4 +845,8 @@ declare module IORedis { retryDelayOnTryAgain?: number; redisOptions?: RedisOptions; } + + interface MultiOptions { + pipeline: boolean; + } } diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 373fba52c5..02b62def62 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -1,15 +1,13 @@ - - import * as Redis from "ioredis"; -var redis = new Redis(); +const redis = new Redis(); redis.set('foo', 'bar'); -redis.get('foo', function(err, result) { +redis.get('foo', (err, result) => { console.log(result); }); // Or using a promise if the last argument isn't a function -redis.get('foo').then(function(result: any) { +redis.get('foo').then((result: any) => { console.log(result); }); @@ -18,24 +16,24 @@ redis.sadd('set', 1, 3, 5, 7); redis.sadd('set', [1, 3, 5, 7]); // All arguments are passed directly to the redis server: -redis.set('key', 100, 'EX', 10); +redis.set('key', '100', 'EX', 10); -new Redis() // Connect to 127.0.0.1:6379 -new Redis(6380) // 127.0.0.1:6380 -new Redis(6379, '192.168.1.1') // 192.168.1.1:6379 -new Redis('/tmp/redis.sock') +new Redis(); // Connect to 127.0.0.1:6379 +new Redis(6380); // 127.0.0.1:6380 +new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379 +new Redis('/tmp/redis.sock'); new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: 'auth', db: 0, - retryStrategy: function() { return false; }, + retryStrategy() { return false; }, showFriendlyErrorStack: true -}) +}); -var pub = new Redis(); -redis.subscribe('news', 'music', function(err: any, count: any) { +const pub = new Redis(); +redis.subscribe('news', 'music', (err: any, count: any) => { // Now we are subscribed to both the 'news' and 'music' channels. // `count` represents the number of channels we are currently subscribed to. @@ -43,7 +41,7 @@ redis.subscribe('news', 'music', function(err: any, count: any) { pub.publish('music', 'Hello again!'); }); -redis.on('message', function(channel: any, message: any) { +redis.on('message', (channel: any, message: any) => { // Receive message Hello world! from channel news // Receive message Hello again! from channel music console.log('Receive message %s from channel %s', message, channel); @@ -51,6 +49,58 @@ redis.on('message', function(channel: any, message: any) { // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. -redis.on('messageBuffer', function(channel: any, message: any) { +redis.on('messageBuffer', (channel: any, message: any) => { // Both `channel` and `message` are buffers. }); + +const pipeline = redis.pipeline(); +pipeline.set('foo', 'bar'); +pipeline.del('cc'); +pipeline.exec((err, results) => { + // `err` is always null, and `results` is an array of responses + // corresponding to the sequence of queued commands. + // Each response follows the format `[err, result]`. +}); + +// You can even chain the commands: +redis.pipeline().set('foo', 'bar').del('cc').exec((err, results) => { +}); + +// `exec` also returns a Promise: +const promise = redis.pipeline().set('foo', 'bar').get('foo').exec(); +promise.then((result) => { + // result === [[null, 'OK'], [null, 'bar']] +}); + +redis.pipeline().set('foo', 'bar').get('foo', (err, result) => { + // result === 'bar' +}).exec((err, result) => { + // result[1][1] === 'bar' +}); + +redis.pipeline([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec(() => { /* ... */ }); + +Redis.Command.setArgumentTransformer('set', args => { + return args; +}); + +Redis.Command.setReplyTransformer('get', (result: any) => { + return result; +}); + +// multi +redis.multi().set('foo', 'bar').set('foo', 'baz').get('foo', (err, result) => { + // result === 'QUEUED' +}).exec((err, results) => { + // results = [[null, 'OK'], [null, 'OK'], [null, 'baz']] +}); + +redis.multi([ + ['set', 'foo', 'bar'], + ['get', 'foo'] +]).exec((err, results) => { + // results = [[null, 'OK'], [null, 'bar']] +}); diff --git a/types/ioredis/tslint.json b/types/ioredis/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/ioredis/tslint.json +++ b/types/ioredis/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/iota.lib.js/index.d.ts b/types/iota.lib.js/index.d.ts new file mode 100644 index 0000000000..758c6a0b3c --- /dev/null +++ b/types/iota.lib.js/index.d.ts @@ -0,0 +1,486 @@ +// Type definitions for iota.lib.js 0.4 +// Project: https://github.com/iotaledger/iota.lib.js +// Definitions by: Fogsh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class IotaClass { + constructor(settings: { + provider: string; + sandbox?: boolean; + token?: boolean; + } | { + host: string; + port: number; + sandbox?: boolean; + token?: boolean; + }); + + api: IotaApi; + utils: IotaUtils; + multisig: IotaMultisig; + valid: IotaValid; + + version: string; +} + +export = IotaClass; + +// +// Types +// + +type Security = 1 | 2 | 3; +type IOTAUnit = "i" | "Ki" | "Mi" | "Gi" | "Ti" | "Pi"; + +// +// Objects +// + +interface TransactionObject { + hash: string; + signatureMessageFragment: string; + address: string; + value: number; + tag: string; + timestamp: number; + currentIndex: number; + lastIndex: number; + bundle: number; + trunkTransaction: string; + branchTransaction: string; + attachmentTimestamp: number; + attachmentTimestampLowerBound: number; + attachmentTimestampUpperBound: number; + nonce: string; +} + +interface InputObject { + address: string; + balance: number; + keyIndex: number; + security: Security; +} + +interface TransferObject { + address: string; + value: number; + message: string; + tag: string; +} + +interface NodeInfo { + appName: string; + appVersion: string; + duration: number; + jreAvailableProcessors: number; + jreFreeMemory: number; + jreVersion: string; + jreMaxMemory: number; + jreTotalMemory: number; + latestMilestone: string; + latestMilestoneIndex: number; + latestSolidSubtangleMilestone: string; + latestSolidSubtangleMilestoneIndex: number; + neighbors: number; + packetsQueueSize: number; + time: number; + tips: number; + transactionsToRequest: number; +} + +interface Neighbor { + address: string; + numberOfAllTransactions: number; + numberOfRandomTransactionRequests: number; + numberOfInvalidTransactions: number; + numberOfSentTransactions: number; + numberOfNewTransactions: number; + connectionType: "udp" | "tcp"; +} + +// +// iota.api +// + +interface IriApi { + getNodeInfo( + callback: (error: Error, info: NodeInfo) => void + ): void; + + getNeighbors( + callback: (error: Error, neighbors: Neighbor[]) => void + ): void; + + addNeighbors( + uris: string[], + callback: (error: Error, addedNeighbors: number) => void + ): void; + + removeNeighbors( + uris: string[], + callback: (error: Error, removedNeighbors: number[]) => void + ): void; + + getTips( + callback: (error: Error, hashes: string[]) => void + ): void; + + findTransactions( + searchValues: { + addresses?: string[] + bundles?: string[] + tags?: string[] + approvees?: string[] + }, + callback: (error: Error, hashes: string[]) => void + ): void; + + getTrytes( + hashes: string[], + callback: (error: Error, trytes: string[]) => void + ): void; + + getInclusionStates( + transactions: string[], + tips: string[], + callback: (error: Error, states: boolean[]) => void + ): void; + + getBalances( + addresses: string[], + treshold: number, + callback: (error: Error, response: { + balances: number[] + milestone: string; + milestoneIndex: number; + duration: number; + }) => void + ): void; + + getTransactionsToApprove( + depth: number, + callback: (error: Error, response: { + trunkTransaction: string; + branchTransaction: string; + duration: number; + }) => void + ): void; + + attachToTangle( + trunkTransaction: string, + branchTransaction: string, + minWeightMagnitude: number, + trytes: string[], + callback: (error: Error, trytes: string[]) => void + ): void; + + interruptAttachingToTangle( + callback: (error: Error, response: {}) => void + ): void; + + broadcastTransactions( + trytes: string[], + callback: (error: Error, response: {}) => void + ): void; + + storeTransactions( + trytes: string[], + callback: (error: Error, response: {}) => void + ): void; +} + +// +// iota.api +// + +interface IotaApi extends IriApi { + getTransactionsObjects( + hashes: string[], + callback?: (error: Error, transactions: TransactionObject[]) => void + ): void; + + findTransactionObjects( + searchValues: { + addresses?: string[] + bundles?: string[] + tags?: string[] + approvees?: string[] + }, + callback?: (error: Error, transactions: TransactionObject[]) => void + ): void; + + getLatestInclusion( + hashes: string[], + callback?: (error: Error, states: boolean[]) => void + ): void; + + broadcastAndStore( + trytes: string[], + callback?: (error: Error, response: {}) => void + ): void; + + getNewAddress( + seed: string, + options?: { + index?: number; + checksum?: boolean; + total?: number; + security?: Security + returnAll?: boolean; + }, + callback?: (error: Error, response: string | string[]) => void + ): void; + + getInputs( + seed: string, + options?: { + start?: number; + end?: number; + security?: Security + threshold?: boolean; + }, + callback?: (error: Error, response: { + inputs: InputObject[] + }) => void + ): void; + + prepareTransfers( + seed: string, + transfers: TransferObject[], + options?: { + inputs?: string[], + address?: string, + security?: Security + }, + callback?: (error: Error, response: { + trytes: string[] + }) => void + ): void; + + sendTrytes( + trytes: string[], + depth: number, + minWeightMagnitude: number, + callback?: (error: Error, response: { + inputs: TransactionObject[] + }) => void + ): void; + + sendTransfer( + seed: string, + depth: number, + minWeightMagnitude: number, + transfers: TransferObject[], + options?: { + inputs: string[], + address: string; + }, + callback?: (error: Error, response: { + inputs: TransactionObject[] + }) => void + ): void; + + replayBundle( + transactionHash: string, + depth: number, + minWeightMagnitude: number, + callback?: (error: Error, response: {}) => void + ): void; + + broadcastBundle( + transactionHash: string, + callback?: (error: Error, response: {}) => void + ): void; + + getBundle( + transactionHash: string, + callback?: (error: Error, bundle: TransactionObject[]) => void + ): void; + + getTransfers( + seed: string, + options?: { + start?: number; + end?: number; + security?: Security + inclusionStates?: boolean; + }, + callback?: (error: Error, transfers: TransactionObject[][]) => void + ): void; + + getAccountData( + seed: string, + options?: { + start: number; + end: number; + security?: Security + }, + callback?: (error: Error, response: { + latestAddress: string; + addresses: string[] + transfers: string[] + inputs: InputObject[] + balance: number; + }) => void + ): void; + + isReattachable( + address: string | string[], + callback?: (error: Error, response: boolean | boolean[]) => void + ): void; +} + +// +// iota.utils +// + +interface IotaUtils { + convertUnits( + value: number, + fromUnit: IOTAUnit, + toUnit: IOTAUnit + ): number; + + addChecksum( + inputValue: string, + checksumLength?: number, + isAddress?: boolean + ): string; + + addChecksum( + inputValue: string[], + checksumLength?: number, + isAddress?: boolean + ): string[]; + + noChecksum( + address: string + ): string; + + isValidChecksum( + addressWithChecksum: string + ): boolean; + + transactionObject( + trytes: string + ): TransactionObject; + + transactionTrytes( + transaction: TransactionObject + ): string; + + categorizeTransfers( + transfers: TransactionObject[], + addresses: string[] + ): { + sent: TransactionObject[] + received: TransactionObject[] + }; + + toTrytes( + input: string + ): string; + + fromTrytes( + trytes: string + ): string; + + extractJson( + bundle: TransactionObject[] + ): string; + + validateSignatures( + signedBundle: string[], + inputAddress: string + ): boolean; + + isBundle( + bundle: TransactionObject[] + ): boolean; +} + +// +// iota.multisig +// + +interface IotaMultisig { + getKey( + seed: string, + index: number, + security: Security + ): string; + + getDigest( + seed: string, + index: number, + security: Security + ): string; + + address( + digestTrytes: string | string[] + ): MultisigAddress; + + validateAddress( + multisigAddress: string, + digests: string[] + ): boolean; + + initiateTransfer( + securitySum: number, + inputAddress: string, + remainderAddress: string, + transfers: TransferObject[], + callback?: (error: Error, bundle: TransactionObject[]) => void + ): void; + + addSignature( + bundleToSign: TransactionObject[], + inputAddress: string, + key: string, + callback?: (error: Error, bundle: TransactionObject[]) => void + ): void; +} + +interface MultisigAddress { + absorb( + digest: string | string[] + ): MultisigAddress; + + finalize(): string; +} + +// +// iota.valid +// + +interface IotaValid { + isAddress(address: string): boolean; + + isTrytes(trytes: string, length?: number): boolean; + + isValue(value: any): boolean; + + isNum(value: any): boolean; + + isHash(hash: any): boolean; + + isTransfersArray(transfers: any): boolean; + + isArrayOfHashes(hashes: any): boolean; + + isArrayOfTrytes(trytes: any): boolean; + + isArrayOfAttachedTrytes(trytes: any): boolean; + + isArrayOfTxObjects(transactions: any): boolean; + + isInputs(inputs: any): boolean; + + isString(string: any): boolean; + + isArray(array: any): boolean; + + isObject(object: any): boolean; + + isUri(uri: any): boolean; +} diff --git a/types/iota.lib.js/iota.lib.js-tests.ts b/types/iota.lib.js/iota.lib.js-tests.ts new file mode 100644 index 0000000000..6b3c3a9b85 --- /dev/null +++ b/types/iota.lib.js/iota.lib.js-tests.ts @@ -0,0 +1,94 @@ +import IOTA = require("iota.lib.js"); + +const config = { + node: "https://localhost:14265", + address: "999999999999999999999999999999999999999999999999999999999999999999999999999999999", + transaction: "999999999999999999999999999999999999999999999999999999999999999999999999999999999" +}; + +const iota = new IOTA({ + provider: config.node +}); + +// +// iota.api +// + +iota.api.getNodeInfo((error, info) => { +}); + +iota.api.getNeighbors((error, info) => { +}); + +iota.api.addNeighbors(["udp://127.0.0.2:14600"], (error, count) => { +}); + +iota.api.removeNeighbors(["udp://127.0.0.2:14600"], (error, count) => { +}); + +iota.api.findTransactions({ + addresses: [config.address] +}, (error, hashes) => { +}); + +iota.api.getTrytes([config.address], (error, trytes) => { +}); + +iota.api.getInclusionStates([config.address], [config.transaction], (error, states) => { +}); + +iota.api.getBalances([config.address], 1, (error, states) => { +}); + +iota.api.getTransactionsToApprove(1, (error, transactions) => { +}); + +iota.api.getTransactionsObjects([config.transaction], (err, response) => { +}); + +iota.api.findTransactionObjects({ + addresses: [config.address] +}, (err, response) => { +}); + +iota.api.getLatestInclusion([config.address], (err, response) => { +}); + +// +// iota.utils +// + +iota.utils.convertUnits(1000, "i", "Mi"); + +const checksum = iota.utils.addChecksum(config.address); +iota.utils.noChecksum(checksum); +iota.utils.isValidChecksum(checksum); + +const transactionObj = iota.utils.transactionObject(new Array(2674).join("9")); +iota.utils.transactionTrytes(transactionObj); + +const trytes = iota.utils.toTrytes("HELLO TANGLE"); +iota.utils.fromTrytes(trytes); + +// +// iota.valid +// + +iota.valid.isAddress(config.address); + +iota.valid.isTrytes(trytes); + +iota.valid.isValue(0); + +iota.valid.isNum(0); + +iota.valid.isHash(config.address); + +const transferObj = { + address: config.address, + message: "", + value: 0, + tag: "" +}; + +iota.valid.isTransfersArray([transferObj]); diff --git a/types/iota.lib.js/tsconfig.json b/types/iota.lib.js/tsconfig.json new file mode 100644 index 0000000000..b206b83455 --- /dev/null +++ b/types/iota.lib.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iota.lib.js-tests.ts" + ] +} \ No newline at end of file diff --git a/types/iota.lib.js/tslint.json b/types/iota.lib.js/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/iota.lib.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/is-glob/index.d.ts b/types/is-glob/index.d.ts new file mode 100644 index 0000000000..3c478c084b --- /dev/null +++ b/types/is-glob/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for is-glob 4.0 +// Project: https://github.com/jonschlinkert/is-glob +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isGlob(pattern?: string | string[] | null, options?: isGlob.Options): boolean; + +declare namespace isGlob { + interface Options { + /** + * When `false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns + * that would return false may return true. This is done so that matching libraries like micromatch + * have a chance at determining if the pattern is a glob or not. + */ + strict?: boolean; + } +} + +export = isGlob; diff --git a/types/is-glob/is-glob-tests.ts b/types/is-glob/is-glob-tests.ts new file mode 100644 index 0000000000..7b9b442173 --- /dev/null +++ b/types/is-glob/is-glob-tests.ts @@ -0,0 +1,10 @@ +import * as isGlob from 'is-glob'; + +// $ExpectType boolean +isGlob(); +isGlob(null); +isGlob('abc.js'); +isGlob(['abc.js']); + +isGlob('abc.js', {}); +isGlob('abc.js', { strict: false }); diff --git a/types/is-glob/tsconfig.json b/types/is-glob/tsconfig.json new file mode 100644 index 0000000000..1a408fe456 --- /dev/null +++ b/types/is-glob/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-glob-tests.ts" + ] +} diff --git a/types/is-glob/tslint.json b/types/is-glob/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-glob/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is/index.d.ts b/types/is/index.d.ts index 3c0e279eea..b61bd6deee 100644 --- a/types/is/index.d.ts +++ b/types/is/index.d.ts @@ -1320,4 +1320,8 @@ declare var is: Is; declare module 'is' { export = is; -} \ No newline at end of file +} + +declare module 'is_js' { + export = is; +} diff --git a/types/jasmine-enzyme/jasmine-enzyme-tests.tsx b/types/jasmine-enzyme/jasmine-enzyme-tests.tsx index 53ee972ed3..6246618d86 100644 --- a/types/jasmine-enzyme/jasmine-enzyme-tests.tsx +++ b/types/jasmine-enzyme/jasmine-enzyme-tests.tsx @@ -254,7 +254,7 @@ describe('toHaveRef', () => { describe('toHaveState', () => { class Fixture extends React.Component { constructor() { - super(); + super({}); this.state = { foo: false, }; diff --git a/types/jasmine-given/index.d.ts b/types/jasmine-given/index.d.ts index 28338d7664..e2b630eccd 100644 --- a/types/jasmine-given/index.d.ts +++ b/types/jasmine-given/index.d.ts @@ -6,5 +6,6 @@ declare function Given(func: (done?: () => void) => void): void; declare function When(func: (done?: () => void) => void): void; declare function Then(func: (done?: () => void) => void): void; +declare function Then(label: string, func: (done?: () => void) => void): void; declare function And(func: (done?: () => void) => void): void; declare function Invariant(func: (done?: () => void) => void): void; diff --git a/types/jasmine-given/jasmine-given-tests.ts b/types/jasmine-given/jasmine-given-tests.ts index e9603e3aaf..7658502b68 100644 --- a/types/jasmine-given/jasmine-given-tests.ts +++ b/types/jasmine-given/jasmine-given-tests.ts @@ -4,6 +4,8 @@ When(() => { }); Then(() => { }); +Then('expected condition 1', () => { }); + And(() => { }); Invariant(() => { }); @@ -20,7 +22,7 @@ When((done) => { } }); -Then((done) => { +Then('expected condition 2', (done) => { if (done) { done(); } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 900c235990..c1c15e45de 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -1,9 +1,8 @@ -// Type definitions for Jasmine 2.6.0 +// Type definitions for Jasmine 2.8.0 // Project: http://jasmine.github.io/ // Definitions by: Boris Yankov , Theodore Brown , David Pärsson , Gabe Moothart , Lukas Zech // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - +// TypeScript Version: 2.1 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts @@ -91,6 +90,11 @@ declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; */ declare function expect(actual: T): jasmine.Matchers; +/** + * Create an expectation for a spec. + */ +declare function expect(): jasmine.NothingMatcher; + /** * Explicitly mark a spec as failed. * @param e @@ -135,9 +139,10 @@ declare namespace jasmine { function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; + function arrayContaining(sample: ArrayLike): ArrayContaining; + function arrayWithExactContents(sample: ArrayLike): ArrayContaining; function objectContaining(sample: Partial): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; + function createSpy(name?: string, originalFn?: Function): Spy; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): any; function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): SpyObj; @@ -173,8 +178,8 @@ declare namespace jasmine { [n: number]: T; } - interface ArrayContaining { - new (sample: any[]): any; + interface ArrayContaining { + new (sample: ArrayLike): ArrayLike; asymmetricMatch(other: any): boolean; jasmineToString(): string; @@ -441,18 +446,23 @@ declare namespace jasmine { toThrow(expected?: any): boolean; toThrowError(message?: string | RegExp): boolean; toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; + not: Matchers; Any: Any; } interface ArrayLikeMatchers extends Matchers> { - toBe(expected: Expected>, expectationFailOutput?: any): boolean; - toEqual(expected: Expected>, expectationFailOutput?: any): boolean; + toBe(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; + toEqual(expected: Expected> | ArrayContaining, expectationFailOutput?: any): boolean; toContain(expected: Expected, expectationFailOutput?: any): boolean; not: ArrayLikeMatchers; } + interface NothingMatcher { + nothing(): void; + } + interface Reporter { reportRunnerStarting(runner: Runner): void; reportRunnerResults(runner: Runner): void; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index d1aad60716..ab132d3cee 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -33,7 +33,7 @@ describe("Included matchers:", () => { var b = a; expect(a).toBe(b); - expect(a).not.toBe(null); + expect(a).not.toBe(24); }); describe("The 'toEqual' matcher", () => { @@ -54,6 +54,11 @@ describe("Included matchers:", () => { }; expect(foo).toEqual(bar); }); + + it("should work for optional values", () => { + var opt: string | undefined = "s"; + expect(opt as (string | undefined)).toEqual(undefined); + }); }); it("The 'toMatch' matcher is for regular expressions", () => { @@ -83,7 +88,7 @@ describe("Included matchers:", () => { }); it("The 'toBeNull' matcher compares against null", () => { - var a: string = null; + var a: string | null = null; var foo = "foo"; expect(null).toBeNull(); @@ -92,14 +97,14 @@ describe("Included matchers:", () => { }); it("The 'toBeTruthy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", () => { - var a: string, foo = "foo"; + var a: string | undefined, foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); @@ -665,6 +670,12 @@ describe("Multiple spies, when created manually", () => { }); }); +describe("jasmine.nothing", () => { + it("matches any value", () => { + expect().nothing(); + }); +}); + describe("jasmine.any", () => { it("matches any value", () => { expect({}).toEqual(jasmine.any(Object)); @@ -754,7 +765,7 @@ describe("jasmine.objectContaining", () => { }); describe("jasmine.arrayContaining", () => { - var foo: any; + var foo: Array; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -763,6 +774,9 @@ describe("jasmine.arrayContaining", () => { it("matches arrays with some of the values", () => { expect(foo).toEqual(jasmine.arrayContaining([3, 1])); expect(foo).not.toEqual(jasmine.arrayContaining([6])); + + expect(foo).toBe(jasmine.arrayContaining([3, 1])); + expect(foo).not.toBe(jasmine.arrayContaining([6])); }); describe("when used with a spy", () => { @@ -777,6 +791,33 @@ describe("jasmine.arrayContaining", () => { }); }); +describe("jasmine.arrayWithExactContents", () => { + var foo: Array; + + beforeEach(() => { + foo = [1, 2, 3, 4]; + }); + + it("matches arrays with exactly the same values", () => { + expect(foo).toEqual(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toEqual(jasmine.arrayWithExactContents([6])); + + expect(foo).toBe(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(foo).not.toBe(jasmine.arrayWithExactContents([6])); + }); + + describe("when used with a spy", () => { + it("is useful when comparing arguments", () => { + var callback = jasmine.createSpy('callback'); + + callback([1, 2, 3, 4]); + + expect(callback).toHaveBeenCalledWith(jasmine.arrayWithExactContents([1, 2, 3, 4])); + expect(callback).not.toHaveBeenCalledWith(jasmine.arrayWithExactContents([5, 2])); + }); + }); +}); + describe("Manually ticking the Jasmine Clock", () => { var timerCallback: any; @@ -961,13 +1002,13 @@ describe("Custom matcher: 'toBeGoofy'", () => { hyuk: 'this is fun' }).not.toBeGoofy(); }); - + it("has a proper message on failure", () => { const actual = { hyuk: 'this is fun' }; - - const matcher = customMatchers.toBeGoofy(jasmine.matchersUtil, []); + + const matcher = customMatchers["toBeGoofy"](jasmine.matchersUtil, []); const result = matcher.compare(actual, null); - + expect(result.pass).toBe(false); expect(result.message).toBe("Expected " + actual + " to be goofy, but it was not very goofy"); }); @@ -990,19 +1031,19 @@ var myReporter: jasmine.CustomReporter = { specDone: (result: jasmine.CustomReporterResult) => { console.log("Spec: " + result.description + " was " + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log("Failure: " + result.failedExpectations[i].message); console.log("Actual: " + result.failedExpectations[i].actual); console.log("Expected: " + result.failedExpectations[i].expected); console.log(result.failedExpectations[i].stack); } - console.log(result.passedExpectations.length); + console.log(result.passedExpectations && result.passedExpectations.length); }, suiteDone: (result: jasmine.CustomReporterResult) => { console.log('Suite: ' + result.description + ' was ' + result.status); //tslint:disable-next-line:prefer-for-of - for (var i = 0; i < result.failedExpectations.length; i++) { + for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i++) { console.log('AfterAll ' + result.failedExpectations[i].message); console.log(result.failedExpectations[i].stack); } diff --git a/types/jasmine/tsconfig.json b/types/jasmine/tsconfig.json index 3af72e4d8b..55b83c6d3a 100644 --- a/types/jasmine/tsconfig.json +++ b/types/jasmine/tsconfig.json @@ -11,7 +11,7 @@ ], "noImplicitAny": true, "noImplicitThis": false, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/jbinary/index.d.ts b/types/jbinary/index.d.ts index 1e9c9c6f03..857627056d 100644 --- a/types/jbinary/index.d.ts +++ b/types/jbinary/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jDataView/jBinary // Definitions by: Tim Bureck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Additional notes: // Method stubs and types are taken from the official jBinary documentation, which can be found here: diff --git a/types/jest-json-schema/index.d.ts b/types/jest-json-schema/index.d.ts new file mode 100644 index 0000000000..67f1c51f7e --- /dev/null +++ b/types/jest-json-schema/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jest-json-schema 1.2 +// Project: https://github.com/americanexpress/jest-json-schema#readme +// Definitions by: Igor Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +import * as ajv from "ajv"; + +declare global { + namespace jest { + interface Matchers { + toMatchSchema(schema: object): R; + } + } +} + +export const matchers: jest.ExpectExtendMap; +export function matchersWithOptions(options: ajv.Options): jest.ExpectExtendMap; diff --git a/types/jest-json-schema/jest-json-schema-tests.ts b/types/jest-json-schema/jest-json-schema-tests.ts new file mode 100644 index 0000000000..a66c54a7e9 --- /dev/null +++ b/types/jest-json-schema/jest-json-schema-tests.ts @@ -0,0 +1,13 @@ +import { matchers } from 'jest-json-schema'; + +expect.extend(matchers); + +it('validates my json', () => { + const schema = { + properties: { + hello: { type: 'string' }, + }, + required: ['hello'], + }; + expect({ hello: 'world' }).toMatchSchema(schema); +}); diff --git a/types/jest-json-schema/package.json b/types/jest-json-schema/package.json new file mode 100644 index 0000000000..ee16c03768 --- /dev/null +++ b/types/jest-json-schema/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "ajv": "^4.11.5" + } +} diff --git a/types/jest-json-schema/tsconfig.json b/types/jest-json-schema/tsconfig.json new file mode 100644 index 0000000000..e8d55cbd89 --- /dev/null +++ b/types/jest-json-schema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jest-json-schema-tests.ts" + ] +} diff --git a/types/jest-json-schema/tslint.json b/types/jest-json-schema/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jest-json-schema/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jest-matcher-utils/index.d.ts b/types/jest-matcher-utils/index.d.ts index 92bc13070b..54e6db67b3 100644 --- a/types/jest-matcher-utils/index.d.ts +++ b/types/jest-matcher-utils/index.d.ts @@ -4,19 +4,19 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import * as chalk from 'chalk'; +import { Chalk } from 'chalk'; -export const EXPECTED_COLOR: chalk.ChalkChain; -export const RECEIVED_COLOR: chalk.ChalkChain; -export const EXPECTED_BG: chalk.ChalkChain; // TODO: removed in b430e51a -export const RECEIVED_BG: chalk.ChalkChain; // TODO: removed in b430e51a +export const EXPECTED_COLOR: Chalk; +export const RECEIVED_COLOR: Chalk; +export const EXPECTED_BG: Chalk; // TODO: removed in b430e51a +export const RECEIVED_BG: Chalk; // TODO: removed in b430e51a export const SUGGEST_TO_EQUAL: string; export function stringify(object: any, maxDepth?: number): string; export function highlightTrailingWhitespace( text: string, - bgColor: chalk.ChalkChain // removed in b430e51a + bgColor: Chalk // removed in b430e51a ): string; export function printReceived(object: any): string; diff --git a/types/jest-matcher-utils/jest-matcher-utils-tests.ts b/types/jest-matcher-utils/jest-matcher-utils-tests.ts index 6f9a4ddeab..6c59a7c274 100644 --- a/types/jest-matcher-utils/jest-matcher-utils-tests.ts +++ b/types/jest-matcher-utils/jest-matcher-utils-tests.ts @@ -1,8 +1,8 @@ -import * as chalk from 'chalk'; +import chalk from 'chalk'; import * as utils from 'jest-matcher-utils'; -utils.EXPECTED_COLOR; // $ExpectType ChalkChain -utils.RECEIVED_COLOR; // $ExpectType ChalkChain +utils.EXPECTED_COLOR; // $ExpectType Chalk +utils.RECEIVED_COLOR; // $ExpectType Chalk utils.SUGGEST_TO_EQUAL; // $ExpectType string utils.stringify({}); // $ExpectType string diff --git a/types/jest-matcher-utils/package.json b/types/jest-matcher-utils/package.json new file mode 100644 index 0000000000..2cc9b48ed6 --- /dev/null +++ b/types/jest-matcher-utils/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "chalk": "^2.2.0" + } +} diff --git a/types/jest-matchers/index.d.ts b/types/jest-matchers/index.d.ts index 27e6a5b9f0..3b028f8929 100644 --- a/types/jest-matchers/index.d.ts +++ b/types/jest-matchers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/facebook/jest#readme // Definitions by: Joscha Feth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// export = expect; diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 18b3db361a..5c2152694f 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -8,6 +8,7 @@ // Allan Lukwago // Ika // Waseem Dahman +// Jamie Mason // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -144,10 +145,16 @@ declare namespace jest { */ function runOnlyPendingTimers(): typeof jest; /** - * Executes only the macro task queue (i.e. all tasks queued by setTimeout() - * or setInterval() and setImmediate()). + * (renamed to `advanceTimersByTime` in Jest 21.3.0+) Executes only the macro + * task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ function runTimersToTime(msToRun: number): typeof jest; + /** + * Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been + * queued via setTimeout() or setInterval(), and would be executed within this timeframe + * will be executed. + */ + function advanceTimersByTime(msToRun: number): typeof jest; /** * Explicitly supplies the mock object that the module system should return * for the specified module. @@ -240,7 +247,7 @@ declare namespace jest { } interface ExpectExtendMap { - [key: string]: (this: MatcherUtils, received: any, actual: any) => { message(): string, pass: boolean }; + [key: string]: (this: MatcherUtils, received: any, ...actual: any[]) => { message(): string, pass: boolean }; } interface SnapshotSerializerOptions { @@ -554,7 +561,7 @@ declare namespace jasmine { function anything(): Any; function arrayContaining(sample: any[]): ArrayContaining; function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: (...args: any[]) => any): Spy; + function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; @@ -866,6 +873,7 @@ declare namespace jest { runAllTicks(): void; runAllTimers(): void; runTimersToTime(msToRun: number): void; + advanceTimersByTime(msToRun: number): void; runOnlyPendingTimers(): void; runWithRealTimers(callback: any): void; useFakeTimers(): void; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index d2b4d95a0e..aca5021f1b 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -259,6 +259,12 @@ describe('Extending extend', () => { () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; return { message, pass }; }, + toBeVariadicMatcher(received: any, floor: number, ceiling: number) { + const pass = received >= floor && received <= ceiling; + const message = + () => `expected ${received} ${pass ? 'not ' : ''} to be within range ${floor}-${ceiling}`; + return { message, pass }; + }, toBeTest(received: any, actual: any) { this.utils.ensureNoExpected(received); this.utils.ensureActualIsNumber(received); diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 02ac767427..41a8063cac 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,6 +1,14 @@ -// Type definitions for joi v10.4.2 +// Type definitions for joi v13.0.1 // Project: https://github.com/hapijs/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier , Rytis Alekna , Pavel Ivanov , Youngrok Kim +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim +// Dan Kraus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -88,7 +96,7 @@ export interface EmailOptions { /** * Specifies a list of acceptable TLDs. */ - tldWhitelist?: string[] | Object; + tldWhitelist?: string[] | object; /** * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. */ @@ -120,6 +128,13 @@ export interface UriOptions { scheme?: string | RegExp | Array; } +export interface Base64Options { + /** + * optional parameter defaulting to true which will require = padding if true or make padding optional if false + */ + paddingRequired?: boolean; +} + export interface WhenOptions { /** * the required condition joi type. @@ -161,7 +176,7 @@ export interface ValidationError extends Error, JoiObject { export interface ValidationErrorItem { message: string; type: string; - path: string; + path: string[]; options?: ValidationOptions; context?: Context; } @@ -195,6 +210,8 @@ export type Schema = AnySchema export interface AnySchema extends JoiObject { + schemaType?: Types | string; + /** * Validates a value using the schema and options. */ @@ -270,7 +287,7 @@ export interface AnySchema extends JoiObject { /** * Attaches metadata to the key. */ - meta(meta: Object): this; + meta(meta: object): this; /** * Annotates the key with an example value, must be valid. @@ -346,7 +363,7 @@ export interface AnySchema extends JoiObject { * an instance of `Error` - the override error. * a `function(errors)`, taking an array of errors as argument, where it must either: * return a `string` - substitutes the error message with this text - * return a single `object` or an `Array` of it, where: + * return a single ` object` or an `Array` of it, where: * `type` - optional parameter providing the type of the error (eg. `number.min`). * `message` - optional parameter if `template` is provided, containing the text of the error. * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. @@ -384,6 +401,8 @@ export interface Description { export interface Context { [key: string]: any; + key?: string; + label?: string; } export interface State { @@ -455,7 +474,7 @@ export interface NumberSchema extends AnySchema { /** * Specifies the maximum number of decimal places where: - * limit - the maximum number of decimal places allowed. + * @param limit - the maximum number of decimal places allowed. */ precision(limit: number): this; @@ -497,6 +516,24 @@ export interface StringSchema extends AnySchema { max(limit: number, encoding?: string): this; max(limit: Reference, encoding?: string): this; + /** + * Specifies whether the string.max() limit should be used as a truncation. + * @param enabled - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value. + */ + truncate(enabled?: boolean): this; + + /** + * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized. + * @param form - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + + /** + * Requires the string value to be a valid base64 string; does not check the decoded value. + * @param options - optional settings: The unicode normalization options to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + base64(options?: Base64Options): this; + /** * Requires the number to be a credit card number (Using Lunh Algorithm). */ @@ -554,7 +591,7 @@ export interface StringSchema extends AnySchema { * Requires the string value to be a valid GUID. */ guid(options?: GuidOptions): this; - + /** * Alias for `guid` -- Requires the string value to be a valid GUID */ @@ -651,6 +688,7 @@ export interface ArraySchema extends AnySchema { } export interface ObjectSchema extends AnySchema { + /** * Sets the allowed object keys. */ @@ -888,7 +926,7 @@ export type ExtensionBoundSchema = Schema & { export interface Rules

{ name: string; - params?: ObjectSchema | { [key in keyof P]: SchemaLike; }; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; setup?(this: ExtensionBoundSchema, params: P): Schema | void; validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; description?: string | ((params: P) => string); @@ -965,10 +1003,15 @@ export function string(): StringSchema; /** * Generates a type that will match one of the provided alternative schemas */ -export function alternatives(): AlternativesSchema; export function alternatives(types: SchemaLike[]): AlternativesSchema; export function alternatives(...types: SchemaLike[]): AlternativesSchema; +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + /** * Generates a placeholder schema for a schema that you would provide with the fn. * Supports the same methods of the any() type. @@ -1030,7 +1073,140 @@ export function reach(schema: ObjectSchema, path: string): T; */ export function extend(extention: Extension): any; +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +import * as Module from 'joi'; +export type Root = typeof Module; +export type DefaultsFunction = (root: Schema) => Schema; + +/** + * Creates a new Joi instance that will apply defaults onto newly created schemas + * through the use of the fn function that takes exactly one argument, the schema being created. + * + * @param fn - The function must always return a schema, even if untransformed. + */ +export function defaults(fn: DefaultsFunction): Root; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + /** * Returns a plain object representing the schema's rules and properties */ export function describe(schema: Schema): Description; + +/** +* Whitelists a value +*/ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 4f49a69b3f..785360746e 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -1,51 +1,52 @@ import Joi = require('joi'); +import { GuidVersions } from 'joi'; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var x: any = null; -var value: any = null; -var num: number = 0; -var str: string = ''; -var bool: boolean = false; -var exp: RegExp = null; -var obj: object = null; -var date: Date = null; -var err: Error = null; -var func: Function = null; +let x: any = null; +let value: any = null; +let num: number = 0; +let str: string = ''; +let bool: boolean = false; +let exp: RegExp = null; +let obj: object = null; +let date: Date = null; +let err: Error = null; +let func: Function = null; -var anyArr: any[] = []; -var numArr: number[] = []; -var strArr: string[] = []; -var boolArr: boolean[] = []; -var expArr: RegExp[] = []; -var objArr: object[] = []; -var errArr: Error[] = []; -var funcArr: Function[] = []; +let anyArr: any[] = []; +let numArr: number[] = []; +let strArr: string[] = []; +let boolArr: boolean[] = []; +let expArr: RegExp[] = []; +let objArr: object[] = []; +let errArr: Error[] = []; +let funcArr: Function[] = []; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schema: Joi.Schema = null; -var schemaLike: Joi.SchemaLike = null; +let schema: Joi.Schema = null; +let schemaLike: Joi.SchemaLike = null; -var anySchema: Joi.AnySchema = null; -var numSchema: Joi.NumberSchema = null; -var strSchema: Joi.StringSchema = null; -var arrSchema: Joi.ArraySchema = null; -var boolSchema: Joi.BooleanSchema = null; -var binSchema: Joi.BinarySchema = null; -var dateSchema: Joi.DateSchema = null; -var funcSchema: Joi.FunctionSchema = null; -var objSchema: Joi.ObjectSchema = null; -var altSchema: Joi.AlternativesSchema = null; +let anySchema: Joi.AnySchema = null; +let numSchema: Joi.NumberSchema = null; +let strSchema: Joi.StringSchema = null; +let arrSchema: Joi.ArraySchema = null; +let boolSchema: Joi.BooleanSchema = null; +let binSchema: Joi.BinarySchema = null; +let dateSchema: Joi.DateSchema = null; +let funcSchema: Joi.FunctionSchema = null; +let objSchema: Joi.ObjectSchema = null; +let altSchema: Joi.AlternativesSchema = null; -var schemaArr: Joi.Schema[] = []; +let schemaArr: Joi.Schema[] = []; -var ref: Joi.Reference = null; -var description: Joi.Description = null; +let ref: Joi.Reference = null; +let description: Joi.Description = null; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validOpts: Joi.ValidationOptions = null; +let validOpts: Joi.ValidationOptions = null; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; @@ -77,7 +78,7 @@ validOpts = { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var renOpts: Joi.RenameOptions = null; +let renOpts: Joi.RenameOptions = null; renOpts = { alias: bool }; renOpts = { multiple: bool }; @@ -86,7 +87,7 @@ renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var emailOpts: Joi.EmailOptions = null; +let emailOpts: Joi.EmailOptions = null; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; @@ -96,7 +97,7 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var ipOpts: Joi.IpOptions = null; +let ipOpts: Joi.IpOptions = null; ipOpts = { version: str }; ipOpts = { version: strArr }; @@ -104,7 +105,7 @@ ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var uriOpts: Joi.UriOptions = null; +let uriOpts: Joi.UriOptions = null; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; @@ -113,7 +114,13 @@ uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var whenOpts: Joi.WhenOptions = null; +let base64Opts: Joi.Base64Options = null; + +base64Opts = { paddingRequired: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +let whenOpts: Joi.WhenOptions = null; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; @@ -122,27 +129,27 @@ whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var refOpts: Joi.ReferenceOptions = null; +let refOpts: Joi.ReferenceOptions = null; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var validErr: Joi.ValidationError = null; -var validErrItem: Joi.ValidationErrorItem; -var validErrFunc: Joi.ValidationErrorFunction; +let validErr: Joi.ValidationError = null; +let validErrItem: Joi.ValidationErrorItem; +let validErrFunc: Joi.ValidationErrorFunction; validErrItem = { message: str, type: str, - path: str + path: [str] }; validErrItem = { message: str, type: str, - path: str, + path: [str], options: validOpts, context: obj }; @@ -176,7 +183,7 @@ anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -var schemaMap: Joi.SchemaMap = null; +let schemaMap: Joi.SchemaMap = null; schemaMap = { a: numSchema, @@ -765,7 +772,7 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: ['uuidv1' as GuidVersions, 'uuidv2' as GuidVersions, 'uuidv3' as GuidVersions, 'uuidv4' as GuidVersions, 'uuidv5' as GuidVersions]}); strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); @@ -773,6 +780,12 @@ strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); strSchema = strSchema.uppercase(); strSchema = strSchema.trim(); +strSchema = strSchema.truncate(); +strSchema = strSchema.truncate(false); +strSchema = strSchema.normalize(); +strSchema = strSchema.normalize('NFKC'); +strSchema = strSchema.base64(); +strSchema = strSchema.base64(base64Opts); namespace common { strSchema = strSchema.allow(x); @@ -830,6 +843,13 @@ schema = Joi.alternatives().try(schema, schema); schema = Joi.alternatives(schemaArr); schema = Joi.alternatives(schema, anySchema, boolSchema); +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- schema = Joi.lazy(() => schema) @@ -844,14 +864,14 @@ namespace validate_tests { Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path[0]; str = err.details[0].message; str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { x = value; str = err.message; - str = err.details[0].path; + str = err.details[0].path.join('.'); str = err.details[0].message; str = err.details[0].type; }); @@ -950,3 +970,120 @@ const Joi3 = Joi.extend({ }, ], }); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +const defaultsJoi = Joi.defaults((schema) => { + switch (schema.schemaType) { + case 'string': + return schema.allow(''); + case 'object': + return (schema as Joi.ObjectSchema).min(1); + default: + return schema; + } +}); + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index f6b8f170dc..57e6c47881 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "joi-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/joi/v10/index.d.ts b/types/joi/v10/index.d.ts new file mode 100644 index 0000000000..372975ed9e --- /dev/null +++ b/types/joi/v10/index.d.ts @@ -0,0 +1,1178 @@ +// Type definitions for joi v10.6.0 +// Project: https://github.com/hapijs/joi +// Definitions by: Bart van der Schoor +// Laurence Dougal Myers +// Christopher Glantschnig +// David Broder-Rodgers +// Gael Magnan de Bornier +// Rytis Alekna +// Pavel Ivanov +// Youngrok Kim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +export type Types = 'any' | 'alternatives' | 'array' | 'boolean' | 'binary' | 'date' | 'function' | 'lazy' | 'number' | 'object' | 'string'; + +export type LanguageOptions = string | false | null | { + [key: string]: LanguageOptions; +}; + +export type LanguageRootOptions = { + root?: string; + key?: string; + messages?: { wrapArrays?: boolean; }; +} & Partial> & { [key: string]: LanguageOptions; }; + +export interface ValidationOptions { + /** + * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + */ + abortEarly?: boolean; + /** + * when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + */ + convert?: boolean; + /** + * when true, allows object to contain unknown keys which are ignored. Defaults to false. + */ + allowUnknown?: boolean; + /** + * when true, ignores unknown keys with a function value. Defaults to false. + */ + skipFunctions?: boolean; + /** + * remove unknown elements from objects and arrays. Defaults to false + * - when true, all unknown elements will be removed + * - when an object: + * - arrays - set to true to remove unknown items from arrays. + * - objects - set to true to remove unknown keys from objects + */ + stripUnknown?: boolean | { arrays?: boolean; objects?: boolean }; + /** + * overrides individual error messages. Defaults to no override ({}). + */ + language?: LanguageRootOptions; + /** + * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + */ + presence?: 'optional' | 'required' | 'forbidden'; + /** + * provides an external data set to be used in references + */ + context?: Context; + /** + * when true, do not apply default values. Defaults to false. + */ + noDefaults?: boolean; +} + +export interface RenameOptions { + /** + * if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + */ + alias?: boolean; + /** + * if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + */ + multiple?: boolean; + /** + * if true, allows renaming a key over an existing key. Defaults to false. + */ + override?: boolean; + /** + * if true, skip renaming of a key if it's undefined. Defaults to false. + */ + ignoreUndefined?: boolean; +} + +export interface EmailOptions { + /** + * Numerical threshold at which an email address is considered invalid + */ + errorLevel?: number | boolean; + /** + * Specifies a list of acceptable TLDs. + */ + tldWhitelist?: string[] | Object; + /** + * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + */ + minDomainAtoms?: number; +} + +export interface IpOptions { + /** + * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + */ + version?: string | string[]; + /** + * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + */ + cidr?: string; +} + +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions; +} + +export interface UriOptions { + /** + * Specifies one or more acceptable Schemes, should only include the scheme name. + * Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + */ + scheme?: string | RegExp | Array; +} + +export interface WhenOptions { + /** + * the required condition joi type. + */ + is: SchemaLike; + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: SchemaLike; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: SchemaLike; +} + +export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; +} + +export interface IPOptions { + version?: Array; + cidr?: string +} + +export interface JoiObject { + isJoi: boolean; +} + +export interface ValidationError extends Error, JoiObject { + details: ValidationErrorItem[]; + annotate(): string; + _object: any; +} + +export interface ValidationErrorItem { + message: string; + type: string; + path: string; + options?: ValidationOptions; + context?: Context; +} + +export interface ValidationErrorFunction { + (errors: ValidationErrorItem[]): string | ValidationErrorItem | ValidationErrorItem[] | Error; +} + +export interface ValidationResult { + error: ValidationError; + value: T; +} + +export type SchemaLike = string | number | boolean | object | null | Schema | SchemaMap; + +export interface SchemaMap { + [key: string]: SchemaLike | SchemaLike[]; +} + +export type Schema = AnySchema + | ArraySchema + | AlternativesSchema + | BinarySchema + | BooleanSchema + | DateSchema + | FunctionSchema + | NumberSchema + | ObjectSchema + | StringSchema + | LazySchema; + +export interface AnySchema extends JoiObject { + + /** + * Validates a value using the schema and options. + */ + validate(value: T): ValidationResult; + validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, callback: (err: ValidationError, value: T) => R): R; + validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + + /** + * Whitelists a value + */ + allow(...values: any[]): this; + allow(values: any[]): this; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(...values: any[]): this; + valid(values: any[]): this; + only(...values: any[]): this; + only(values: any[]): this; + equal(...values: any[]): this; + equal(values: any[]): this; + + /** + * Blacklists a value + */ + invalid(...values: any[]): this; + invalid(values: any[]): this; + disallow(...values: any[]): this; + disallow(values: any[]): this; + not(...values: any[]): this; + not(values: any[]): this; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): this; + exist(): this; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): this; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): this; + + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): this; + + /** + * Annotates the key + */ + description(desc: string): this; + + /** + * Annotates the key + */ + notes(notes: string): this; + notes(notes: string[]): this; + + /** + * Annotates the key + */ + tags(notes: string): this; + tags(notes: string[]): this; + + /** + * Attaches metadata to the key. + */ + meta(meta: object): this; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): this; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): this; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): this; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(isStrict?: boolean): this; + + /** + * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. + */ + default(value: any, description?: string): this; + default(): this; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: this): this; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): this; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): this; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: SchemaLike): this; + + /** + * Overrides the default joi error with a custom error if the rule fails where: + * @param err - can be: + * an instance of `Error` - the override error. + * a `function(errors)`, taking an array of errors as argument, where it must either: + * return a `string` - substitutes the error message with this text + * return a single ` object` or an `Array` of it, where: + * `type` - optional parameter providing the type of the error (eg. `number.min`). + * `message` - optional parameter if `template` is provided, containing the text of the error. + * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. + * `context` - optional parameter, to provide context to your error if you are using the `template`. + * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. + * + * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the + * normal joi error properties. If validation fails and another error is found before the error + * override, that error will be returned and the override will be ignored (unless the `abortEarly` + * option has been set to `false`). + */ + error?(err: Error | ValidationErrorFunction): this; + + /** + * Returns a plain object representing the schema's rules and properties + */ + describe(): Description; +} + +export interface Description { + type?: Types | string; + label?: string; + description?: string; + flags?: object; + notes?: string[]; + tags?: string[]; + meta?: any[]; + example?: any[]; + valids?: any[]; + invalids?: any[]; + unit?: string; + options?: ValidationOptions; + [key: string]: any; +} + +export interface Context { + [key: string]: any; +} + +export interface State { + key?: string; + path?: string; + parent?: any; + reference?: any; +} + +export interface BooleanSchema extends AnySchema { + + /** + * Allows for additional values to be considered valid booleans by converting them to true during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + truthy(...values: Array): this; + + /** + * Allows for additional values to be considered valid booleans by converting them to false during validation. + * Accepts a value or an array of values. String comparisons are by default case insensitive, + * see boolean.insensitive() to change this behavior. + * @param values - strings, numbers or arrays of them + */ + falsy(...values: Array): this; + + /** + * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion + * (when not in strict() mode) to be matched in a case insensitive manner. + * @param enabled + */ + insensitive(enabled?: boolean): this; +} + +export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + * It can also be a reference to another field. + */ + min(limit: number): this; + min(limit: Reference): this; + + /** + * Specifies the maximum value. + * It can also be a reference to another field. + */ + max(limit: number): this; + max(limit: Reference): this; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): this; + greater(limit: Reference): this; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): this; + less(limit: Reference): this; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): this; + + /** + * Specifies the maximum number of decimal places where: + * @param limit - the maximum number of decimal places allowed. + */ + precision(limit: number): this; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): this; + + /** + * Requires the number to be positive. + */ + positive(): this; + + /** + * Requires the number to be negative. + */ + negative(): this; +} + +export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): this; + + /** + * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + min(limit: number, encoding?: string): this; + min(limit: Reference, encoding?: string): this; + + /** + * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + max(limit: number, encoding?: string): this; + max(limit: Reference, encoding?: string): this; + + + /** + * Specifies whether the string.max() limit should be used as a truncation. + * @param enabled - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value. + */ + truncate(enabled?: boolean): this; + + /** + * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized. + * @param form - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD + */ + normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): this; + + /** + * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + length(limit: number, encoding?: string): this; + length(limit: Reference, encoding?: string): this; + + /** + * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. + */ + regex(pattern: RegExp, name?: string): this; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): this; + replace(pattern: string, replacement: string): this; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): this; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): this; + + /** + * Requires the string value to be a valid email address. + */ + email(options?: EmailOptions): this; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): this; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): this; + + /** + * Requires the string value to be a valid GUID. + */ + guid(options?: GuidOptions): this; + + /** + * Alias for `guid` -- Requires the string value to be a valid GUID + */ + uuid(options?: GuidOptions): this; + + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(): this; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): this; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): this; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): this; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): this; +} + +export interface ArraySchema extends AnySchema { + /** + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. + */ + sparse(enabled?: any): this; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): this; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(...types: SchemaLike[]): this; + items(types: SchemaLike[]): this; + + /** + * Lists the types in sequence order for the array values where: + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. + */ + ordered(...types: SchemaLike[]): this; + ordered(types: SchemaLike[]): this; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): this; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): this; + + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(comparator?: string): this; + unique(comparator?: (a: T, b: T) => boolean): this; +} + +export interface ObjectSchema extends AnySchema { + + /** + * Sets the allowed object keys. + */ + keys(schema?: SchemaMap): this; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): this; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): this; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): this; + + /** + * Specify validation rules for unknown keys matching a pattern. + */ + pattern(regex: RegExp, schema: SchemaLike): this; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. + */ + and(...peers: string[]): this; + and(peers: string[]): this; + + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(...peers: string[]): this; + nand(peers: string[]): this; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(...peers: string[]): this; + or(peers: string[]): this; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(...peers: string[]): this; + xor(peers: string[]): this; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): this; + with(key: string, peers: string[]): this; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): this; + without(key: string, peers: string[]): this; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): this; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: SchemaLike, message?: string): this; + assert(ref: Reference, schema: SchemaLike, message?: string): this; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?: boolean): this; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): this; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string[]): this; + requiredKeys(...children: string[]): this; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string[]): this; + optionalKeys(...children: string[]): this; +} + +export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): this; + + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): this; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): this; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): this; +} + +export interface DateSchema extends AnySchema { + + /** + * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + min(date: Date): this; + min(date: number): this; + min(date: string): this; + min(date: Reference): this; + + /** + * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + max(date: Date): this; + max(date: number): this; + max(date: string): this; + max(date: Reference): this; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): this; + format(format: string[]): this; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): this; + + /** + * Requires the value to be a timestamp interval from Unix Time. + * @param type - the type of timestamp (allowed values are unix or javascript [default]) + */ + timestamp(type?: 'javascript' | 'unix'): this; +} + +export interface FunctionSchema extends AnySchema { + + /** + * Specifies the arity of the function where: + * @param n - the arity expected. + */ + arity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + minArity(n: number): this; + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + maxArity(n: number): this; + + /** + * Requires the function to be a Joi reference. + */ + ref(): this; +} + +export interface AlternativesSchema extends AnySchema { + try(types: SchemaLike[]): this; + try(...types: SchemaLike[]): this; + when(ref: string, options: WhenOptions): this; + when(ref: Reference, options: WhenOptions): this; +} + +export interface LazySchema extends AnySchema { + +} + +export interface Reference extends JoiObject { + (value: any, validationOptions: ValidationOptions): any; + isContext: boolean; + key: string; + path: string; + toString(): string; +} + +export type ExtensionBoundSchema = Schema & { + /** + * Creates a joi error object. + * Used in conjunction with custom rules. + * @param type - the type of rule to create the error for. + * @param context - provide properties that will be available in the `language` templates. + * @param state - should the context passed into the `validate` function in a custom rule + * @param options - should the context passed into the `validate` function in a custom rule + */ + createError(type: string, context: Context, state: State, options: ValidationOptions): Err; +} + +export interface Rules

{ + name: string; + params?: ObjectSchema | {[key in keyof P]: SchemaLike; }; + setup?(this: ExtensionBoundSchema, params: P): Schema | void; + validate?(this: ExtensionBoundSchema, params: P, value: any, state: State, options: ValidationOptions): Err | R; + description?: string | ((params: P) => string); +} + +export interface Extension { + name: string; + base?: Schema; + language?: LanguageOptions; + coerce?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + pre?(this: ExtensionBoundSchema, value: any, state: State, options: ValidationOptions): Err | R; + describe?(this: Schema, description: Description): Description; + rules?: Rules[]; +} + +export interface Err extends JoiObject { + toString(): string; +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Current version of the joi package. + */ +export const version: string; + +/** + * Generates a schema object that matches any data type. + */ +export function any(): AnySchema; + +/** + * Generates a schema object that matches an array data type. + */ +export function array(): ArraySchema; + +/** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ +export function bool(): BooleanSchema; + +export function boolean(): BooleanSchema; + +/** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ +export function binary(): BinarySchema; + +/** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ +export function date(): DateSchema; + +/** + * Generates a schema object that matches a function type. + */ +export function func(): FunctionSchema; + +/** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ +export function number(): NumberSchema; + +/** + * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + */ +export function object(schema?: SchemaMap): ObjectSchema; + +/** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ +export function string(): StringSchema; + +/** + * Generates a type that will match one of the provided alternative schemas + */ +export function alternatives(types: SchemaLike[]): AlternativesSchema; +export function alternatives(...types: SchemaLike[]): AlternativesSchema; + +/** + * Alias for `alternatives` + */ +export function alt(types: SchemaLike[]): AlternativesSchema; +export function alt(...types: SchemaLike[]): AlternativesSchema; + +/** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ +export function lazy(cb: () => Schema): LazySchema; + +/** + * Validates a value using the given schema and options. + */ +export function validate(value: T, schema: SchemaLike): ValidationResult; +export function validate(value: T, schema: SchemaLike, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: SchemaLike, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: SchemaLike, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + +/** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ +export function compile(schema: SchemaLike): Schema; +export function compile(schema: SchemaLike): T; + +/** + * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function assert(value: any, schema: SchemaLike, message?: string | Error): void; + +/** + * Validates a value against a schema, returns valid object, and throws if validation fails where: + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ +export function attempt(value: T, schema: SchemaLike, message?: string | Error): T; + +/** + * Generates a reference to the value of the named key. + */ +export function ref(key: string, options?: ReferenceOptions): Reference; + +/** + * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages. + */ +export function isRef(ref: any): ref is Reference; + +/** + * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + */ +export function reach(schema: ObjectSchema, path: string): Schema; +export function reach(schema: ObjectSchema, path: string): T; + +/** + * Creates a new Joi instance customized with the extension(s) you provide included. + */ +export function extend(extention: Extension): any; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +// Below are undocumented APIs. use at your own risk +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +/** + * Returns a plain object representing the schema's rules and properties + */ +export function describe(schema: Schema): Description; + +/** +* Whitelists a value +*/ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values: any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values: any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values: any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values: any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any): Schema; diff --git a/types/joi/v10/joi-tests.ts b/types/joi/v10/joi-tests.ts new file mode 100644 index 0000000000..226abb3a7f --- /dev/null +++ b/types/joi/v10/joi-tests.ts @@ -0,0 +1,1016 @@ +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var x: any = null; +var value: any = null; +var num: number = 0; +var str: string = ''; +var bool: boolean = false; +var exp: RegExp = null; +var obj: object = null; +var date: Date = null; +var err: Error = null; +var func: Function = null; + +var anyArr: any[] = []; +var numArr: number[] = []; +var strArr: string[] = []; +var boolArr: boolean[] = []; +var expArr: RegExp[] = []; +var objArr: object[] = []; +var errArr: Error[] = []; +var funcArr: Function[] = []; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schema: Joi.Schema = null; +var schemaLike: Joi.SchemaLike = null; + +var anySchema: Joi.AnySchema = null; +var numSchema: Joi.NumberSchema = null; +var strSchema: Joi.StringSchema = null; +var arrSchema: Joi.ArraySchema = null; +var boolSchema: Joi.BooleanSchema = null; +var binSchema: Joi.BinarySchema = null; +var dateSchema: Joi.DateSchema = null; +var funcSchema: Joi.FunctionSchema = null; +var objSchema: Joi.ObjectSchema = null; +var altSchema: Joi.AlternativesSchema = null; + +var schemaArr: Joi.Schema[] = []; + +var ref: Joi.Reference = null; +var description: Joi.Description = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validOpts: Joi.ValidationOptions = null; + +validOpts = { abortEarly: bool }; +validOpts = { convert: bool }; +validOpts = { allowUnknown: bool }; +validOpts = { skipFunctions: bool }; +validOpts = { stripUnknown: bool }; +validOpts = { stripUnknown: { arrays: bool } }; +validOpts = { stripUnknown: { objects: bool } }; +validOpts = { stripUnknown: { arrays: bool, objects: bool } }; +validOpts = { presence: 'optional' || 'required' || 'forbidden' }; +validOpts = { context: obj }; +validOpts = { noDefaults: bool }; +validOpts = { + language: { + root: str, + key: str, + messages: { wrapArrays: bool }, + string: { base: str }, + number: { base: str }, + object: { + base: false, + children: { childRule: str } + }, + customType: { + customRule: str + } + } +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var renOpts: Joi.RenameOptions = null; + +renOpts = { alias: bool }; +renOpts = { multiple: bool }; +renOpts = { override: bool }; +renOpts = { ignoreUndefined: bool }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var emailOpts: Joi.EmailOptions = null; + +emailOpts = { errorLevel: num }; +emailOpts = { errorLevel: bool }; +emailOpts = { tldWhitelist: strArr }; +emailOpts = { tldWhitelist: obj }; +emailOpts = { minDomainAtoms: num }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var ipOpts: Joi.IpOptions = null; + +ipOpts = { version: str }; +ipOpts = { version: strArr }; +ipOpts = { cidr: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var uriOpts: Joi.UriOptions = null; + +uriOpts = { scheme: str }; +uriOpts = { scheme: exp }; +uriOpts = { scheme: strArr }; +uriOpts = { scheme: expArr }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var whenOpts: Joi.WhenOptions = null; + +whenOpts = { is: x }; +whenOpts = { is: schema, then: schema }; +whenOpts = { is: schema, otherwise: schema }; +whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var refOpts: Joi.ReferenceOptions = null; + +refOpts = { separator: str }; +refOpts = { contextPrefix: str }; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validErr: Joi.ValidationError = null; +var validErrItem: Joi.ValidationErrorItem; +var validErrFunc: Joi.ValidationErrorFunction; + +validErrItem = { + message: str, + type: str, + path: str +}; + +validErrItem = { + message: str, + type: str, + path: str, + options: validOpts, + context: obj +}; + +validErrFunc = errs => errs; +validErrFunc = errs => errs[0]; +validErrFunc = errs => 'Some error'; +validErrFunc = errs => err; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; +schemaMap = { + a: numSchema, + b: { + b1: strSchema, + b2: anySchema + } +}; +schemaMap = { + a: numSchema, + b: [ + { b1: strSchema }, + { b2: anySchema } + ], + c: arrSchema, + d: schemaLike +}; +schemaMap = { + a: 1, + b: { + b1: '1', + b2: 2 + }, + c: [ + { c1: true }, + { c2: null } + ] +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +namespace common { + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); + + anySchema = anySchema.error(err); + anySchema = anySchema.error(validErrFunc); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.ordered(anySchema); +arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema, schemaLike); +arrSchema = arrSchema.ordered(schemaMap); +arrSchema = arrSchema.ordered([schemaMap, schemaMap, schemaLike]); +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); +arrSchema = arrSchema.unique(); +arrSchema = arrSchema.unique((a, b) => a.test === b.test); +arrSchema = arrSchema.unique('customer.id'); + + +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema, schemaLike); +arrSchema = arrSchema.items([numSchema, strSchema, schemaLike]); +arrSchema = arrSchema.items(schemaMap); +arrSchema = arrSchema.items(schemaMap, schemaMap, schemaLike); +arrSchema = arrSchema.items([schemaMap, schemaMap, schemaLike]); + +// - - - - - - - - + +namespace common_copy_paste { + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +namespace common_copy_paste { + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + boolSchema = boolSchema.truthy(str); + boolSchema = boolSchema.truthy(num); + boolSchema = boolSchema.truthy(strArr); + boolSchema = boolSchema.truthy(numArr); + boolSchema = boolSchema.truthy(str, str); + boolSchema = boolSchema.truthy(strArr, str); + boolSchema = boolSchema.truthy(str, strArr); + boolSchema = boolSchema.truthy(strArr, strArr); + boolSchema = boolSchema.falsy(str); + boolSchema = boolSchema.falsy(num); + boolSchema = boolSchema.falsy(strArr); + boolSchema = boolSchema.falsy(numArr); + boolSchema = boolSchema.falsy(str, str); + boolSchema = boolSchema.falsy(strArr, str); + boolSchema = boolSchema.falsy(str, strArr); + boolSchema = boolSchema.falsy(strArr, strArr); + boolSchema = boolSchema.insensitive(bool); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.encoding(str); +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +namespace common { + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + +dateSchema = dateSchema.timestamp(); +dateSchema = dateSchema.timestamp('javascript'); +dateSchema = dateSchema.timestamp('unix'); + +namespace common { + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +funcSchema = funcSchema.arity(num); +funcSchema = funcSchema.minArity(num); +funcSchema = funcSchema.maxArity(num); +funcSchema = funcSchema.ref(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); +numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); +numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); + +namespace common { + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); +objSchema = objSchema.pattern(exp, schemaLike); + +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema); +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + +namespace common { + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); +strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); +strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); +strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); +strSchema = strSchema.guid(); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: 'uuidv4' }); +strSchema = strSchema.hex(); +strSchema = strSchema.hostname(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); +strSchema = strSchema.truncate(); +strSchema = strSchema.truncate(false); +strSchema = strSchema.normalize(); +strSchema = strSchema.normalize('NFKC'); + +namespace common { + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(); +schema = Joi.alternatives().try(schemaArr); +schema = Joi.alternatives().try(schema, schema); + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +schema = Joi.alt(); +schema = Joi.alt().try(schemaArr); +schema = Joi.alt().try(schema, schema); + +schema = Joi.alt(schemaArr); +schema = Joi.alt(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.lazy(() => schema) + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +namespace validate_tests { + { + Joi.validate(value, obj); + Joi.validate(value, schema); + Joi.validate(value, schema, validOpts); + Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; + }); + Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; + }); + // variant + Joi.validate(num, schema, validOpts, (err, value) => { + num = value; + }); + + // plain opts + Joi.validate(value, {}); + } + + { + let value = { username: 'example', password: 'example' }; + let schema = Joi.object().keys({ + username: Joi.string().max(255).required(), + password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), + }); + let returnValue: Joi.ValidationResult; + + returnValue = schema.validate(value); + value = schema.validate(value, (err, value) => value); + + returnValue = Joi.validate(value, schema); + returnValue = Joi.validate(value, obj); + value = Joi.validate(value, obj, (err, value) => value); + value = Joi.validate(value, schema, (err, value) => value); + + returnValue = Joi.validate(value, schema, validOpts); + returnValue = Joi.validate(value, obj, validOpts); + value = Joi.validate(value, obj, validOpts, (err, value) => value); + value = Joi.validate(value, schema, validOpts, (err, value) => value); + + returnValue = schema.validate(value); + returnValue = schema.validate(value, validOpts); + value = schema.validate(value, (err, value) => value); + value = schema.validate(value, validOpts, (err, value) => value); + } +} + + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); +schema = Joi.compile(schemaMap); + +Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); +Joi.assert(obj, schemaLike); + +Joi.attempt(obj, schema); +Joi.attempt(obj, schema, str); +Joi.attempt(obj, schema, err); +Joi.attempt(obj, schemaLike); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); + +Joi.isRef(ref); + +description = Joi.describe(schema); +description = schema.describe(); + +schema = Joi.reach(objSchema, ''); + +const Joi2 = Joi.extend({ name: '', base: schema }); + +const Joi3 = Joi.extend({ + base: Joi.string(), + name: 'string', + language: { + asd: 'must be exactly asd(f)', + }, + pre(value, state, options) { + return value; + }, + describe(description) { + return description; + }, + rules: [ + { + name: 'asd', + params: { + allowF: Joi.boolean().default(false), + }, + setup(params) { + const fIsAllowed = params.allowF; + }, + validate(params, value, state, options) { + if (value === 'asd' || params.allowF && value === 'asdf') { + return value; + } + return this.createError('asd', { v: value }, state, options); + }, + }, + ], +}); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/types/joi/v10/tsconfig.json b/types/joi/v10/tsconfig.json new file mode 100644 index 0000000000..1bd530aff0 --- /dev/null +++ b/types/joi/v10/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "joi": [ + "joi/v10" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "joi-tests.ts" + ] +} diff --git a/types/joigoose/index.d.ts b/types/joigoose/index.d.ts index e1d0fe9919..5852e6628e 100644 --- a/types/joigoose/index.d.ts +++ b/types/joigoose/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/yoitsro/joigoose // Definitions by: Karoline // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 import * as Mongoose from "mongoose"; import * as Joi from "joi"; diff --git a/types/jquery.noty/index.d.ts b/types/jquery.noty/index.d.ts index 0e54c7a750..ec2f9c36dd 100644 --- a/types/jquery.noty/index.d.ts +++ b/types/jquery.noty/index.d.ts @@ -2,9 +2,10 @@ // Project: http://needim.github.io/noty/ // Definitions by: Aaron King , Tim Helfensdörfer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Project by: Nedim Carter // TypeScript Version: 2.3 +// Project by: Nedim Carter + /// interface NotyOptions { diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index bac194ee78..ef3d33a09e 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -235,7 +235,6 @@ interface JQueryStatic { * * @param element The DOM element to query for the data. * @param key Name of the data stored. - * @param undefined * @see {@link https://api.jquery.com/jQuery.data/} * @since 1.2.3 */ @@ -728,7 +727,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.parseHTML/} * @since 1.8 */ - parseHTML(data: string, context_keepScripts?: Document | null | undefined | boolean): JQuery.Node[]; + parseHTML(data: string, context_keepScripts?: Document | null | boolean): JQuery.Node[]; /** * Takes a well-formed JSON string and returns the resulting JavaScript value. * @@ -3422,7 +3421,6 @@ interface JQuery extends Iterable * data(name, value) or by an HTML5 data-* attribute. * * @param key Name of the data stored. - * @param undefined * @see {@link https://api.jquery.com/data/} * @since 1.2.3 */ @@ -6774,7 +6772,7 @@ declare namespace JQuery { (failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF) | undefined | null): PromiseBase | Thenable | ARF) | null): PromiseBase; @@ -7355,7 +7353,7 @@ declare namespace JQuery { (failFilter?: ((...t: TJ[]) => PromiseBase | Thenable | ARF) | undefined | null): PromiseBase | Thenable | ARF) | null): PromiseBase; diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 32f26b1489..6cb790f408 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -7193,7 +7193,8 @@ function JQuery_Promise3() { } async function testAsync(p: JQuery.Promise3): Promise { - return await p; + const s: string = await p; + return s; } function compatibleWithPromise(): Promise { @@ -7336,7 +7337,8 @@ function JQuery_Promise2(p: JQuery.Promise2): Promise { - return await p; + const s: string = await p; + return s; } function compatibleWithPromise(): Promise { @@ -7456,7 +7458,8 @@ function JQuery_Promise(p: JQuery.Promise) { } async function testAsync(p: JQuery.Promise): Promise { - return await p; + const s: string = await p; + return s; } function compatibleWithPromise(): Promise { diff --git a/types/jquery/v1/jquery-tests.ts b/types/jquery/v1/jquery-tests.ts index 4b6fc4e0db..d00c075125 100644 --- a/types/jquery/v1/jquery-tests.ts +++ b/types/jquery/v1/jquery-tests.ts @@ -2215,8 +2215,8 @@ function test_hide() { $("p").hide("slow"); }); $("#hidr").click(function () { - $("span:last-child").hide("fast", function () { - $(this).prev().hide("fast", arguments.callee); + $("span:last-child").hide("fast", function f() { + $(this).prev().hide("fast", f); }); }); $("#showr").click(function () { @@ -3126,20 +3126,21 @@ function test_map() { }).get().join(", ")); var mappedItems = $("li").map(function (index) { var replacement:any = $("

  • ").text($(this).text()).get(0); - if (index === 0) { - - // Make the first item all caps - $(replacement).text($(replacement).text().toUpperCase()); - } else if (index === 1 || index === 3) { - - // Delete the second and fourth items - replacement = null; - } else if (index === 2) { - - // Make two of the third item and add some text - replacement = [replacement, $("
  • ").get(0)]; - $(replacement[0]).append(" - A"); - $(replacement[1]).append("Extra - B"); + switch (index) { + case 0: + // Make the first item all caps + $(replacement).text($(replacement).text().toUpperCase()); + break; + case 1: + case 3: + // Delete the second and fourth items + replacement = null; + break; + case 2: + // Make two of the third item and add some text + replacement = [replacement, $("
  • ").get(0)]; + $(replacement[0]).append(" - A"); + $(replacement[1]).append("Extra - B"); } // Replacement will be a dom element, null, diff --git a/types/jquery/v2/jquery-tests.ts b/types/jquery/v2/jquery-tests.ts index 4b6fc4e0db..d00c075125 100644 --- a/types/jquery/v2/jquery-tests.ts +++ b/types/jquery/v2/jquery-tests.ts @@ -2215,8 +2215,8 @@ function test_hide() { $("p").hide("slow"); }); $("#hidr").click(function () { - $("span:last-child").hide("fast", function () { - $(this).prev().hide("fast", arguments.callee); + $("span:last-child").hide("fast", function f() { + $(this).prev().hide("fast", f); }); }); $("#showr").click(function () { @@ -3126,20 +3126,21 @@ function test_map() { }).get().join(", ")); var mappedItems = $("li").map(function (index) { var replacement:any = $("
  • ").text($(this).text()).get(0); - if (index === 0) { - - // Make the first item all caps - $(replacement).text($(replacement).text().toUpperCase()); - } else if (index === 1 || index === 3) { - - // Delete the second and fourth items - replacement = null; - } else if (index === 2) { - - // Make two of the third item and add some text - replacement = [replacement, $("
  • ").get(0)]; - $(replacement[0]).append(" - A"); - $(replacement[1]).append("Extra - B"); + switch (index) { + case 0: + // Make the first item all caps + $(replacement).text($(replacement).text().toUpperCase()); + break; + case 1: + case 3: + // Delete the second and fourth items + replacement = null; + break; + case 2: + // Make two of the third item and add some text + replacement = [replacement, $("
  • ").get(0)]; + $(replacement[0]).append(" - A"); + $(replacement[1]).append("Extra - B"); } // Replacement will be a dom element, null, diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 8f7c0a346d..2fa264cbd9 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,96 +1,103 @@ -// Type definitions for js-yaml 3.9.1 +// Type definitions for js-yaml 3.10 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -declare namespace jsyaml { - export function safeLoad(str: string, opts?: LoadOptions): any; - export function load(str: string, opts?: LoadOptions): any; +export function safeLoad(str: string, opts?: LoadOptions): any; +export function load(str: string, opts?: LoadOptions): any; - export interface Type extends TypeConstructorOptions { } - export class Type { - constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; - } - export class Schema { - constructor(definition: SchemaDefinition); - public static create(types: Type[] | Type): Schema; - public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; - } - - export function safeLoadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; - export function loadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; - - export function safeDump(obj: any, opts?: DumpOptions): string; - export function dump(obj: any, opts?: DumpOptions): string; - - export interface LoadOptions { - // string to be used as a file path in error/warning messages. - filename?: string; - // makes the loader to throw errors instead of warnings. - strict?: boolean; - // specifies a schema to use. - schema?: any; - } - - export interface DumpOptions { - // indentation width to use (in spaces). - indent?: number; - // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - skipInvalid?: boolean; - // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - flowLevel?: number; - // Each tag may have own set of styles. - "tag" => "style" map. - styles?: Object; - // specifies a schema to use. - schema?: any; - // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) - sortKeys?: boolean | ((a: any, b: any) => number); - // set max line width. (default: 80) - lineWidth?: number; - // if true, don't convert duplicate objects into references (default: false) - noRefs?: boolean; - // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) - noCompatMode?: boolean; - // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) - condenseFlow?: boolean; - } - - export interface TypeConstructorOptions { - kind?: string; - resolve?: Function; - construct?: Function; - instanceOf?: Object; - predicate?: string; - represent?: Function; - defaultStyle?: string; - styleAliases?: Object; - } - - export interface SchemaDefinition { - implicit?: any[]; - explicit?: any[]; - include?: any[]; - } - - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var FAILSAFE_SCHEMA: any; - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var JSON_SCHEMA: any; - // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 - export var CORE_SCHEMA: any; - // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ - export var DEFAULT_SAFE_SCHEMA: any; - // all supported YAML types. - export var DEFAULT_FULL_SCHEMA: any; - export var MINIMAL_SCHEMA: any; - export var SAFE_SCHEMA: any; - - export class YAMLException extends Error { - constructor(reason?: any, mark?: any); - toString(compact?: boolean): string; - } +export class Type { + constructor(tag: string, opts?: TypeConstructorOptions); + kind: 'sequence' | 'scalar' | 'mapping' | null; + resolve(data: any): boolean; + construct(data: any): any; + instanceOf: object | null; + predicate: string | null; + represent: ((data: object) => any) | { [x: string]: (data: object) => any; } | null; + defaultStyle: string | null; + styleAliases: { [x: string]: any; }; } -export = jsyaml; -export as namespace jsyaml; +/* tslint:disable-next-line:no-unnecessary-class */ +export class Schema implements SchemaDefinition { + constructor(definition: SchemaDefinition); + static create(types: Type[] | Type): Schema; + static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; +} + +export function safeLoadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; +export function loadAll(str: string, iterator?: (doc: any) => void, opts?: LoadOptions): any; + +export function safeDump(obj: any, opts?: DumpOptions): string; +export function dump(obj: any, opts?: DumpOptions): string; + +export interface LoadOptions { + // string to be used as a file path in error/warning messages. + filename?: string; + // makes the loader to throw errors instead of warnings. + strict?: boolean; + // specifies a schema to use. + schema?: any; + // compatibility with JSON.parse behaviour. + json?: boolean; +} + +export interface DumpOptions { + // indentation width to use (in spaces). + indent?: number; + // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. + skipInvalid?: boolean; + // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere + flowLevel?: number; + // Each tag may have own set of styles. - "tag" => "style" map. + styles?: { [x: string]: any; }; + // specifies a schema to use. + schema?: any; + // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) + sortKeys?: boolean | ((a: any, b: any) => number); + // set max line width. (default: 80) + lineWidth?: number; + // if true, don't convert duplicate objects into references (default: false) + noRefs?: boolean; + // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) + noCompatMode?: boolean; + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. + // Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + condenseFlow?: boolean; +} + +export interface TypeConstructorOptions { + kind?: 'sequence' | 'scalar' | 'mapping'; + resolve?: (data: any) => boolean; + construct?: (data: any) => any; + instanceOf?: object; + predicate?: string; + represent?: ((data: object) => any) | { [x: string]: (data: object) => any }; + defaultStyle?: string; + styleAliases?: { [x: string]: any; }; +} + +export interface SchemaDefinition { + implicit?: any[]; + explicit?: Type[]; + include?: Schema[]; +} + +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let FAILSAFE_SCHEMA: Schema; +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let JSON_SCHEMA: Schema; +// same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 +export let CORE_SCHEMA: Schema; +// all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ +export let DEFAULT_SAFE_SCHEMA: Schema; +// all supported YAML types. +export let DEFAULT_FULL_SCHEMA: Schema; +export let MINIMAL_SCHEMA: Schema; +export let SAFE_SCHEMA: Schema; + +export class YAMLException extends Error { + constructor(reason?: any, mark?: any); + toString(compact?: boolean): string; +} diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index aff53acd3c..3d5ecc17bf 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -1,45 +1,55 @@ - - import yaml = require('js-yaml'); import LoadOptions = yaml.LoadOptions; import DumpOptions = yaml.DumpOptions; import TypeConstructorOptions = yaml.TypeConstructorOptions; import SchemaDefinition = yaml.SchemaDefinition; -var bool: boolean; -var num: number; -var str: string; -var obj: Object; -var value: any; -var array: any[]; -var fn: Function; -var schemaDefinition: SchemaDefinition = { +const bool = true; +const num = 0; +const str = ""; +const obj: object = {}; +const map: { [x: string]: any; } = {}; +const array: any[] = []; +const fn: (...args: any[]) => any = () => {}; +const type = new yaml.Type(str); + +const schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, include: array }; -var typeConstructorOptions: TypeConstructorOptions = { - kind: str, +const typeConstructorOptions: TypeConstructorOptions = { + kind: "scalar", resolve: fn, construct: fn, instanceOf: obj, predicate: str, represent: fn, defaultStyle: str, - styleAliases: obj + styleAliases: map }; -var loadOpts: LoadOptions; -var dumpOpts: DumpOptions; +const schema: yaml.Schema = new yaml.Schema(schemaDefinition); + +let value: any; +let loadOpts: LoadOptions; +let dumpOpts: DumpOptions; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +// $ExpectType Schema yaml.FAILSAFE_SCHEMA; +// $ExpectType Schema yaml.JSON_SCHEMA; +// $ExpectType Schema yaml.CORE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_SAFE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_FULL_SCHEMA; +// $ExpectType Schema yaml.MINIMAL_SCHEMA; +// $ExpectType Schema yaml.SAFE_SCHEMA; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -53,6 +63,9 @@ loadOpts = { loadOpts = { schema: bool }; +loadOpts = { + json: bool +}; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -74,42 +87,87 @@ dumpOpts = { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoad(str); -value = yaml.safeLoad(str, loadOpts); +// $ExpectType Type +new yaml.Type(str, typeConstructorOptions); -value = yaml.load(str); -value = yaml.load(str, loadOpts); +// $ExpectType "sequence" | "scalar" | "mapping" | null +type.kind; +// $ExpectType (data: any) => boolean +type.resolve; +// $ExpectType (data: any) => any +type.construct; +// $ExpectType object | null +type.instanceOf; +// $ExpectType string | null +type.predicate; +// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } | null +type.represent; +// $ExpectType string | null +type.defaultStyle; +// $ExpectType { [x: string]: any; } +type.styleAliases; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoadAll(str, (doc) => { - value = doc; -}); -value = yaml.safeLoadAll(str, (doc) => { - value = doc; -}, loadOpts); +// $ExpectType any +yaml.safeLoad(str); +// $ExpectType any +yaml.safeLoad(str, loadOpts); -value = yaml.loadAll(str, (doc) => { - value = doc; -}); -value = yaml.loadAll(str, (doc) => { - value = doc; -}, loadOpts); +// $ExpectType any +yaml.load(str); +// $ExpectType any +yaml.load(str, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeDump(str); -value = yaml.safeDump(str, dumpOpts); +// $ExpectType any +yaml.safeLoadAll(str); +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { + value = doc; +}); +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { + value = doc; +}, loadOpts); +value = yaml.safeLoadAll(str, undefined, loadOpts); -value = yaml.dump(str); -value = yaml.dump(str, dumpOpts); +// $ExpectType any +value = yaml.loadAll(str); +// $ExpectType any +yaml.loadAll(str, (doc) => { + value = doc; +}); +// $ExpectType any +yaml.loadAll(str, (doc) => { + value = doc; +}, loadOpts); +value = yaml.loadAll(str, undefined, loadOpts); -value = new yaml.YAMLException(); -value = new yaml.Type(str, typeConstructorOptions); -value = new yaml.Schema(schemaDefinition); -value = yaml.Schema.create([new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Type(str)); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), [new yaml.Type(str)]); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], [new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), new yaml.Type(str)); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], new yaml.Type(str)); +// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + +// $ExpectType string +yaml.safeDump(str); +// $ExpectType string +yaml.safeDump(str, dumpOpts); + +// $ExpectType string +yaml.dump(str); +// $ExpectType string +yaml.dump(str, dumpOpts); + +new yaml.YAMLException(); + +// $ExpectType Schema +yaml.Schema.create([type]); +// $ExpectType Schema +yaml.Schema.create(type); +// $ExpectType Schema +yaml.Schema.create(schema, [type]); +// $ExpectType Schema +yaml.Schema.create([schema], [type]); +// $ExpectType Schema +yaml.Schema.create(schema, type); +// $ExpectType Schema +yaml.Schema.create([schema], type); diff --git a/types/js-yaml/tsconfig.json b/types/js-yaml/tsconfig.json index b1e787d1b3..c36931fa61 100644 --- a/types/js-yaml/tsconfig.json +++ b/types/js-yaml/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "js-yaml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/js.spec/index.d.ts b/types/js.spec/index.d.ts index 735de40976..764bfa845e 100644 --- a/types/js.spec/index.d.ts +++ b/types/js.spec/index.d.ts @@ -71,7 +71,7 @@ export interface Problem { * @param value the value to test * @returns true if valid */ -export function valid(spec: Spec, value: any): boolean; +export function valid(spec: spec.SpecInput, value: any): boolean; /** * Returns the conformed value to this spec. @@ -79,7 +79,7 @@ export function valid(spec: Spec, value: any): boolean; * @param value the value to test * @returns if the value does not conform to the spec, or the conformed value if it does. */ -export function conform(spec: Spec, value: any): any; +export function conform(spec: spec.SpecInput, value: any): any; /** * Like explain(), but returns Problems array. @@ -87,28 +87,28 @@ export function conform(spec: Spec, value: any): any; * @param value the value to test * @returns list of problems or null if none */ -export function explainData(spec: Spec, value: any): Problem[]; +export function explainData(spec: spec.SpecInput, value: any): Problem[]; /** * Prints, to the console, reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explain(spec: Spec, value: any): void; +export function explain(spec: spec.SpecInput, value: any): void; /** * Returns a multiline string with reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explainStr(spec: Spec, value: any): string; +export function explainStr(spec: spec.SpecInput, value: any): string; /** * Tests if a value conforms to a spec, and if not, throws an Error. * @param spec the spec to test with * @param value the value to test */ -export function assert(spec: Spec, value: any): void; +export function assert(spec: spec.SpecInput, value: any): void; export namespace symbol { /** diff --git a/types/js.spec/js.spec-tests.ts b/types/js.spec/js.spec-tests.ts index 8bb9611e87..e1d7703f76 100644 --- a/types/js.spec/js.spec-tests.ts +++ b/types/js.spec/js.spec-tests.ts @@ -7,20 +7,28 @@ const name: string = spec.name; const options: object = spec.options; const isValid: boolean = S.valid(S.spec.boolean, true); +S.valid((value) => true, "a value"); const result = S.conform(S.spec.map("dancing", {field: S.spec.string}), "not a map"); +S.conform((value) => true, "a value"); const problems: S.Problem[] = S.explainData(S.spec.int, "not a number"); +S.explainData((value) => true, "a value"); const {path, via, value, predicate}: {path: string[], via: string[], value: any, predicate: S.Predicate} = problems[0]; const problemStr: string = S.explainStr(S.spec.even, 3); +S.explainStr((value) => true, "a value"); // $ExpectType void S.explain(S.spec.positive, true); +// $ExpectType void +S.explain((value) => true, "a value"); // $ExpectType void S.assert(S.spec.string, "things"); +// $ExpectType void +S.assert((value) => true, "a value"); const symbols: symbol[] = [S.symbol.count, S.symbol.invalid, S.symbol.maxCount, S.symbol.minCount, S.symbol.optional]; diff --git a/types/jsbn/index.d.ts b/types/jsbn/index.d.ts index cde50e0df2..b6e5f52ab6 100644 --- a/types/jsbn/index.d.ts +++ b/types/jsbn/index.d.ts @@ -1,250 +1,249 @@ -// Type definitions for jsbn v1.2 +// Type definitions for jsbn v1.2.29 // Project: http://www-cs-students.stanford.edu/%7Etjw/jsbn/ -// Definitions by: Eugene Chernyshov +// Definitions by: Eugene Chernyshov , Al Tabayoyon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace jsbn { - - interface RandomGenerator { - nextBytes(bytes: number[]): void; - } - - export class BigInteger { - constructor(a: number, c: RandomGenerator); - constructor(a: number, b: number, c: RandomGenerator); - constructor(a: string, b?: number); - constructor(a: number[], b?: number); - constructor(a: BigInteger); - - s: number; - t: number; - data: number[]; // forge specific - - DB: number; - DM: number; - DV: number; - - FV: number; - F1: number; - F2: number; - - // am: Compute w_j += (x*this_i), propagate carries, - am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number; - - // (protected) copy this to r - copyTo(r: BigInteger): void; - - // (protected) set from integer value x, -DV <= x < DV - fromInt(x: number): void; - - // (protected) set from string and radix - fromString(x: string, b: number): void; - - // (protected) clamp off excess high words - clamp(): void; - - // (public) return string representation in given radix - toString(b?: number): string; - - // (public) -this - negate(): BigInteger; - - // (public) |this| - abs(): BigInteger; - - // (public) return + if this > a, - if this < a, 0 if equal - compareTo(a: BigInteger): number; - - // (public) return the number of bits in "this" - bitLength(): number; - - // (protected) r = this << n*DB - dlShiftTo(n: number, r: BigInteger): void; - - // (protected) r = this >> n*DB - drShiftTo(n: number, r: BigInteger): void; - - // (protected) r = this << n - lShiftTo(n: number, r: BigInteger): void; - - // (protected) r = this >> n - rShiftTo(n: number, r: BigInteger): void; - - // (protected) r = this - a - subTo(a: BigInteger, r: BigInteger): void; - - // (protected) r = this * a, r != this,a (HAC 14.12) - multiplyTo(a: BigInteger, r: BigInteger): void; - - // (protected) r = this^2, r != this (HAC 14.16) - squareTo(r: BigInteger): void; - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void; - - // (public) this mod a - mod(a: BigInteger): BigInteger; - - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - invDigit(): number; - - // (protected) true iff this is even - isEven(): boolean; - - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - exp(e: number, z: Reduction): BigInteger; - - // (public) this^e % m, 0 <= e < 2^32 - modPowInt(e: number, m: BigInteger): BigInteger; - - // (public) - clone(): BigInteger; - - // (public) return value as integer - intValue(): number; - - // (public) return value as byte - byteValue(): number; - - // (public) return value as short (assumes DB>=16) - shortValue(): number; - - // (protected) return x s.t. r^x < DV - chunkSize(r: number): number; - - // (public) 0 if this == 0, 1 if this > 0 - signum(): number; - - // (protected) convert to radix string - toRadix(b: number): string; - - // (protected) convert from radix string - fromRadix(s: string, b: number): void; - - // (protected) alternate constructor - fromNumber(a: number, b?: number, c?: number): void; - - // (public) convert to bigendian byte array - toByteArray(): number[]; - - equals(a: BigInteger): boolean; - - min(a: BigInteger): BigInteger; - - max(a: BigInteger): BigInteger; - - // (protected) r = this op a (bitwise) - bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void; - - // (public) this & a - and(a: BigInteger): BigInteger; - - // (public) this | a - or(a: BigInteger): BigInteger; - - // (public) this ^ a - xor(a: BigInteger): BigInteger; - - // (public) this & ~a - andNot(a: BigInteger): BigInteger; - - // (public) ~this - not(): BigInteger; - - // (public) this << n - shiftLeft(n: number): BigInteger; - - // (public) this >> n - shiftRight(n: number): BigInteger; - - // (public) returns index of lowest 1-bit (or -1 if none) - getLowestSetBit(): number; - - // (public) return number of set bits - bitCount(): number; - - // (public) true iff nth bit is set - testBit(n: number): boolean; - - // (protected) this op (1< number): BigInteger; - - // (protected) this op (1<= 0, 1 < n < DV - dMultiply(n: number): void; - - // (protected) this += n << w words, this >= 0 - dAddOffset(n: number, w: number): void; - - // (public) this^e - pow(e: number): BigInteger; - - // (protected) r = lower n words of "this * a", a.t <= n - multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void; - - // (protected) r = "this * a" without lower n words, n > 0 - multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void; - - // (public) this^e % m (HAC 14.85) - modPow(e: BigInteger, m: BigInteger): BigInteger; - - // (public) gcd(this,a) (HAC 14.54) - gcd(a: BigInteger): BigInteger; - - // (protected) this % n, n < 2^26 - modInt(n: number): number; - - // (public) 1/this % m (HAC 14.61) - modInverse(m: BigInteger): BigInteger; - - // (public) test primality with certainty >= 1-.5^t - isProbablePrime(t: number): boolean; - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - millerRabin(t: number): boolean; - - static ZERO: BigInteger; - static ONE: BigInteger; - } - - interface Reduction { - convert(x: BigInteger): BigInteger; - revert(x: BigInteger): BigInteger; - reduce(x: BigInteger): void; - mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void; - sqrTo(x: BigInteger, r: BigInteger): void; - } +export interface RandomGenerator { + nextBytes(bytes: number[]): void; } + +export class BigInteger { + constructor(a: number, c: RandomGenerator); + constructor(a: number, b: number, c: RandomGenerator); + constructor(a: string, b?: number); + constructor(a: number[], b?: number); + constructor(a: BigInteger); + + s: number; + t: number; + data: number[]; // forge specific + + DB: number; + DM: number; + DV: number; + + FV: number; + F1: number; + F2: number; + + // am: Compute w_j += (x*this_i), propagate carries, + am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number; + + // (protected) copy this to r + copyTo(r: BigInteger): void; + + // (protected) set from integer value x, -DV <= x < DV + fromInt(x: number): void; + + // (protected) set from string and radix + fromString(x: string, b: number): void; + + // (protected) clamp off excess high words + clamp(): void; + + // (public) return string representation in given radix + toString(b?: number): string; + + // (public) -this + negate(): BigInteger; + + // (public) |this| + abs(): BigInteger; + + // (public) return + if this > a, - if this < a, 0 if equal + compareTo(a: BigInteger): number; + + // (public) return the number of bits in "this" + bitLength(): number; + + // (protected) r = this << n*DB + dlShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n*DB + drShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this << n + lShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this >> n + rShiftTo(n: number, r: BigInteger): void; + + // (protected) r = this - a + subTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this * a, r != this,a (HAC 14.12) + multiplyTo(a: BigInteger, r: BigInteger): void; + + // (protected) r = this^2, r != this (HAC 14.16) + squareTo(r: BigInteger): void; + + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void; + + // (public) this mod a + mod(a: BigInteger): BigInteger; + + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + invDigit(): number; + + // (protected) true iff this is even + isEven(): boolean; + + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + exp(e: number, z: Reduction): BigInteger; + + // (public) this^e % m, 0 <= e < 2^32 + modPowInt(e: number, m: BigInteger): BigInteger; + + // (public) + clone(): BigInteger; + + // (public) return value as integer + intValue(): number; + + // (public) return value as byte + byteValue(): number; + + // (public) return value as short (assumes DB>=16) + shortValue(): number; + + // (protected) return x s.t. r^x < DV + chunkSize(r: number): number; + + // (public) 0 if this == 0, 1 if this > 0 + signum(): number; + + // (protected) convert to radix string + toRadix(b: number): string; + + // (protected) convert from radix string + fromRadix(s: string, b: number): void; + + // (protected) alternate constructor + fromNumber(a: number, b?: number, c?: number): void; + + // (public) convert to bigendian byte array + toByteArray(): number[]; + + equals(a: BigInteger): boolean; + + min(a: BigInteger): BigInteger; + + max(a: BigInteger): BigInteger; + + // (protected) r = this op a (bitwise) + bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void; + + // (public) this & a + and(a: BigInteger): BigInteger; + + // (public) this | a + or(a: BigInteger): BigInteger; + + // (public) this ^ a + xor(a: BigInteger): BigInteger; + + // (public) this & ~a + andNot(a: BigInteger): BigInteger; + + // (public) ~this + not(): BigInteger; + + // (public) this << n + shiftLeft(n: number): BigInteger; + + // (public) this >> n + shiftRight(n: number): BigInteger; + + // (public) returns index of lowest 1-bit (or -1 if none) + getLowestSetBit(): number; + + // (public) return number of set bits + bitCount(): number; + + // (public) true iff nth bit is set + testBit(n: number): boolean; + + // (protected) this op (1< number): BigInteger; + + // (protected) this op (1<= 0, 1 < n < DV + dMultiply(n: number): void; + + // (protected) this += n << w words, this >= 0 + dAddOffset(n: number, w: number): void; + + // (public) this^e + pow(e: number): BigInteger; + + // (protected) r = lower n words of "this * a", a.t <= n + multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void; + + // (protected) r = "this * a" without lower n words, n > 0 + multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void; + + // (public) this^e % m (HAC 14.85) + modPow(e: BigInteger, m: BigInteger): BigInteger; + + // (public) gcd(this,a) (HAC 14.54) + gcd(a: BigInteger): BigInteger; + + // (protected) this % n, n < 2^26 + modInt(n: number): number; + + // (public) 1/this % m (HAC 14.61) + modInverse(m: BigInteger): BigInteger; + + // (public) test primality with certainty >= 1-.5^t + isProbablePrime(t: number): boolean; + + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + millerRabin(t: number): boolean; + + static ZERO: BigInteger; + static ONE: BigInteger; +} + +export interface Reduction { + convert(x: BigInteger): BigInteger; + revert(x: BigInteger): BigInteger; + reduce(x: BigInteger): void; + mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void; + sqrTo(x: BigInteger, r: BigInteger): void; +} + +export as namespace jsbn; diff --git a/types/jsbn/jsbn-tests.ts b/types/jsbn/jsbn-tests.ts index 76088a32b6..eb5959173f 100644 --- a/types/jsbn/jsbn-tests.ts +++ b/types/jsbn/jsbn-tests.ts @@ -1,16 +1,15 @@ - -var BigInteger = jsbn.BigInteger; +import {BigInteger} from 'jsbn'; // constructor tests var x = new BigInteger("AABB", 16); x = new BigInteger("75643564363473453456342378564387956906736546456235345"); // method tests -var isBigInteger: jsbn.BigInteger; +var isBigInteger: BigInteger; var isNumber: number; var isBoolean: boolean; var isString: string; -var isDivmod: jsbn.BigInteger[]; +var isDivmod: BigInteger[]; var isByteArray: number[]; x.copyTo(x); diff --git a/types/jschannel/index.d.ts b/types/jschannel/index.d.ts new file mode 100644 index 0000000000..42145531ea --- /dev/null +++ b/types/jschannel/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for jschannel 1.0 +// Project: https://github.com/yochannah/jschannel +// Definitions by: Yitzchok Gottlieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export as namespace Channel; + +export function build(config: ChannelConfiguration): MessagingChannel; + +export interface MessagingChannel { + unbind: (method: string, doNotPublish?: boolean) => boolean; + bind: (method: string, callback?: (transaction: MessageTransaction, params: any) => void, doNotPublish?: boolean) => MessagingChannel; + call: (message: Message) => void; + notify: (message: Message) => void; + destroy: () => void; +} + +export interface Message { + method: string; + success?: (result: any) => void; + params?: any; + timeout?: number; + error?: (error: any, message: string) => void; +} + +export interface ChannelConfiguration { + window: any; + origin: string; + scope: string; + debugOutput?: boolean; + postMessageObserver?: (origin: string, message: Message) => void; + gotMessageObserver?: (origin: string, message: Message) => void; + onReady?: (channel: MessagingChannel) => void; + reconnect?: boolean; + publish?: boolean; + remote?: string | ReadonlyArray; +} + +export interface MessageTransaction { + delayReturn: (delay: boolean) => boolean; + complete: (result: any) => void; + error: (error: any, message: string) => void; + invoke: (callbackName: string, params: any) => void; + completed: () => boolean; +} diff --git a/types/jschannel/jschannel-tests.ts b/types/jschannel/jschannel-tests.ts new file mode 100644 index 0000000000..eabd150bf2 --- /dev/null +++ b/types/jschannel/jschannel-tests.ts @@ -0,0 +1,3 @@ +import { build } from 'jschannel'; + +build({ window: null, origin: "*", scope: "testScope"}); diff --git a/types/jschannel/tsconfig.json b/types/jschannel/tsconfig.json new file mode 100644 index 0000000000..83727a281c --- /dev/null +++ b/types/jschannel/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jschannel-tests.ts" + ] +} diff --git a/types/jschannel/tslint.json b/types/jschannel/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jschannel/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index ca2a1aad41..cfb54fa25f 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -103,7 +103,153 @@ export type ConstructorOptions = Options & { contentType?: string; }; -export interface DOMWindow extends Window { eval(script: string): void; } +export interface DOMWindow extends Window { + eval(script: string): void; + + /* node_modules/jsdom/living/index.js */ + DOMException: typeof DOMException; + Attr: typeof Attr; + Node: typeof Node; + Element: typeof Element; + DocumentFragment: typeof DocumentFragment; + Document: typeof Document; + HTMLDocument: typeof HTMLDocument; + XMLDocument: typeof XMLDocument; + CharacterData: typeof CharacterData; + Text: typeof Text; + CDATASection: typeof CDATASection; + ProcessingInstruction: typeof ProcessingInstruction; + Comment: typeof Comment; + DocumentType: typeof DocumentType; + DOMImplementation: typeof DOMImplementation; + NodeList: typeof NodeList; + HTMLCollection: typeof HTMLCollection; + HTMLOptionsCollection: typeof HTMLOptionsCollection; + DOMStringMap: typeof DOMStringMap; + DOMTokenList: typeof DOMTokenList; + Event: typeof Event; + CustomEvent: typeof CustomEvent; + MessageEvent: typeof MessageEvent; + ErrorEvent: typeof ErrorEvent; + HashChangeEvent: typeof HashChangeEvent; + FocusEvent: typeof FocusEvent; + PopStateEvent: typeof PopStateEvent; + UIEvent: typeof UIEvent; + MouseEvent: typeof MouseEvent; + KeyboardEvent: typeof KeyboardEvent; + TouchEvent: typeof TouchEvent; + ProgressEvent: typeof ProgressEvent; + CompositionEvent: typeof CompositionEvent; + WheelEvent: typeof WheelEvent; + EventTarget: typeof EventTarget; + Location: typeof Location; + History: typeof History; + Blob: typeof Blob; + File: typeof File; + FileList: typeof FileList; + DOMParser: typeof DOMParser; + FormData: typeof FormData; + XMLHttpRequestEventTarget: XMLHttpRequestEventTarget; + XMLHttpRequestUpload: typeof XMLHttpRequestUpload; + NodeIterator: typeof NodeIterator; + TreeWalker: typeof TreeWalker; + NamedNodeMap: typeof NamedNodeMap; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + + /* node_modules/jsdom/living/register-elements.js */ + HTMLElement: typeof HTMLElement; + HTMLAnchorElement: typeof HTMLAnchorElement; + HTMLAppletElement: typeof HTMLAppletElement; + HTMLAreaElement: typeof HTMLAreaElement; + HTMLAudioElement: typeof HTMLAudioElement; + HTMLBaseElement: typeof HTMLBaseElement; + HTMLBodyElement: typeof HTMLBodyElement; + HTMLBRElement: typeof HTMLBRElement; + HTMLButtonElement: typeof HTMLButtonElement; + HTMLCanvasElement: typeof HTMLCanvasElement; + HTMLDataElement: typeof HTMLDataElement; + HTMLDataListElement: typeof HTMLDataListElement; + // HTMLDetailsElement: typeof HTMLDetailsElement; + // HTMLDialogElement: typeof HTMLDialogElement; + HTMLDirectoryElement: typeof HTMLDirectoryElement; + HTMLDivElement: typeof HTMLDivElement; + HTMLDListElement: typeof HTMLDListElement; + HTMLEmbedElement: typeof HTMLEmbedElement; + HTMLFieldSetElement: typeof HTMLFieldSetElement; + HTMLFontElement: typeof HTMLFontElement; + HTMLFormElement: typeof HTMLFormElement; + HTMLFrameElement: typeof HTMLFrameElement; + HTMLFrameSetElement: typeof HTMLFrameSetElement; + HTMLHeadingElement: typeof HTMLHeadingElement; + HTMLHeadElement: typeof HTMLHeadElement; + HTMLHRElement: typeof HTMLHRElement; + HTMLHtmlElement: typeof HTMLHtmlElement; + HTMLIFrameElement: typeof HTMLIFrameElement; + HTMLImageElement: typeof HTMLImageElement; + HTMLInputElement: typeof HTMLInputElement; + HTMLLabelElement: typeof HTMLLabelElement; + HTMLLegendElement: typeof HTMLLegendElement; + HTMLLIElement: typeof HTMLLIElement; + HTMLLinkElement: typeof HTMLLinkElement; + HTMLMapElement: typeof HTMLMapElement; + HTMLMarqueeElement: typeof HTMLMarqueeElement; + HTMLMediaElement: typeof HTMLMediaElement; + HTMLMenuElement: typeof HTMLMenuElement; + HTMLMetaElement: typeof HTMLMetaElement; + HTMLMeterElement: typeof HTMLMeterElement; + HTMLModElement: typeof HTMLModElement; + HTMLObjectElement: typeof HTMLObjectElement; + HTMLOListElement: typeof HTMLOListElement; + HTMLOptGroupElement: typeof HTMLOptGroupElement; + HTMLOptionElement: typeof HTMLOptionElement; + HTMLOutputElement: typeof HTMLOutputElement; + HTMLParagraphElement: typeof HTMLParagraphElement; + HTMLParamElement: typeof HTMLParamElement; + HTMLPictureElement: typeof HTMLPictureElement; + HTMLPreElement: typeof HTMLPreElement; + HTMLProgressElement: typeof HTMLProgressElement; + HTMLQuoteElement: typeof HTMLQuoteElement; + HTMLScriptElement: typeof HTMLScriptElement; + HTMLSelectElement: typeof HTMLSelectElement; + HTMLSourceElement: typeof HTMLSourceElement; + HTMLSpanElement: typeof HTMLSpanElement; + HTMLStyleElement: typeof HTMLStyleElement; + HTMLTableCaptionElement: typeof HTMLTableCaptionElement; + HTMLTableCellElement: typeof HTMLTableCellElement; + HTMLTableColElement: typeof HTMLTableColElement; + HTMLTableElement: typeof HTMLTableElement; + HTMLTimeElement: typeof HTMLTimeElement; + HTMLTitleElement: typeof HTMLTitleElement; + HTMLTableRowElement: typeof HTMLTableRowElement; + HTMLTableSectionElement: typeof HTMLTableSectionElement; + HTMLTemplateElement: typeof HTMLTemplateElement; + HTMLTextAreaElement: typeof HTMLTextAreaElement; + HTMLTrackElement: typeof HTMLTrackElement; + HTMLUListElement: typeof HTMLUListElement; + HTMLUnknownElement: typeof HTMLUnknownElement; + HTMLVideoElement: typeof HTMLVideoElement; + + /* node_modules/jsdom/level2/style.js */ + StyleSheet: typeof StyleSheet; + MediaList: typeof MediaList; + CSSStyleSheet: typeof CSSStyleSheet; + CSSRule: typeof CSSRule; + CSSStyleRule: typeof CSSStyleRule; + CSSMediaRule: typeof CSSMediaRule; + CSSImportRule: typeof CSSImportRule; + CSSStyleDeclaration: typeof CSSStyleDeclaration; + StyleSheetList: typeof StyleSheetList; + + /* node_modules/jsdom/level3/xpath.js */ + // XPathException: typeof XPathException; + XPathExpression: typeof XPathExpression; + XPathResult: typeof XPathResult; + XPathEvaluator: typeof XPathEvaluator; + + /* node_modules/jsdom/living/node-filter.js */ + NodeFilter: typeof NodeFilter; +} export type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index c7d39c9499..73a848b79f 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dolan Miu // Kamil Ejsymont // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 import * as fs from 'fs'; import * as stream from 'stream'; diff --git a/types/json-query/index.d.ts b/types/json-query/index.d.ts new file mode 100644 index 0000000000..929ab738ae --- /dev/null +++ b/types/json-query/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for json-query 2.2 +// Project: http://github.com/mmckegg/json-query#readme +// Definitions by: Matt Traynham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = JsonQuery; + +declare function JsonQuery( + selector: JsonQuery.Selector | JsonQuery.SelectorWithQueryParams, + options: JsonQuery.Options +): JsonQuery.Result; + +declare namespace JsonQuery { + type Selector = string; + + type QueryParam = any; + // No way to support [Selector, ...QueryParam[]]? + // 10 params should be more than enough, hopefully. + type SelectorWithQueryParams = + [Selector, QueryParam] + | [Selector, QueryParam] + | [Selector, QueryParam] + | [Selector, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam] + | [Selector, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam, QueryParam]; + + type Context = any; + + type Filter = (input: Context, ...args: any[]) => Context; + interface Locals { + [filterName: string]: Filter; + } + + interface Options { + data?: Context; + rootContext?: Context; + source?: Context; + context?: Context; + parent?: Context; + locals?: Locals; + globals?: boolean; + force?: boolean; + allowRegexp?: boolean; + } + + interface Result { + value: any; + key: string; + references: any[]; + parents: string[]; + } +} diff --git a/types/json-query/json-query-tests.ts b/types/json-query/json-query-tests.ts new file mode 100644 index 0000000000..5da1ca9e78 --- /dev/null +++ b/types/json-query/json-query-tests.ts @@ -0,0 +1,123 @@ +import jsonQuery = require('json-query'); + +// API +let data: jsonQuery.Context = { + people: [ + {name: 'Matt', country: 'NZ'}, + {name: 'Pete', country: 'AU'}, + {name: 'Mikey', country: 'NZ'} + ] +}; +jsonQuery('people[country=NZ].name', {data}); // => {value: 'Matt', parents: [...], key: 0} ... etc + +// Deep Queries +data = { + grouped_people: { + friends: [ + {name: 'Steve', country: 'NZ'}, + {name: 'Jane', country: 'US'}, + {name: 'Mike', country: 'AU'}, + {name: 'Mary', country: 'NZ'} + ], + enemies: [ + {name: 'Evil Steve', country: 'AU'}, + {name: 'Betty', country: 'NZ'} + ] + } +}; +const result: any = jsonQuery('grouped_people[**][*country=NZ]', {data}).value; + +// Inner Queries +data = { + page: { + id: 'page_1', + title: 'Test' + }, + comments_lookup: { + page_1: [ + {id: 'comment_1', parent_id: 'page_1', content: "I am a comment"} + ] + } +}; +jsonQuery('comments_lookup[{page.id}]', {data}); + +// Local functions (helpers) +const locals: jsonQuery.Locals = { + greetingName: (input: jsonQuery.Context) => { + if (input.known_as) { + return input.known_as; + } else { + return input.name; + } + }, + and: (inputA: jsonQuery.Context, inputB: boolean) => { + return inputA && inputB; + }, + text: (input: jsonQuery.Context, text: string) => { + return text; + }, + then: (input: jsonQuery.Context, thenValue: string, elseValue: string) => { + if (input) { + return thenValue; + } else { + return elseValue; + } + } +}; +data = { + is_fullscreen: true, + is_playing: false, + user: { + name: "Matthew McKegg", + known_as: "Matt" + } +}; +jsonQuery('user:greetingName', {data, locals}).value; // => "Matt" +jsonQuery(['is_fullscreen:and({is_playing}):then(?, ?)', "Playing big!", "Not so much"], {data, locals}).value; // => "Not so much" +jsonQuery(':text(This displays text cos we made it so)', {locals}).value; // => "This displays text cos we made it so" +jsonQuery('people:select(name, country)', { + data, + locals: { + select: (input: jsonQuery.Context, ...keys: string[]) => { + if (Array.isArray(input)) { + return input.map((item: any) => { + return Object.keys(item).reduce((result: {[p: string]: any}, key: string) => { + if (~keys.indexOf(key)) { + result[key] = item[key]; + } + return result; + }, {}); + }); + } + } + } +}); +jsonQuery('people[*:recentlyUpdated]', { + data, + locals: { + recentlyUpdated: (item: {updatedAt: number}) => { + return item.updatedAt < Date.now() - (30 * 24 * 60 * 60 * 1000); + } + } +}); + +// Context +data = { + styles: { + bold: 'font-weight:strong', + red: 'color: red' + }, + paragraphs: [ + {content: "I am a red paragraph", style: 'red'}, + {content: "I am a bold paragraph", style: 'bold'}, + ], +}; +let pageHtml = ''; +data.paragraphs.forEach((paragraph: {content: string, style: string}) => { + const style = jsonQuery('styles[{.style}]', {data, source: paragraph}).value; + const content = jsonQuery('.content', {data, source: paragraph}).value; // pretty pointless :) + pageHtml += `

    ${content}

    `; +}); + +// Query Params +jsonQuery(['people[country=?]', 'NZ'], {data}); diff --git a/types/json-query/tsconfig.json b/types/json-query/tsconfig.json new file mode 100644 index 0000000000..9a317f4d83 --- /dev/null +++ b/types/json-query/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "json-query-tests.ts" + ] +} \ No newline at end of file diff --git a/types/json-query/tslint.json b/types/json-query/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-query/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsplumb/index.d.ts b/types/jsplumb/index.d.ts deleted file mode 100644 index 7e195888c1..0000000000 --- a/types/jsplumb/index.d.ts +++ /dev/null @@ -1,132 +0,0 @@ -// Type definitions for jsPlumb jQuery adapter 1.3 -// Project: http://jsplumb.org -// Definitions by: Steve Shearn -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -declare var jsPlumb: jsPlumbInstance; - -interface jsPlumbInstance { - setRenderMode(renderMode: string): string; - bind(event: string, callback: (e: any) => void ): void; - unbind(event?: string): void; - ready(callback: () => void): void; - importDefaults(defaults: Defaults): void; - Defaults: Defaults; - restoreDefaults(): void; - addClass(el: any, clazz: string): void; - addEndpoint(ep: string): any; - removeClass(el: any, clazz: string): void; - hasClass(el: any, clazz: string): void; - draggable(el: string, options?: DragOptions): jsPlumbInstance; - draggable(ids: string[], options?: DragOptions): jsPlumbInstance; - connect(connection: ConnectParams, referenceParams?: ConnectParams): Connection; - makeSource(el: string, options: SourceOptions): void; - makeTarget(el: string, options: TargetOptions): void; - repaintEverything(): void; - detachEveryConnection(): void; - detachAllConnections(el: string): void; - removeAllEndpoints(el: string, recurse?: boolean): jsPlumbInstance; - removeAllEndpoints(el: Element, recurse?: boolean): jsPlumbInstance; - select(params: SelectParams): Connections; - getConnections(options?: any, flat?: any): any[]; - deleteEndpoint(uuid: string, doNotRepaintAfterwards?: boolean): jsPlumbInstance; - deleteEndpoint(endpoint: Endpoint, doNotRepaintAfterwards?: boolean): jsPlumbInstance; - repaint(el: string): jsPlumbInstance; - repaint(el: Element): jsPlumbInstance; - getInstance(): jsPlumbInstance; - getInstance(defaults: Defaults): jsPlumbInstance; - getInstanceIndex(): number; - - SVG: string; - CANVAS: string; - VML: string; -} - -interface Defaults { - Endpoint?: any[]; - PaintStyle?: PaintStyle; - HoverPaintStyle?: PaintStyle; - ConnectionsDetachable?: boolean; - ReattachConnections?: boolean; - ConnectionOverlays?: any[][]; - Container?: any; // string(selector or id) or element - DragOptions?: DragOptions; -} - -interface PaintStyle { - strokeStyle: string; - lineWidth: number; -} - -interface ArrowOverlay { - location: number; - id: string; - length: number; - foldback: number; -} - -interface LabelOverlay { - label: string; - id: string; - location: number; -} - -interface Connections { - detach(): void; - length: number; -} - -interface ConnectParams { - source?: any; // string, element or endpoint - target?: any; // string, element or endpoint - detachable?: boolean; - deleteEndpointsOnDetach?: boolean; - endPoint?: string; - anchor?: string; - anchors?: any[]; - label?: string; -} - -interface DragOptions { - containment?: string; -} - -interface SourceOptions { - parent: string; - endpoint?: string; - anchor?: string; - connector?: any[]; - connectorStyle?: PaintStyle; -} - -interface TargetOptions { - isTarget?: boolean; - maxConnections?: number; - uniqueEndpoint?: boolean; - deleteEndpointsOnDetach?: boolean; - endpoint?: string; - dropOptions?: DropOptions; - anchor?: any; -} - -interface DropOptions { - hoverClass: string; -} - -interface SelectParams { - scope?: string; - source: string; - target: string; -} - -interface Connection { - setDetachable(detachable: boolean): void; - setParameter(name: string, value: T): void; - endpoints: Endpoint[]; -} - -interface Endpoint { -} diff --git a/types/jsplumb/tslint.json b/types/jsplumb/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/jsplumb/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/jui-grid/index.d.ts b/types/jui-grid/index.d.ts index f22ad652d5..7ffae14ace 100644 --- a/types/jui-grid/index.d.ts +++ b/types/jui-grid/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/juijs/jui-grid // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { UIEvent } from 'jui-core'; export interface GridColumn { diff --git a/types/jui/index.d.ts b/types/jui/index.d.ts index d9e60d8a9c..d87fddc241 100644 --- a/types/jui/index.d.ts +++ b/types/jui/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/juijs/jui#readme // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + import { UIEvent } from 'jui-core'; export interface UIAccordion extends UIEvent { (selector: any, options?: { diff --git a/types/jws/index.d.ts b/types/jws/index.d.ts new file mode 100644 index 0000000000..f384fadefc --- /dev/null +++ b/types/jws/index.d.ts @@ -0,0 +1,152 @@ +// Type definitions for jws 3.1 +// Project: https://github.com/brianloveswords/node-jws +// Definitions by: Justin Beckwith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as events from 'events'; +import * as stream from 'stream'; + +/** + * (Synchronous) Return a JSON Web Signature for a header + * and a payload. + */ +export function sign(options: SignOptions): string; + +/** + * (Synchronous) Returns true or false for whether a signature + * matches a secret or key. + * @param signature JWS Signature + * @param algorithm Algorithm + * @param secretOrKey string or buffer containing either the secret + * for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA + */ +export function verify(signature: string, algorithm: Algorithm, secretOrKey: string|Buffer): boolean; + +/** + * (Synchronous) Returns the decoded header, decoded payload, + * and signature parts of the JWS Signature. + */ +export function decode(signature: string): Signature; + +/** + * Returns a new SignStream object. + */ +export function createSign(options: SignOptions): SignStream; + +/** + * Returns a new VerifyStream object. + */ +export function createVerify(options?: VerifyOptions): VerifyStream; + +/** + * A Readable Stream that emits a single data event, the + * calculated signature, when done. + */ +export interface SignStream extends stream.Readable { + /** + * A Writable Stream that expects the JWS payload. Do not + * use if you passed a payload option to the constructor. + * + * Example: payloadStream.pipe(signer.payload); + */ + payload: stream.Writable; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + secret: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + key: any; + + /** + * A Writable Stream. Expects the JWS secret for HMAC, or + * the privateKey for ECDSA and RSA. Do not use if you + * passed a secret or key option to the constructor. + * + * Example: privateKeyStream.pipe(signer.privateKey); + */ + privateKey: any; +} + +/** + * This is a Readable Stream that emits a single data event, + * the result of whether or not that signature was valid. + */ +export interface VerifyStream extends events.EventEmitter { + /** + * A Writable Stream that expects a JWS Signature. Do not + * use if you passed a signature option to the constructor. + */ + signature: stream.Writable; + + /** + * Secret. Can be a string, buffer, or object. + */ + secret: any; + + /** + * Key. Can be a string, buffer, or object. + */ + key: any; + + /** + * A Writable Stream that expects a public key or secret. + * Do not use if you passed a key or secret option to the + * constructor. + */ + publicKey: stream.Writable; +} + +export interface Signature { + header: Header; + payload: any; + signature: string; +} + +export interface SignOptions { + header: Header; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + payload?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + key?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + secret?: any; + + /** + * Can be a string, Buffer, Readable stream, or object. + */ + privateKey?: any; + + encoding?: string|Buffer|stream.Readable; +} + +export interface VerifyOptions { + signature?: string|Buffer|stream.Readable; + algorithm?: Algorithm|Buffer|stream.Readable; + key?: string|stream.Readable|Buffer; + secret?: string|stream.Readable|Buffer; + publicKey?: string|stream.Readable|Buffer; + encoding?: string|Buffer|stream.Readable; +} + +export type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | + 'RS384' | 'RS512' | 'ES256' | 'ES384' | + 'ES512' | 'none'; + +export interface Header { + alg: Algorithm; +} diff --git a/types/jws/jws-tests.ts b/types/jws/jws-tests.ts new file mode 100644 index 0000000000..d5271b24ca --- /dev/null +++ b/types/jws/jws-tests.ts @@ -0,0 +1,51 @@ +/** + * Tests are built by copying samples from the github repository: + * https://github.com/brianloveswords/node-jws + */ + +import * as jws from 'jws'; +import * as fs from "fs"; + +// set up mock objects +const fakeStream = fs.createReadStream('fakefile'); +const privateKeyStream = fakeStream; +const payloadStream = fakeStream; +const pubKeyStream = fakeStream; +const sigStream = fakeStream; + +// jws.sign +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); + +// jws.decode +const message = jws.decode('djfakdid'); + +// jws.createSign +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', signature => {}); + +// jws.createSign no params +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', signature => {}); + +// jws.createVerify +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', (verified, obj) => {}); + +// jws.createVerify with no options +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', (verified, obj) => {}); diff --git a/types/jws/tsconfig.json b/types/jws/tsconfig.json new file mode 100644 index 0000000000..a8a2f625d3 --- /dev/null +++ b/types/jws/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jws-tests.ts" + ] +} diff --git a/types/jws/tslint.json b/types/jws/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jws/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/karma-chai-sinon/index.d.ts b/types/karma-chai-sinon/index.d.ts index 70680f2ac7..76ee313a40 100644 --- a/types/karma-chai-sinon/index.d.ts +++ b/types/karma-chai-sinon/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tubalmartin/karma-chai-sinon // Definitions by: Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// import Sinon = require("sinon"); diff --git a/types/karma-coverage/tsconfig.json b/types/karma-coverage/tsconfig.json index 02a491bc01..fe130be15a 100644 --- a/types/karma-coverage/tsconfig.json +++ b/types/karma-coverage/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/karma-webpack/index.d.ts b/types/karma-webpack/index.d.ts index 0042ff01a3..06f45e3cbf 100644 --- a/types/karma-webpack/index.d.ts +++ b/types/karma-webpack/index.d.ts @@ -2,6 +2,7 @@ // Project: http://github.com/webpack/karma-webpack // Definitions by: Matt Traynham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as m from 'karma'; import webpack = require('webpack'); diff --git a/types/karma-webpack/tsconfig.json b/types/karma-webpack/tsconfig.json index d91714d8bc..86996cdcfa 100644 --- a/types/karma-webpack/tsconfig.json +++ b/types/karma-webpack/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/karma/tsconfig.json b/types/karma/tsconfig.json index 50bbc0c60b..23c81534d2 100644 --- a/types/karma/tsconfig.json +++ b/types/karma/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/kcors/index.d.ts b/types/kcors/index.d.ts index e4e9e53fa6..04c45d365a 100644 --- a/types/kcors/index.d.ts +++ b/types/kcors/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/cors // Definitions by: Xavier Stouder , Izayoi Ko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/keypress.js/index.d.ts b/types/keypress.js/index.d.ts index 63da327acd..202990da93 100644 --- a/types/keypress.js/index.d.ts +++ b/types/keypress.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Keypress 2.0 +// Type definitions for Keypress 2.1 // Project: https://github.com/dmauro/Keypress/ // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,9 +39,9 @@ export class Listener { simple_combo(keys: string, on_keydown_callback: (event?: KeyboardEvent, count?: number) => any): void; counting_combo(keys: string, on_count_callback: (event?: KeyboardEvent, count?: number) => any): void; sequence_combo(keys: string, callback: (event?: KeyboardEvent, count?: number) => any): void; - register_combo(combo: Combo): void; + register_combo(combo: Combo): Combo; unregister_combo(combo: Combo | string): void; - register_many(combos: Combo[]): void; + register_many(combos: Combo[]): Combo[]; unregister_many(combos: Combo[] | string[]): void; get_registered_combos(): Combo[]; destroy(): void; diff --git a/types/knex-postgis/index.d.ts b/types/knex-postgis/index.d.ts index 93105208c4..b63c1f11dd 100644 --- a/types/knex-postgis/index.d.ts +++ b/types/knex-postgis/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jfgodoy/knex-postgis // Definitions by: Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as GeoJSON from 'geojson'; import * as Knex from 'knex'; diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 974c3eb0a4..e96dfbefd8 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Knex.js // Project: https://github.com/tgriesser/knex -// Definitions by: Qubo , Baronfel +// Definitions by: Qubo , Baronfel , Pablo Rodríguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,7 +8,7 @@ import events = require("events"); import stream = require ("stream"); -import Promise = require("bluebird"); +import Bluebird = require("bluebird"); type Callback = Function; type Client = Function; @@ -22,9 +22,9 @@ interface Knex extends Knex.QueryInterface { __knex__: string; raw: Knex.RawBuilder; - transaction(transactionScope: (trx: Knex.Transaction) => any): Promise; + transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; destroy(callback: Function): void; - destroy(): Promise; + destroy(): Bluebird; batchInsert(tableName : TableName, data: any[], chunkSize : number) : Knex.QueryBuilder; schema: Knex.SchemaBuilder; queryBuilder(): Knex.QueryBuilder; @@ -156,7 +156,7 @@ declare namespace Knex { delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - transacting(trx: Transaction): QueryBuilder; + transacting(trx?: Transaction): QueryBuilder; connection(connection: any): QueryBuilder; clone(): QueryBuilder; @@ -351,7 +351,7 @@ declare namespace Knex { and: QueryBuilder; //TODO: Promise? - columnInfo(column?: string): Promise; + columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; forShare(): QueryBuilder; @@ -372,18 +372,18 @@ declare namespace Knex { // Chainable interface // - interface ChainableInterface extends Promise { + interface ChainableInterface extends Bluebird { toQuery(): string; options(options: any): QueryBuilder; - stream(callback: (readable: stream.PassThrough) => any): Promise; + stream(callback: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; - stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Promise; + stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird; pipe(writable: any): stream.PassThrough; exec(callback: Function): QueryBuilder; } interface Transaction extends Knex { - savepoint(transactionScope: (trx: Transaction) => any): Promise; + savepoint(transactionScope: (trx: Transaction) => any): Bluebird; commit(value?: any): QueryBuilder; rollback(error?: any): QueryBuilder; } @@ -392,14 +392,14 @@ declare namespace Knex { // Schema builder // - interface SchemaBuilder extends Promise { + interface SchemaBuilder extends Bluebird { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - renameTable(oldTableName: string, newTableName: string): Promise; + renameTable(oldTableName: string, newTableName: string): Bluebird; dropTable(tableName: string): SchemaBuilder; - hasTable(tableName: string): Promise; - hasColumn(tableName: string, columnName: string): Promise; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; + hasTable(tableName: string): Bluebird; + hasColumn(tableName: string, columnName: string): Bluebird; + table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Bluebird; dropTableIfExists(tableName: string): SchemaBuilder; raw(statement: string): SchemaBuilder; withSchema(schemaName: string): SchemaBuilder; @@ -666,11 +666,11 @@ declare namespace Knex { } interface Migrator { - make(name: string, config?: MigratorConfig): Promise; - latest(config?: MigratorConfig): Promise; - rollback(config?: MigratorConfig): Promise; - status(config?: MigratorConfig): Promise; - currentVersion(config?: MigratorConfig): Promise; + make(name: string, config?: MigratorConfig): Bluebird; + latest(config?: MigratorConfig): Bluebird; + rollback(config?: MigratorConfig): Bluebird; + status(config?: MigratorConfig): Bluebird; + currentVersion(config?: MigratorConfig): Bluebird; } interface FunctionHelper { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 95d28b1b2b..c7c99813f1 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -520,7 +520,6 @@ knex.transaction(function(trx) { }) .then(trx.commit) .catch(trx.rollback); - }).then(function() { console.log('Transaction complete.'); }).catch(function(err) { @@ -537,7 +536,17 @@ knex.transaction(function(trx) { .transacting(trx) .forShare() .select('*') -}); +}) + +const transactionReturnValue = knex.transaction(function(trx) { + return knex("table") + .insert({ foo: "bar" }) + .returning(["id"]) + .then(function(result) { return result[0].id as number }) +}) + +// Tests that the transaction has kept the type of its return value by referencing a method of number +transactionReturnValue.then(value => value.toExponential); knex('users').count('active'); @@ -616,7 +625,7 @@ knex.transaction(function(trx) { }); // Using trx as a transaction object: -knex.transaction(function(trx) { +knex.transaction<{ length: number }>(function(trx) { trx.raw(''); @@ -663,6 +672,9 @@ knex.transaction(function(trx) { console.error(error); }); +// transacting handles undefined +knex.insert({ name: 'Old Books'}).transacting(undefined); + knex.schema.withSchema("public").hasTable("table") as Promise; knex.schema.createTable('users', function (table) { diff --git a/types/knockout-amd-helpers/index.d.ts b/types/knockout-amd-helpers/index.d.ts index d12c8d9a8f..6f3a5493e1 100644 --- a/types/knockout-amd-helpers/index.d.ts +++ b/types/knockout-amd-helpers/index.d.ts @@ -2,10 +2,10 @@ // Project: https://github.com/rniemeyer/knockout-amd-helpers // Definitions by: David Sichau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// - interface KnockoutAMDModule { baseDir: string; initializer: string; diff --git a/types/knockout-secure-binding/index.d.ts b/types/knockout-secure-binding/index.d.ts index 84a432738b..f7c7500cff 100644 --- a/types/knockout-secure-binding/index.d.ts +++ b/types/knockout-secure-binding/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brianmhunt/knockout-secure-binding // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -28,4 +29,4 @@ declare module "knockout-secure-binding" { }; export = klass; -} \ No newline at end of file +} diff --git a/types/knockout-transformations/index.d.ts b/types/knockout-transformations/index.d.ts index 958eb99fb6..5fab318c1b 100644 --- a/types/knockout-transformations/index.d.ts +++ b/types/knockout-transformations/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/One-com/knockout-transformations // Definitions by: John Reilly , Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.deferred.updates/index.d.ts b/types/knockout.deferred.updates/index.d.ts index 89fb752089..c02f371277 100644 --- a/types/knockout.deferred.updates/index.d.ts +++ b/types/knockout.deferred.updates/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout-deferred-updates // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -42,4 +43,4 @@ interface KnockoutUtils { // Deferred extender interface KnockoutExtenders { deferred(target: any, value: boolean): any; -} \ No newline at end of file +} diff --git a/types/knockout.editables/index.d.ts b/types/knockout.editables/index.d.ts index 4a4ed59d3b..5167287e7e 100644 --- a/types/knockout.editables/index.d.ts +++ b/types/knockout.editables/index.d.ts @@ -2,6 +2,7 @@ // Project: http://romanych.github.com/ko.editables/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.es5/index.d.ts b/types/knockout.es5/index.d.ts index ce41db0d73..0ae2526c25 100644 --- a/types/knockout.es5/index.d.ts +++ b/types/knockout.es5/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/SteveSanderson/knockout-es5 // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapper/index.d.ts b/types/knockout.mapper/index.d.ts index 747a3d1f4a..d77f3e8f22 100644 --- a/types/knockout.mapper/index.d.ts +++ b/types/knockout.mapper/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/LucasLorentz/knockout.mapper // Definitions by: Brandon Meyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.mapping/index.d.ts b/types/knockout.mapping/index.d.ts index 23f7aae8b5..e6d5fe2f6c 100644 --- a/types/knockout.mapping/index.d.ts +++ b/types/knockout.mapping/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for Knockout.Mapping 2.0 // Project: https://github.com/SteveSanderson/knockout.mapping -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -33,17 +35,25 @@ declare global { update?: (options: KnockoutMappingUpdateOptions) => void; key?: (data: any) => any; } + + type KnockoutObservableType = { + [P in keyof T]: KnockoutObservable; + }; interface KnockoutMapping { isMapped(viewModel: any): boolean; - fromJS(jsObject: any): any; - fromJS(jsObject: any, targetOrOptions: any): any; - fromJS(jsObject: any, inputOptions: any, target: any): any; + fromJS(jsObject: T[]): KnockoutObservableType[]; + fromJS(jsObject: T[], targetOrOptions: any): KnockoutObservableType[]; + fromJS(jsObject: T[], inputOptions: any, target: any): KnockoutObservableType[]; + fromJS(jsObject: T): KnockoutObservableType; + fromJS(jsObject: T, targetOrOptions: any): KnockoutObservableType; + fromJS(jsObject: T, inputOptions: any, target: any): KnockoutObservableType; fromJSON(jsonString: string): any; fromJSON(jsonString: string, targetOrOptions: any): any; fromJSON(jsonString: string, inputOptions: any, target: any): any; - toJS(rootObject: any, options?: KnockoutMappingOptions): any; - toJSON(rootObject: any, options?: KnockoutMappingOptions): any; + toJS(rootObject: KnockoutObservableArray|T, options?: KnockoutMappingOptions): T[]; + toJS(rootObject: KnockoutObservableType|T, options?: KnockoutMappingOptions): T; + toJSON(rootObject: any, options?: KnockoutMappingOptions): string; defaultOptions(): KnockoutMappingOptions; resetDefaultOptions(): void; getType(x: any): any; diff --git a/types/knockout.postbox/index.d.ts b/types/knockout.postbox/index.d.ts index 56afa3a2b6..d7e967bcb9 100644 --- a/types/knockout.postbox/index.d.ts +++ b/types/knockout.postbox/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rniemeyer/knockout-postbox // Definitions by: Judah Gabriel Himango // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.projections/index.d.ts b/types/knockout.projections/index.d.ts index aae8b55f57..bed2ac82ca 100644 --- a/types/knockout.projections/index.d.ts +++ b/types/knockout.projections/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/stevesanderson/knockout-projections // Definitions by: John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.punches/index.d.ts b/types/knockout.punches/index.d.ts index aec2860bd9..c378d68c37 100644 --- a/types/knockout.punches/index.d.ts +++ b/types/knockout.punches/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mbest/knockout.punches // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.rx/index.d.ts b/types/knockout.rx/index.d.ts index 82a5473f1c..fea2c5175b 100644 --- a/types/knockout.rx/index.d.ts +++ b/types/knockout.rx/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Igorbek/knockout.rx // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/knockout.validation/index.d.ts b/types/knockout.validation/index.d.ts index 8b0300bd7f..e302ee6279 100644 --- a/types/knockout.validation/index.d.ts +++ b/types/knockout.validation/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ericmbarnard/Knockout-Validation // Definitions by: Dan Ludwig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout.viewmodel/index.d.ts b/types/knockout.viewmodel/index.d.ts index 5e57afb449..2ea6815531 100644 --- a/types/knockout.viewmodel/index.d.ts +++ b/types/knockout.viewmodel/index.d.ts @@ -2,6 +2,7 @@ // Project: http://coderenaissance.github.com/knockout.viewmodel/ // Definitions by: Oisin Grehan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 4ef3bc8739..8d035ed8d2 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov -// Igor Oleinikov -// Clément Bourgeois -// Matt Brooks -// Benjamin Eckardt +// Definitions by: Boris Yankov , +// Igor Oleinikov , +// Clément Bourgeois , +// Matt Brooks , +// Benjamin Eckardt , +// Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 interface KnockoutExtensionFunctions { [key: string]: any; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index e3f7820f94..9913b64fa8 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -484,8 +484,8 @@ function test_mappingplugin() { ko.mapping.fromJS(data, {}, this); var alice, aliceMappingOptions, bob, bobMappingOptions; - var viewModel = ko.mapping.fromJS(alice, aliceMappingOptions); - ko.mapping.fromJS(bob, bobMappingOptions, viewModel); + var aliceViewModel = ko.mapping.fromJS(alice, aliceMappingOptions); + ko.mapping.fromJS(bob, bobMappingOptions, aliceViewModel); var obj; var result = ko.mapping.fromJS(obj, { diff --git a/types/knuddels-userapps-api/tslint.json b/types/knuddels-userapps-api/tslint.json index 67eb97841e..3c7d3fe9c7 100644 --- a/types/knuddels-userapps-api/tslint.json +++ b/types/knuddels-userapps-api/tslint.json @@ -3,6 +3,8 @@ "rules": { // TODOs "no-mergeable-namespace": false, - "no-unnecsesary-class": false + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-unnecessary-class": false } } diff --git a/types/koa-basic-auth/index.d.ts b/types/koa-basic-auth/index.d.ts index 9d3433f006..2e76f6325a 100644 --- a/types/koa-basic-auth/index.d.ts +++ b/types/koa-basic-auth/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/basic-auth // Definitions by: Tobias Wolff // Definitions: https://github.com/Tobias4872/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/koa-bodyparser/index.d.ts b/types/koa-bodyparser/index.d.ts index fe6e3f23f9..042aa99ea3 100644 --- a/types/koa-bodyparser/index.d.ts +++ b/types/koa-bodyparser/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/bodyparser // Definitions by: Jerry Chin // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-cache-control/index.d.ts b/types/koa-cache-control/index.d.ts index 19329fcfec..4a65630fad 100644 --- a/types/koa-cache-control/index.d.ts +++ b/types/koa-cache-control/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DaMouse404/koa-cache-control // Definitions by: Peter Safranek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/koa-compress/index.d.ts b/types/koa-compress/index.d.ts index 16ade4120f..24b7a1e1af 100644 --- a/types/koa-compress/index.d.ts +++ b/types/koa-compress/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/compress // Definitions by: Jerry Chin // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-favicon/index.d.ts b/types/koa-favicon/index.d.ts index 57b3ae7ed3..3cb6af4551 100644 --- a/types/koa-favicon/index.d.ts +++ b/types/koa-favicon/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/favicon // Definitions by: Jerry Chin // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-helmet/index.d.ts b/types/koa-helmet/index.d.ts index 3e862fe6e6..df4c880ba9 100644 --- a/types/koa-helmet/index.d.ts +++ b/types/koa-helmet/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/venables/koa-helmet#readme // Definitions by: Nick Simmons // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { IHelmetConfiguration, diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts new file mode 100644 index 0000000000..fb7164d47d --- /dev/null +++ b/types/koa-joi-router/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for koa-joi-router 5.0 +// Project: https://github.com/koajs/joi-router +// Definitions by: Matthew Bull +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as Koa from 'koa'; +import * as Joi from 'joi'; + +interface Spec { + method: string; + path: string|RegExp; + handler: (ctx: createRouter.Context) => void; + validate?: { + type: string; + body?: Joi.AnySchema; + params?: Joi.AnySchema; + [status: number]: Joi.AnySchema; + }; +} + +interface Router { + route(spec: Spec): Router; + middleware(): Koa.Middleware; +} + +interface createRouter { + (): Router; + Joi: typeof Joi; +} + +declare namespace createRouter { + interface Request extends Koa.Request { + body: any; + params: {[key: string]: string}; + } + + interface Context extends Koa.Context { + request: Request; + } +} + +declare var createRouter: createRouter; + +export = createRouter; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts new file mode 100644 index 0000000000..e36ce95746 --- /dev/null +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -0,0 +1,71 @@ +import router = require('koa-joi-router'); + +const { Joi } = router; + +const spec1 = { + path: '/user', + method: 'POST', + handler: (ctx: router.Context) => ctx.body = '', +}; + +router().route(spec1); + +const spec2 = { + method: 'PATCH', + path: '/user', + validate: { + type: 'json', + }, + handler: (ctx: router.Context) => ctx.status = 201, +}; + +router().route(spec2); + +const spec3 = { + method: 'PATCH', + path: '/user', + validate: { + type: 'json', + body: Joi.any(), + }, + handler: (ctx: router.Context) => ctx.status = 201, +}; + +router().route(spec3); + +const spec4 = { + method: 'PATCH', + path: '/user', + validate: { + type: 'json', + 201: Joi.object(), + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = {}; + }, +}; + +router().route(spec4); + +const spec5 = { + method: 'PUT', + path: '/user', + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.body; + }, +}; + +router().route(spec5); + +const spec6 = { + method: 'GET', + path: '/user', + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec6); diff --git a/types/koa-joi-router/tsconfig.json b/types/koa-joi-router/tsconfig.json new file mode 100644 index 0000000000..a872570270 --- /dev/null +++ b/types/koa-joi-router/tsconfig.json @@ -0,0 +1,23 @@ +{ + "files": [ + "index.d.ts", + "koa-joi-router-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/koa-joi-router/tslint.json b/types/koa-joi-router/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/koa-joi-router/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/koa-json-error/index.d.ts b/types/koa-json-error/index.d.ts index 5fc9618edf..b660e4c55f 100644 --- a/types/koa-json-error/index.d.ts +++ b/types/koa-json-error/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/koajs/json-error // Definitions by: Mudkip // Definitions: https://github.com/mudkipme/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/koa-json/index.d.ts b/types/koa-json/index.d.ts index aceecf721f..670b33be39 100644 --- a/types/koa-json/index.d.ts +++ b/types/koa-json/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/json // Definitions by: Alex Friedman // Definitions: https://github.com/brooklyndev/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-jwt/index.d.ts b/types/koa-jwt/index.d.ts index 87b64bea58..5017be7bc2 100644 --- a/types/koa-jwt/index.d.ts +++ b/types/koa-jwt/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/jwt // Definitions by: Bruno Krebs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import Koa = require("koa"); diff --git a/types/koa-logger-winston/index.d.ts b/types/koa-logger-winston/index.d.ts index 687c3494fa..ccb63ccd68 100644 --- a/types/koa-logger-winston/index.d.ts +++ b/types/koa-logger-winston/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/selbyk/koa-logger-winston#readme // Definitions by: Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/koa-logger/index.d.ts b/types/koa-logger/index.d.ts index bd0d4174b0..460d70f3fb 100644 --- a/types/koa-logger/index.d.ts +++ b/types/koa-logger/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/logger // Definitions by: Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/koa-mount/index.d.ts b/types/koa-mount/index.d.ts index f0cec6f938..d408932bfc 100644 --- a/types/koa-mount/index.d.ts +++ b/types/koa-mount/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/koajs/mount // Definitions by: AmirSaber Sharifi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/koa-passport/index.d.ts b/types/koa-passport/index.d.ts index e3a318004a..d7d63cee96 100644 --- a/types/koa-passport/index.d.ts +++ b/types/koa-passport/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rkusa/koa-passport // Definitions by: horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-pino-logger/index.d.ts b/types/koa-pino-logger/index.d.ts index 2ea66937b6..0994e7584a 100644 --- a/types/koa-pino-logger/index.d.ts +++ b/types/koa-pino-logger/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/pinojs/koa-pino-logger // Definitions by: Cameron Yan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/koa-pug/index.d.ts b/types/koa-pug/index.d.ts index f478072953..347e4004c7 100644 --- a/types/koa-pug/index.d.ts +++ b/types/koa-pug/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/chrisyip/koa-pug // Definitions by: Xavier Stouder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as koa from "koa"; diff --git a/types/koa-range/index.d.ts b/types/koa-range/index.d.ts index f2b109b899..9240491f04 100644 --- a/types/koa-range/index.d.ts +++ b/types/koa-range/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/koa-range // Definitions by: Sami Kukkonen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from "koa"; declare const KoaRange: Koa.Middleware; diff --git a/types/koa-redis/index.d.ts b/types/koa-redis/index.d.ts index 1103665858..bdc3b99bfa 100644 --- a/types/koa-redis/index.d.ts +++ b/types/koa-redis/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/koa-redis // Definitions by: Nick Simmons // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { ClientOpts } from 'redis'; import { SessionStore } from 'koa-generic-session'; diff --git a/types/koa-route/index.d.ts b/types/koa-route/index.d.ts index 4ee63b7b14..33840d2842 100644 --- a/types/koa-route/index.d.ts +++ b/types/koa-route/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/koajs/route#readme // Definitions by: Mike Cook // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Koa from 'koa'; import * as pathToRegexp from 'path-to-regexp'; diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 972c02014c..4ad96140eb 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/alexmingoia/koa-router/ // Definitions by: Jerry Chin , Pavel Ivanov // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== @@ -33,15 +34,25 @@ declare module Router { export interface IRouterOptions { /** - * Router prefixes + * Prefix for all routes. */ prefix?: string; /** - * HTTP verbs + * Methods which should be supported by the router. */ methods?: string[]; routerPath?: string; + /** + * Whether or not routing should be case-sensitive. + */ sensitive?: boolean; + /** + * Whether or not routes should matched strictly. + * + * If strict matching is enabled, the trailing slash is taken into + * account when matching routes. + */ + strict?: boolean; } export interface IRouterContext extends Koa.Context { @@ -139,7 +150,7 @@ declare class Router { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string | RegExp, ...middleware: Array): Router; + use(path: string | string[] | RegExp, ...middleware: Array): Router; /** * HTTP get method diff --git a/types/koa-send/index.d.ts b/types/koa-send/index.d.ts index 521e96036e..a15f5b688d 100644 --- a/types/koa-send/index.d.ts +++ b/types/koa-send/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/send // Definitions by: Peter Safranek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from 'koa'; diff --git a/types/koa-session-minimal/index.d.ts b/types/koa-session-minimal/index.d.ts index 02d3a68004..dd3cf141b4 100644 --- a/types/koa-session-minimal/index.d.ts +++ b/types/koa-session-minimal/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/longztian/koa-session-minimal // Definitions by: Longzhang Tian // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-session/index.d.ts b/types/koa-session/index.d.ts index da08cc6464..bdc7d6b25b 100644 --- a/types/koa-session/index.d.ts +++ b/types/koa-session/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/session // Definitions by: Yu Hsin Lu // Definitions: https://github.com/kerol2r20/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-static/index.d.ts b/types/koa-static/index.d.ts index 06e8e09bf6..6395efec3a 100644 --- a/types/koa-static/index.d.ts +++ b/types/koa-static/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/static // Definitions by: Jerry Chin // Definitions: https://github.com/hellopao/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-views/index.d.ts b/types/koa-views/index.d.ts index e89a2d7cf8..ecbf019a59 100644 --- a/types/koa-views/index.d.ts +++ b/types/koa-views/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/queckezz/koa-views // Definitions by: Alex Friedman // Definitions: https://github.com/brooklyndev/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts index 115dbb43f6..326f098ae5 100644 --- a/types/koa-websocket/index.d.ts +++ b/types/koa-websocket/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kudos/koa-websocket // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Koa from 'koa'; import * as ws from 'ws'; diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index 0fd2b73edd..d4f339aa32 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -2,6 +2,7 @@ // Project: http://koajs.com // Definitions by: DavidCai1993 , jKey Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /* =================== USAGE =================== @@ -135,6 +136,11 @@ declare interface ContextDelegatedRequest { */ secure: boolean; + /** + * Request remote address. Supports X-Forwarded-For when app.proxy is true. + */ + ip: string; + /** * When `app.proxy` is `true`, parse * the "X-Forwarded-For" ip address list. diff --git a/types/koa2-cors/index.d.ts b/types/koa2-cors/index.d.ts index b353904eff..93409e846e 100644 --- a/types/koa2-cors/index.d.ts +++ b/types/koa2-cors/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zadzbw/koa2-cors#readme // Definitions by: xialeistudio // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import * as Koa from 'koa'; declare namespace cors { diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index c7dc10bad4..25d337716e 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/koajs/cors // Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Koa from "koa"; diff --git a/types/kolite/knockout.activity.d.ts b/types/kolite/knockout.activity.d.ts index 8a1f1a0fac..8022e18cff 100644 --- a/types/kolite/knockout.activity.d.ts +++ b/types/kolite/knockout.activity.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.command.d.ts b/types/kolite/knockout.command.d.ts index ff509dbd16..786bbcfaae 100644 --- a/types/kolite/knockout.command.d.ts +++ b/types/kolite/knockout.command.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kolite/knockout.dirtyFlag.d.ts b/types/kolite/knockout.dirtyFlag.d.ts index 1c63ce8b7d..2f63a110e0 100644 --- a/types/kolite/knockout.dirtyFlag.d.ts +++ b/types/kolite/knockout.dirtyFlag.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/CodeSeven/kolite // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 /// /// diff --git a/types/kue/index.d.ts b/types/kue/index.d.ts index 2b7d7015b8..35c7a1c475 100644 --- a/types/kue/index.d.ts +++ b/types/kue/index.d.ts @@ -4,6 +4,7 @@ // Amiram Korach // Christian D. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/latlon-geohash/index.d.ts b/types/latlon-geohash/index.d.ts new file mode 100644 index 0000000000..a7d843c30c --- /dev/null +++ b/types/latlon-geohash/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for latlon-geohash 1.1 +// Project: https://github.com/chrisveness/latlon-geohash +// Definitions by: Robert Imig +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export enum Direction { + North = "N", + South = "S", + East = "E", + West = "W" +} + +export interface Neighbours { + n: string; + ne: string; + e: string; + se: string; + s: string; + sw: string; + w: string; + nw: string; +} + +export interface Bounds { + sw: Point; + ne: Point; +} + +export interface Point { + lat: number; + lon: number; +} + +/** + * Encodes latitude/longitude to geohash, either to specified precision or to automatically + * evaluated precision. + * + * @param lat - Latitude in degrees. + * @param lon - Longitude in degrees. + * @param [precision] - Number of characters in resulting geohash. + * @returns Geohash of supplied latitude/longitude. + * @throws Invalid geohash. + * + * @example + * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw' + */ + +export function encode( + latitude: number, + longitude: number, + precision?: number +): string; + +/** + * Decode geohash to latitude/longitude (location is approximate centre of geohash cell, + * to reasonable precision). + * + * @param geohash - Geohash string to be converted to latitude/longitude. + * @returns (Center of) geohashed location. + * @throws Invalid geohash. + * + * @example + * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 } + */ +export function decode(geohash: string): Point; + +/** + * Returns SW/NE latitude/longitude bounds of specified geohash. + * + * @param geohash - Cell that bounds are required of. + * @returns The Bounds + * @throws Invalid geohash. + */ +export function bounds(geohash: string): Bounds; + +/** + * Determines adjacent cell in given direction. + * + * @param geohash - Cell to which adjacent cell is required. + * @param direction - Direction from geohash (N/S/E/W). + * @returns Geocode of adjacent cell. + * @throws Invalid geohash. + */ +export function adjacent(geohash: string, direction: Direction | string): string; + +/** + * Returns all 8 adjacent cells to specified geohash. + * + * @param geohash - Geohash neighbours are required of. + * @returns The neighbours + * @throws Invalid geohash. + */ +export function neighbours(geohash: string): Neighbours; diff --git a/types/latlon-geohash/latlon-geohash-tests.ts b/types/latlon-geohash/latlon-geohash-tests.ts new file mode 100644 index 0000000000..632c7e64ed --- /dev/null +++ b/types/latlon-geohash/latlon-geohash-tests.ts @@ -0,0 +1,19 @@ +import * as Geohash from "latlon-geohash"; + +// Encoding +const atx_geohash: string = Geohash.encode(30.2672, -97.7431); +const atx_geohash_p3: string = Geohash.encode(30.2672, -97.7431, 3); + +// Decoding +const atx_latlong: Geohash.Point = Geohash.decode(atx_geohash); + +// Bounds +const atx_bounds: Geohash.Bounds = Geohash.bounds(atx_geohash); + +// Adjacent +const atx_adj_cell1: string = Geohash.adjacent(atx_geohash, Geohash.Direction.North); +const atx_adj_cell2: string = Geohash.adjacent(atx_geohash, "N"); + +// Neighbors +const atx_neighbors: Geohash.Neighbours = Geohash.neighbours(atx_geohash); +const atx_adj_cell3: string = atx_neighbors.n; diff --git a/types/latlon-geohash/tsconfig.json b/types/latlon-geohash/tsconfig.json new file mode 100644 index 0000000000..10d9c00791 --- /dev/null +++ b/types/latlon-geohash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "latlon-geohash-tests.ts" + ] +} diff --git a/types/latlon-geohash/tslint.json b/types/latlon-geohash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/latlon-geohash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lazypipe/tsconfig.json b/types/lazypipe/tsconfig.json index 31a6b4b294..7eb8c93b6a 100644 --- a/types/lazypipe/tsconfig.json +++ b/types/lazypipe/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/ldapjs/index.d.ts b/types/ldapjs/index.d.ts index 0afbf16046..8034add042 100644 --- a/types/ldapjs/index.d.ts +++ b/types/ldapjs/index.d.ts @@ -71,6 +71,10 @@ export interface Change { }; } +export var Change: { + new(change: Change): Change; +} + export interface SearchCallBack { (error: Error, result: EventEmitter): void; } diff --git a/types/ldapjs/ldapjs-tests.ts b/types/ldapjs/ldapjs-tests.ts index 6b2d879142..ec106fd29a 100644 --- a/types/ldapjs/ldapjs-tests.ts +++ b/types/ldapjs/ldapjs-tests.ts @@ -18,3 +18,14 @@ let opts: ldap.SearchOptions = { client.search('o=example', opts, (err: Error, res: NodeJS.EventEmitter): void => { // nothing }); + +let change = new ldap.Change({ + operation: 'add', + modification: { + pets: ['cat', 'dog'] + } +}); + +client.modify('cn=foo, o=example', change, function(err) { + // nothing +}); diff --git a/types/ldapjs/tsconfig.json b/types/ldapjs/tsconfig.json index 1f1d5bafc9..a0df7615fd 100644 --- a/types/ldapjs/tsconfig.json +++ b/types/ldapjs/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "ldapjs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/leaflet-areaselect/index.d.ts b/types/leaflet-areaselect/index.d.ts index 50b0202f6a..ae7f4e042d 100644 --- a/types/leaflet-areaselect/index.d.ts +++ b/types/leaflet-areaselect/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/heyman/leaflet-areaselect // Definitions by: André Wallat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-curve/index.d.ts b/types/leaflet-curve/index.d.ts index 58e4551dec..aaf9fa1c38 100644 --- a/types/leaflet-curve/index.d.ts +++ b/types/leaflet-curve/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/onikiienko/Leaflet.curve // Definitions by: Onikiienko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-draw/index.d.ts b/types/leaflet-draw/index.d.ts index de0767d462..35d014b699 100644 --- a/types/leaflet-draw/index.d.ts +++ b/types/leaflet-draw/index.d.ts @@ -66,6 +66,13 @@ declare module 'leaflet' { */ circle?: DrawOptions.CircleOptions | false; + /** + * Circle marker draw handler options. Set to false to disable handler. + * + * Default value: {} + */ + circlemarker?: DrawOptions.CircleMarkerOptions | false; + /** * Marker draw handler options. Set to false to disable handler. * @@ -201,6 +208,71 @@ declare module 'leaflet' { repeatMode?: boolean; } + interface CircleMarkerOptions { + /** + * Whether to draw stroke around the circle marker. + * + * Default value: true + */ + stroke?: boolean; + + /** + * The stroke color of the circle marker. + * + * Default value: '#3388ff' + */ + color?: string; + + /** + * The stroke width in pixels of the circle marker. + * + * Default value: 4 + */ + weight?: number; + + /** + * The stroke opacity of the circle marker. + * + * Default value: 0.5 + */ + opacity?: number; + + /** + * Whether to fill the circle marker with color. + * + * Default value: true + */ + fill?: boolean; + + /** + * The fill color of the circle marker. Defaults to the value of the color option. + * + * Default value: null + */ + fillColor?: string; + + /** + * The opacity of the circle marker. + * + * Default value: 0.2 + */ + fillOpacity?: number; + + /** + * Whether you can click the circle marker. + * + * Default value: true + */ + clickable?: boolean; + + /** + * This should be a high number to ensure that you can draw over all other layers on the map. + * + * Default value: 2000 + */ + zIndexOffset?: number; + } + interface MarkerOptions { /** * TThe icon displayed when drawing a marker. diff --git a/types/leaflet-editable/index.d.ts b/types/leaflet-editable/index.d.ts index ee42cb1fb1..932ca33fd2 100644 --- a/types/leaflet-editable/index.d.ts +++ b/types/leaflet-editable/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yohanboniface/Leaflet.Editable // Definitions by: Dominic Alie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Leaflet from 'leaflet'; diff --git a/types/leaflet-fullscreen/index.d.ts b/types/leaflet-fullscreen/index.d.ts index bf354e9155..b9248092e1 100644 --- a/types/leaflet-fullscreen/index.d.ts +++ b/types/leaflet-fullscreen/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Leaflet/Leaflet.fullscreen // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-geocoder-mapzen/index.d.ts b/types/leaflet-geocoder-mapzen/index.d.ts index d4f8b445d9..c6b5444c3e 100644 --- a/types/leaflet-geocoder-mapzen/index.d.ts +++ b/types/leaflet-geocoder-mapzen/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mapzen/leaflet-geocoder // Definitions by: Leonard Lausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-imageoverlay-rotated/index.d.ts b/types/leaflet-imageoverlay-rotated/index.d.ts index 6a37345ca5..a40fb7861c 100644 --- a/types/leaflet-imageoverlay-rotated/index.d.ts +++ b/types/leaflet-imageoverlay-rotated/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/IvanSanchez/Leaflet.ImageOverlay.Rotated // Definitions by: Thomas Kleinke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-label/index.d.ts b/types/leaflet-label/index.d.ts index 60f2b6b398..0a651a0d0c 100644 --- a/types/leaflet-label/index.d.ts +++ b/types/leaflet-label/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Leaflet/Leaflet.label // Definitions by: Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-providers/index.d.ts b/types/leaflet-providers/index.d.ts index aa5af026a1..bc9a4576de 100644 --- a/types/leaflet-providers/index.d.ts +++ b/types/leaflet-providers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/leaflet-extras/leaflet-providers#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet-rotatedmarker/index.d.ts b/types/leaflet-rotatedmarker/index.d.ts index d11a82ae56..dfbf8966de 100644 --- a/types/leaflet-rotatedmarker/index.d.ts +++ b/types/leaflet-rotatedmarker/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bbecquet/Leaflet.RotatedMarker // Definitions by: Robert Prib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet.awesome-markers/v0/index.d.ts b/types/leaflet.awesome-markers/v0/index.d.ts index b695d3918b..154c7852a4 100644 --- a/types/leaflet.awesome-markers/v0/index.d.ts +++ b/types/leaflet.awesome-markers/v0/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sigma-geosistemas/Leaflet.awesome-markers#properties // Definitions by: Egor Komarov , Marcel Sebek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Leaflet from "leaflet"; diff --git a/types/leaflet.fullscreen/index.d.ts b/types/leaflet.fullscreen/index.d.ts index 4e58ede10c..79ab81114b 100644 --- a/types/leaflet.fullscreen/index.d.ts +++ b/types/leaflet.fullscreen/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brunob/leaflet.fullscreen // Definitions by: William Comartin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet.gridlayer.googlemutant/index.d.ts b/types/leaflet.gridlayer.googlemutant/index.d.ts index 00fd9fdce0..29a1e69a6b 100644 --- a/types/leaflet.gridlayer.googlemutant/index.d.ts +++ b/types/leaflet.gridlayer.googlemutant/index.d.ts @@ -2,6 +2,7 @@ // Project: https://gitlab.com/IvanSanchez/Leaflet.GridLayer.GoogleMutant#README // Definitions by: Ernest Rhinozeros // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet.locatecontrol/index.d.ts b/types/leaflet.locatecontrol/index.d.ts index 4b8225dec2..35c88be5be 100644 --- a/types/leaflet.locatecontrol/index.d.ts +++ b/types/leaflet.locatecontrol/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/domoritz/leaflet-locatecontrol // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as L from 'leaflet'; diff --git a/types/leaflet.markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts index f60a7a2891..e2f317dd46 100644 --- a/types/leaflet.markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -29,7 +29,7 @@ declare module 'leaflet' { getBounds(): LatLngBounds; } - interface MarkerClusterGroupOptions { + interface MarkerClusterGroupOptions extends LayerOptions { /* * When you mouse over a cluster it shows the bounds of its markers. */ diff --git a/types/leaflet.polylinemeasure/index.d.ts b/types/leaflet.polylinemeasure/index.d.ts new file mode 100644 index 0000000000..ea647b1266 --- /dev/null +++ b/types/leaflet.polylinemeasure/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for leaflet.polylinemeasure 1.0 +// Project: https://github.com/ppete2/Leaflet.PolylineMeasure#readme +// Definitions by: Rinat Sultanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as L from 'leaflet'; + +declare module 'leaflet' { + namespace Control { + interface PolylineMeasure extends Control { + new (options?: PolylineMeasureOptions): any; + } + + interface PolylineMeasureOptions { + position?: string; + unit?: string; + measureControlTitleOn?: string; + measureControlTitleOff?: string; + measureControlLabel?: string; + measureControlClasses?: any[]; + backgroundColor?: string; + cursor?: string; + clearMeasurementsOnStop?: boolean; + showMeasurementsClearControl?: boolean; + clearControlTitle?: string; + clearControlLabel?: string; + clearControlClasses?: any[]; + showUnitControl?: boolean; + tempLine?: any; + fixedLine?: any; + startCircle?: any; + intermedCircle?: any; + currentCircle?: any; + endCircle?: any; + } + } + + namespace control { + function polylineMeasure(options?: Control.PolylineMeasureOptions): Control.PolylineMeasure; + } +} diff --git a/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts b/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts new file mode 100644 index 0000000000..c659a77b1c --- /dev/null +++ b/types/leaflet.polylinemeasure/leaflet.polylinemeasure-tests.ts @@ -0,0 +1,11 @@ +import * as L from 'leaflet'; +import 'leaflet.polylinemeasure'; + +const map = L.map('map', {center: L.latLng(43.24209, 76.87743), zoom: 15}); + +L.tileLayer("http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", { + subdomains: ['a', 'b', 'c'], + attribution: '© OpenStreetMap' +}).addTo(map); + +L.control.polylineMeasure().addTo(map); diff --git a/types/leaflet.polylinemeasure/tsconfig.json b/types/leaflet.polylinemeasure/tsconfig.json new file mode 100644 index 0000000000..b1db5e086d --- /dev/null +++ b/types/leaflet.polylinemeasure/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "DOM" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leaflet.polylinemeasure-tests.ts" + ] +} diff --git a/types/leaflet.polylinemeasure/tslint.json b/types/leaflet.polylinemeasure/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leaflet.polylinemeasure/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index b4c71d06f7..71c6ea4adf 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -241,20 +241,22 @@ export abstract class Evented extends Class { */ on(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:disable:unified-signatures */ // With an eventMap there are no additional arguments allowed /** * Removes a previously added listener function. If no function is specified, * it will remove all the listeners of that particular event from the object. * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(type: string, fn?: LeafletEventHandlerFn, context?: any): this; /** * Removes a set of type/listener pairs. */ + // With an eventMap there are no additional arguments allowed + // tslint:disable-next-line:unified-signatures off(eventMap: LeafletEventHandlerFnMap): this; - /* tslint:enable */ /** * Removes all listeners to all events on the object. */ @@ -581,9 +583,9 @@ export interface PolylineOptions extends PathOptions { noClip?: boolean; } -export class Polyline extends Path { +export class Polyline extends Path { constructor(latlngs: LatLngExpression[], options?: PolylineOptions); - toGeoJSON(): geojson.Feature; + toGeoJSON(): geojson.Feature; getLatLngs(): LatLng[]; setLatLngs(latlngs: LatLngExpression[]): this; isEmpty(): boolean; @@ -591,19 +593,19 @@ export class Polyline; + feature?: geojson.Feature; options: PolylineOptions; } export function polyline(latlngs: LatLngExpression[], options?: PolylineOptions): Polyline; -export class Polygon extends Polyline { +export class Polygon

    extends Polyline { constructor(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions); } export function polygon(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions): Polygon; -export class Rectangle extends Polygon { +export class Rectangle

    extends Polygon

    { constructor(latLngBounds: LatLngBoundsExpression, options?: PolylineOptions); setBounds(latLngBounds: LatLngBoundsExpression): this; } @@ -614,21 +616,21 @@ export interface CircleMarkerOptions extends PathOptions { radius?: number; } -export class CircleMarker extends Path { +export class CircleMarker

    extends Path { constructor(latlng: LatLngExpression, options?: CircleMarkerOptions); - toGeoJSON(): geojson.Feature; + toGeoJSON(): geojson.Feature; setLatLng(latLng: LatLngExpression): this; getLatLng(): LatLng; setRadius(radius: number): this; getRadius(): number; options: CircleMarkerOptions; - feature?: geojson.Feature; + feature?: geojson.Feature; } export function circleMarker(latlng: LatLngExpression, options?: CircleMarkerOptions): CircleMarker; -export class Circle extends CircleMarker { +export class Circle

    extends CircleMarker

    { constructor(latlng: LatLngExpression, options?: CircleMarkerOptions); constructor(latlng: LatLngExpression, radius: number, options?: CircleMarkerOptions); // deprecated! getBounds(): LatLngBounds; @@ -666,12 +668,13 @@ export function canvas(options?: RendererOptions): Canvas; * If you add it to the map, any layers added or removed from the group will be * added/removed on the map as well. Extends Layer. */ -export class LayerGroup extends Layer { - constructor(layers?: Layer[]); +export class LayerGroup

    extends Layer { + constructor(layers?: Layer[], options?: LayerOptions); + /** * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection, GeoJSONFeatureCollection or Multipoint). */ - toGeoJSON(): geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; + toGeoJSON(): geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; /** * Adds the given layer to the group. @@ -725,23 +728,23 @@ export class LayerGroup extends Layer { */ getLayerId(layer: Layer): number; - feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; + feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; } /** - * Create a layer group, optionally given an initial set of layers. + * Create a layer group, optionally given an initial set of layers and an `options` object. */ -export function layerGroup(layers: Layer[]): LayerGroup; +export function layerGroup(layers?: Layer[], options?: LayerOptions): LayerGroup; /** * Extended LayerGroup that also has mouse events (propagated from * members of the group) and a shared bindPopup method. */ -export class FeatureGroup extends LayerGroup { +export class FeatureGroup

    extends LayerGroup

    { /** * Sets the given path options to each layer of the group that has a setStyle method. */ - setStyle(style: StyleFunction): this; + setStyle(style: PathOptions): this; /** * Brings the layer group to the top of all other layers @@ -765,9 +768,9 @@ export class FeatureGroup extends LayerGroup { */ export function featureGroup(layers?: Layer[]): FeatureGroup; -export type StyleFunction = (feature?: geojson.Feature) => PathOptions; +export type StyleFunction

    = (feature?: geojson.Feature) => PathOptions; -export interface GeoJSONOptions extends LayerOptions { +export interface GeoJSONOptions

    extends LayerOptions { /** * A Function defining how GeoJSON points spawn Leaflet layers. * It is internally called when data is added, passing the GeoJSON point @@ -781,7 +784,7 @@ export interface GeoJSONOptions extends LayerOptions { * } * ``` */ - pointToLayer?(geoJsonPoint: geojson.Feature, latlng: LatLng): Layer; // should import GeoJSON typings + pointToLayer?(geoJsonPoint: geojson.Feature, latlng: LatLng): Layer; // should import GeoJSON typings /** * A Function defining the Path options for styling GeoJSON lines and polygons, @@ -795,7 +798,7 @@ export interface GeoJSONOptions extends LayerOptions { * } * ``` */ - style?: StyleFunction; + style?: StyleFunction

    ; /** * A Function that will be called once for each created Feature, after it @@ -807,7 +810,7 @@ export interface GeoJSONOptions extends LayerOptions { * function (feature, layer) {} * ``` */ - onEachFeature?(feature: geojson.Feature, layer: Layer): void; + onEachFeature?(feature: geojson.Feature, layer: Layer): void; /** * A Function that will be used to decide whether to show a feature or not. @@ -820,7 +823,7 @@ export interface GeoJSONOptions extends LayerOptions { * } * ``` */ - filter?(geoJsonFeature: geojson.Feature): boolean; + filter?(geoJsonFeature: geojson.Feature): boolean; /** * A Function that will be used for converting GeoJSON coordinates to LatLngs. @@ -833,12 +836,12 @@ export interface GeoJSONOptions extends LayerOptions { * Represents a GeoJSON object or an array of GeoJSON objects. * Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup. */ -export class GeoJSON extends FeatureGroup { +export class GeoJSON

    extends FeatureGroup

    { /** * Creates a Layer from a given GeoJSON feature. Can use a custom pointToLayer * and/or coordsToLatLng functions if provided as options. */ - static geometryToLayer(featureData: geojson.Feature, options?: GeoJSONOptions): Layer; + static geometryToLayer

    (featureData: geojson.Feature, options?: GeoJSONOptions

    ): Layer; /** * Creates a LatLng object from an array of 2 numbers (longitude, latitude) or @@ -872,9 +875,9 @@ export class GeoJSON extends FeatureGroup { /** * Normalize GeoJSON geometries/features into GeoJSON features. */ - static asFeature(geojson: geojson.Feature | geojson.GeometryObject): geojson.Feature; + static asFeature

    (geojson: geojson.Feature | geojson.GeometryObject): geojson.Feature; - constructor(geojson?: geojson.GeoJsonObject, options?: GeoJSONOptions) + constructor(geojson?: geojson.GeoJsonObject, options?: GeoJSONOptions

    ) /** * Adds a GeoJSON object to the layer. */ @@ -886,12 +889,7 @@ export class GeoJSON extends FeatureGroup { */ resetStyle(layer: Layer): Layer; - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: StyleFunction): this; - - options: GeoJSONOptions; + options: GeoJSONOptions

    ; } /** @@ -901,7 +899,7 @@ export class GeoJSON extends FeatureGroup { * map (you can alternatively add it later with addData method) and * an options object. */ -export function geoJSON(geojson?: geojson.GeoJsonObject, options?: GeoJSONOptions): GeoJSON; +export function geoJSON

    (geojson?: geojson.GeoJsonObject, options?: GeoJSONOptions

    ): GeoJSON

    ; export type Zoom = boolean | 'center'; @@ -1133,9 +1131,8 @@ export interface PanOptions { noMoveStart?: boolean; } -/* tslint:disable:no-empty-interface */ // This is not empty, it extends two interfaces into one... +// This is not empty, it extends two interfaces into one... export interface ZoomPanOptions extends ZoomOptions, PanOptions {} -/* tslint:enable */ export interface FitBoundsOptions extends ZoomOptions, PanOptions { paddingTopLeft?: PointExpression; @@ -1457,8 +1454,9 @@ export interface MarkerOptions extends InteractiveLayerOptions { riseOffset?: number; } -export class Marker extends Layer { +export class Marker

    extends Layer { constructor(latlng: LatLngExpression, options?: MarkerOptions); + toGeoJSON(): geojson.Feature; getLatLng(): LatLng; setLatLng(latlng: LatLngExpression): this; setZIndexOffset(offset: number): this; @@ -1469,6 +1467,7 @@ export class Marker extends Layer { // Properties options: MarkerOptions; dragging?: Handler; + feature?: geojson.Feature; } export function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index b85c8bf4d7..a39ea761b1 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -381,11 +381,11 @@ draggable.on('drag', () => {}); let twoCoords: [number, number] = [1, 2]; latLng = L.GeoJSON.coordsToLatLng(twoCoords); -twoCoords = L.GeoJSON.latLngToCoords(latLng); +twoCoords = L.GeoJSON.latLngToCoords(latLng) as [number, number]; -let threeCoords: [number, number] = [1, 2]; +let threeCoords: [number, number, number] = [1, 2, 3]; latLng = L.GeoJSON.coordsToLatLng(threeCoords); -threeCoords = L.GeoJSON.latLngToCoords(latLng); +threeCoords = L.GeoJSON.latLngToCoords(latLng) as [number, number, number]; let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); @@ -484,3 +484,29 @@ L.Util.requestAnimFrame(() => {}, {}); L.Util.requestAnimFrame(() => {}, {}, true); L.Util.cancelAnimFrame(1); L.Util.emptyImageUrl; + +interface MyProperties { + testProperty: string; +} + +(L.polygon(latLngs) as L.Polygon).feature.properties.testProperty = "test"; + +(L.marker([1, 2], { + icon: L.icon({ + iconUrl: 'my-icon.png' + }) +}) as L.Marker).feature.properties.testProperty = "test"; + +let lg = L.layerGroup(); +lg = L.layerGroup([new L.Layer(), new L.Layer()]); +lg = L.layerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); + +lg = new L.LayerGroup(); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()]); +lg = new L.LayerGroup([new L.Layer(), new L.Layer()], { + pane: 'overlayPane', + attribution: 'test' +}); diff --git a/types/leaflet/v0/index.d.ts b/types/leaflet/v0/index.d.ts index b33d19c5bb..efadd88e8f 100644 --- a/types/leaflet/v0/index.d.ts +++ b/types/leaflet/v0/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/lil-uuid/index.d.ts b/types/lil-uuid/index.d.ts new file mode 100644 index 0000000000..fb0a783142 --- /dev/null +++ b/types/lil-uuid/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for lil-uuid 0.1 +// Project: https://github.com/lil-js/uuid +// Definitions by: Pr1st0n +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Generate a random UUID + * + * @returns UUID string. + */ +export function uuid(): string; + +/** + * Check if a given string has a valid UUID format. It supports multiple version (3, 4 and 5). + * + * @param uuid UUID string. + * @returns True if string is valid UUID, false otherwise. + */ +export function isUUID(uuid: string): boolean; diff --git a/types/lil-uuid/lil-uuid-tests.ts b/types/lil-uuid/lil-uuid-tests.ts new file mode 100644 index 0000000000..8b39216e67 --- /dev/null +++ b/types/lil-uuid/lil-uuid-tests.ts @@ -0,0 +1,4 @@ +import * as lil from 'lil-uuid'; + +lil.uuid(); +lil.isUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479'); diff --git a/types/lil-uuid/tsconfig.json b/types/lil-uuid/tsconfig.json new file mode 100644 index 0000000000..889bd07cca --- /dev/null +++ b/types/lil-uuid/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lil-uuid-tests.ts" + ] +} diff --git a/types/lil-uuid/tslint.json b/types/lil-uuid/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lil-uuid/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f1685af04f..a0eaef941c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -7,7 +7,8 @@ // AJ Richardson , // Junyoung Clare Jang , // e-cloud , -// Georgii Dolzhykov +// Georgii Dolzhykov , +// Jack Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -580,64 +581,77 @@ declare namespace _ { * @param iteratee The iteratee invoked per element. * @returns Returns the new array of filtered values. */ - differenceBy( - array: List | null | undefined, - values?: List, - iteratee?: ValueIteratee - ): T[]; + differenceBy( + array: List | null | undefined, + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.differenceBy + */ + differenceBy( + array: List | null | undefined, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): T1[]; /** * @see _.differenceBy */ differenceBy( array: List | null | undefined, - values1: List, - values2: List, - iteratee?: ValueIteratee - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1: List, - values2: List, - values3: List, - iteratee?: ValueIteratee - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1: List, - values2: List, - values3: List, - values4: List, - iteratee?: ValueIteratee - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - values1: List, - values2: List, - values3: List, - values4: List, - values5: List, - iteratee?: ValueIteratee - ): T[]; - - /** - * @see _.differenceBy - */ - differenceBy( - array: List | null | undefined, - ...values: Array | ValueIteratee> + ...values: Array> ): T[]; } @@ -645,64 +659,77 @@ declare namespace _ { /** * @see _.differenceBy */ - differenceBy( - this: LoDashImplicitWrapper | null | undefined>, - values?: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): LoDashImplicitWrapper; /** * @see _.differenceBy */ differenceBy( this: LoDashImplicitWrapper | null | undefined>, - values1: List, - values2: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashImplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashImplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - values4: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashImplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - values4: List, - values5: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashImplicitWrapper | null | undefined>, - ...values: Array | ValueIteratee> + ...values: Array> ): LoDashImplicitWrapper; } @@ -710,64 +737,77 @@ declare namespace _ { /** * @see _.differenceBy */ - differenceBy( - this: LoDashExplicitWrapper | null | undefined>, - values?: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.differenceBy + */ + differenceBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + values3: List, + values4: List, + values5: List, + ...values: Array | ValueIteratee> + ): LoDashExplicitWrapper; /** * @see _.differenceBy */ differenceBy( this: LoDashExplicitWrapper | null | undefined>, - values1: List, - values2: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashExplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashExplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - values4: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashExplicitWrapper | null | undefined>, - values1: List, - values2: List, - values3: List, - values4: List, - values5: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; - - /** - * @see _.differenceBy - */ - differenceBy( - this: LoDashExplicitWrapper | null | undefined>, - ...values: Array | ValueIteratee> + ...values: Array> ): LoDashExplicitWrapper; } @@ -789,18 +829,38 @@ declare namespace _ { * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ - differenceWith( - array: List | null | undefined, - values?: List, - comparator?: Comparator - ): T[]; + differenceWith( + array: List | null | undefined, + values: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + values1: List, + values2: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.differenceWith + */ + differenceWith( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): T1[]; /** * @see _.differenceWith */ differenceWith( array: List | null | undefined, - ...values: Array | Comparator>, + ...values: Array> ): T[]; } @@ -808,18 +868,38 @@ declare namespace _ { /** * @see _.differenceWith */ - differenceWith( - this: LoDashImplicitWrapper | null | undefined>, - values?: List, - comparator?: Comparator - ): LoDashImplicitWrapper; + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashImplicitWrapper; /** * @see _.differenceWith */ differenceWith( this: LoDashImplicitWrapper | null | undefined>, - ...values: Array | Comparator>, + ...values: Array> ): LoDashImplicitWrapper; } @@ -827,18 +907,38 @@ declare namespace _ { /** * @see _.differenceWith */ - differenceWith( - this: LoDashExplicitWrapper | null | undefined>, - values?: List, - comparator?: Comparator - ): LoDashExplicitWrapper; + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.differenceWith + */ + differenceWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): LoDashExplicitWrapper; /** * @see _.differenceWith */ differenceWith( this: LoDashExplicitWrapper | null | undefined>, - ...values: Array | Comparator>, + ...values: Array> ): LoDashExplicitWrapper; } @@ -1134,7 +1234,7 @@ declare namespace _ { */ findIndex( array: List | null | undefined, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1145,7 +1245,7 @@ declare namespace _ { */ findIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1156,7 +1256,7 @@ declare namespace _ { */ findIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1182,7 +1282,7 @@ declare namespace _ { */ findLastIndex( array: List | null | undefined, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1193,7 +1293,7 @@ declare namespace _ { */ findLastIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1204,7 +1304,7 @@ declare namespace _ { */ findLastIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1580,18 +1680,38 @@ declare namespace _ { * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ - intersectionBy( - array: List | null | undefined, - values?: List, - iteratee?: ValueIteratee - ): T[]; + intersectionBy( + array: List | null, + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array: List | null, + values1: List, + values2: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.intersectionBy + */ + intersectionBy( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): T1[]; /** * @see _.intersectionBy */ intersectionBy( - array: List | null | undefined, - ...values: Array | ValueIteratee>, + array?: List | null, + ...values: Array> ): T[]; } @@ -1599,18 +1719,38 @@ declare namespace _ { /** * @see _.intersectionBy */ - intersectionBy( - this: LoDashImplicitWrapper | null | undefined>, - values?: List, - iteratee?: ValueIteratee - ): LoDashImplicitWrapper; + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): LoDashImplicitWrapper; /** * @see _.intersectionBy */ intersectionBy( this: LoDashImplicitWrapper | null | undefined>, - ...values: Array | ValueIteratee>, + ...values: Array> ): LoDashImplicitWrapper; } @@ -1618,18 +1758,38 @@ declare namespace _ { /** * @see _.intersectionBy */ - intersectionBy( - this: LoDashExplicitWrapper | null | undefined>, - values?: List, - iteratee?: ValueIteratee - ): LoDashExplicitWrapper; + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + iteratee: ValueIteratee + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionBy + */ + intersectionBy( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | ValueIteratee> + ): LoDashExplicitWrapper; /** * @see _.intersectionBy */ intersectionBy( this: LoDashExplicitWrapper | null | undefined>, - ...values: Array | ValueIteratee>, + ...values: Array> ): LoDashExplicitWrapper; } @@ -1647,22 +1807,43 @@ declare namespace _ { * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] */ - intersectionWith( - array: List | null | undefined, - values?: List, - comparator?: Comparator - ): T[]; + intersectionWith( + array: List | null | undefined, + values: List, + comparator: Comparator2 + ): T1[]; /** - * @see _.differenceWith + * @see _.intersectionWith + */ + intersectionWith( + array: List | null | undefined, + values1: List, + values2: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.intersectionWith + */ + intersectionWith( + array: List | null | undefined, + values1: List, + values2: List, + ...values: Array | Comparator2> + ): T1[]; + + /** + * @see _.intersectionWith */ intersectionWith( - array: List | null | undefined, - ...values: Array | Comparator>, + array?: List | null, + ...values: Array> ): T[]; } @@ -1670,18 +1851,38 @@ declare namespace _ { /** * @see _.intersectionWith */ - intersectionWith( - this: LoDashImplicitWrapper | null | undefined>, - values?: List, - comparator?: Comparator - ): LoDashImplicitWrapper; + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashImplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashImplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2>, + ): LoDashImplicitWrapper; /** * @see _.intersectionWith */ intersectionWith( this: LoDashImplicitWrapper | null | undefined>, - ...values: Array | Comparator>, + ...values: Array> ): LoDashImplicitWrapper; } @@ -1689,18 +1890,38 @@ declare namespace _ { /** * @see _.intersectionWith */ - intersectionWith( - this: LoDashExplicitWrapper | null | undefined>, - values?: List, - comparator?: Comparator - ): LoDashExplicitWrapper; + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + comparator: Comparator2 + ): LoDashExplicitWrapper; + + /** + * @see _.intersectionWith + */ + intersectionWith( + this: LoDashExplicitWrapper | null | undefined>, + values1: List, + values2: List, + ...values: Array | Comparator2>, + ): LoDashExplicitWrapper; /** * @see _.intersectionWith */ intersectionWith( this: LoDashExplicitWrapper | null | undefined>, - ...values: Array | Comparator>, + ...values: Array> ): LoDashExplicitWrapper; } @@ -2038,27 +2259,43 @@ declare namespace _ { values?: List, iteratee?: ValueIteratee ): List; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: T1[], + values: List, + iteratee: ValueIteratee + ): T1[]; + + /** + * @see _.pullAllBy + */ + pullAllBy( + array: List, + values: List, + iteratee: ValueIteratee + ): List; } - interface LoDashImplicitWrapper { + interface LoDashWrapper { /** * @see _.pullAllBy */ pullAllBy( - this: LoDashImplicitWrapper>, + this: LoDashWrapper>, values?: List, iteratee?: ValueIteratee ): this; - } - interface LoDashExplicitWrapper { /** * @see _.pullAllBy */ - pullAllBy( - this: LoDashExplicitWrapper>, - values?: List, - iteratee?: ValueIteratee + pullAllBy( + this: LoDashWrapper>, + values: List, + iteratee: ValueIteratee ): this; } @@ -2078,11 +2315,11 @@ declare namespace _ { * @returns Returns `array`. * @example * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); - * // => [{ 'x': 2 }] + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ pullAllWith( array: T[], @@ -2098,27 +2335,43 @@ declare namespace _ { values?: List, comparator?: Comparator ): List; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: T1[], + values: List, + comparator: Comparator2 + ): T1[]; + + /** + * @see _.pullAllWith + */ + pullAllWith( + array: List, + values: List, + comparator: Comparator2 + ): List; } - interface LoDashImplicitWrapper { + interface LoDashWrapper { /** * @see _.pullAllWith */ pullAllWith( - this: LoDashImplicitWrapper>, + this: LoDashWrapper>, values?: List, comparator?: Comparator ): this; - } - interface LoDashExplicitWrapper { /** * @see _.pullAllWith */ - pullAllWith( - this: LoDashExplicitWrapper>, - values?: List, - comparator?: Comparator + pullAllWith( + this: LoDashWrapper>, + values: List, + comparator: Comparator2 ): this; } @@ -2976,7 +3229,7 @@ declare namespace _ { */ uniqBy( array: string | null | undefined, - iteratee: StringIterator + iteratee: StringIterator ): string[]; /** @@ -2994,7 +3247,7 @@ declare namespace _ { */ uniqBy( this: LoDashImplicitWrapper, - iteratee: StringIterator + iteratee: StringIterator ): LoDashImplicitWrapper; /** @@ -3012,7 +3265,7 @@ declare namespace _ { */ uniqBy( this: LoDashExplicitWrapper, - iteratee: StringIterator + iteratee: StringIterator ): LoDashExplicitWrapper; /** @@ -3118,7 +3371,7 @@ declare namespace _ { */ sortedUniqBy( array: string | null | undefined, - iteratee: StringIterator + iteratee: StringIterator ): string[]; /** @@ -3136,7 +3389,7 @@ declare namespace _ { */ sortedUniqBy( this: LoDashImplicitWrapper, - iteratee: StringIterator + iteratee: StringIterator ): LoDashImplicitWrapper; /** @@ -3154,7 +3407,7 @@ declare namespace _ { */ sortedUniqBy( this: LoDashExplicitWrapper, - iteratee: StringIterator + iteratee: StringIterator ): LoDashExplicitWrapper; /** @@ -4062,6 +4315,14 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + countBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.countBy + */ countBy( collection: List | null | undefined, iteratee?: ListIteratee @@ -4085,6 +4346,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.countBy */ @@ -4111,6 +4380,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.countBy */ @@ -4226,7 +4503,7 @@ declare namespace _ { */ every( collection: List | null | undefined, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): boolean; /** @@ -4234,7 +4511,7 @@ declare namespace _ { */ every( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): boolean; /** @@ -4242,7 +4519,7 @@ declare namespace _ { */ every( collection: T | null | undefined, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): boolean; } @@ -4252,7 +4529,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): boolean; /** @@ -4260,7 +4537,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): boolean; /** @@ -4268,7 +4545,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -4278,7 +4555,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4286,7 +4563,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -4294,7 +4571,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -4320,7 +4597,7 @@ declare namespace _ { */ filter( collection: string | null | undefined, - predicate?: StringIterator + predicate?: StringIterator ): string[]; /** @@ -4336,7 +4613,7 @@ declare namespace _ { */ filter( collection: List | null | undefined, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): T[]; /** @@ -4352,7 +4629,7 @@ declare namespace _ { */ filter( collection: T | null | undefined, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): Array; } @@ -4362,7 +4639,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper, - predicate?: StringIterator + predicate?: StringIterator ): LoDashImplicitWrapper; /** @@ -4378,7 +4655,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -4394,7 +4671,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -4404,7 +4681,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper, - predicate?: StringIterator + predicate?: StringIterator ): LoDashExplicitWrapper; /** @@ -4420,7 +4697,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4436,7 +4713,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -4471,7 +4748,7 @@ declare namespace _ { */ find( collection: List | null | undefined, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4489,7 +4766,7 @@ declare namespace _ { */ find( collection: T | null | undefined, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4509,7 +4786,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4527,7 +4804,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4547,7 +4824,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4565,7 +4842,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4591,7 +4868,7 @@ declare namespace _ { */ findLast( collection: List | null | undefined, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4609,7 +4886,7 @@ declare namespace _ { */ findLast( collection: T | null | undefined, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4629,7 +4906,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): T | undefined; @@ -4647,7 +4924,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4667,7 +4944,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4685,7 +4962,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4705,6 +4982,13 @@ declare namespace _ { collection: List> | Dictionary> | NumericDictionary> | null | undefined ): T[]; + /** + * @see _.flatMap + */ + flatMap( + collection: object | null | undefined + ): any[]; + /** * @see _.flatMap */ @@ -4752,6 +5036,11 @@ declare namespace _ { */ flatMap(this: LoDashImplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashImplicitWrapper; + /** + * @see _.flatMap + */ + flatMap(): LoDashImplicitWrapper; + /** * @see _.flatMap */ @@ -4797,6 +5086,11 @@ declare namespace _ { */ flatMap(this: LoDashExplicitWrapper> | Dictionary> | NumericDictionary> | null | undefined>): LoDashExplicitWrapper; + /** + * @see _.flatMap + */ + flatMap(): LoDashExplicitWrapper; + /** * @see _.flatMap */ @@ -5421,7 +5715,7 @@ declare namespace _ { */ groupBy( collection: string | null | undefined, - iteratee?: StringIterator + iteratee?: StringIterator ): Dictionary; /** @@ -5455,7 +5749,7 @@ declare namespace _ { */ groupBy( this: LoDashImplicitWrapper, - iteratee?: StringIterator + iteratee?: StringIterator ): LoDashImplicitWrapper>; /** @@ -5489,7 +5783,7 @@ declare namespace _ { */ groupBy( this: LoDashExplicitWrapper, - iteratee?: StringIterator + iteratee?: StringIterator ): LoDashExplicitWrapper>; /** @@ -5579,9 +5873,17 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + keyBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.keyBy + */ keyBy( collection: List | null | undefined, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): Dictionary; /** @@ -5589,7 +5891,7 @@ declare namespace _ { */ keyBy( collection: T | null | undefined, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): Dictionary; /** @@ -5597,17 +5899,25 @@ declare namespace _ { */ keyBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): Dictionary; } interface LoDashImplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5615,7 +5925,7 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5623,17 +5933,25 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5641,7 +5959,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5649,7 +5967,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper>; } @@ -6440,7 +6758,7 @@ declare namespace _ { */ reject( collection: string | null | undefined, - predicate?: StringIterator + predicate?: StringIterator ): string[]; /** @@ -6448,7 +6766,7 @@ declare namespace _ { */ reject( collection: List | null | undefined, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): T[]; /** @@ -6456,7 +6774,7 @@ declare namespace _ { */ reject( collection: T | null | undefined, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): Array; } @@ -6466,7 +6784,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper, - predicate?: StringIterator + predicate?: StringIterator ): LoDashImplicitWrapper; /** @@ -6474,7 +6792,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -6482,7 +6800,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -6492,7 +6810,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper, - predicate?: StringIterator + predicate?: StringIterator ): LoDashExplicitWrapper; /** @@ -6500,7 +6818,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -6508,7 +6826,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -6722,7 +7040,7 @@ declare namespace _ { */ some( collection: List | null | undefined, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): boolean; /** @@ -6730,7 +7048,7 @@ declare namespace _ { */ some( collection: T | null | undefined, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): boolean; /** @@ -6738,7 +7056,7 @@ declare namespace _ { */ some( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -6748,7 +7066,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): boolean; /** @@ -6756,7 +7074,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): boolean; /** @@ -6764,7 +7082,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -6774,7 +7092,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIteratee + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -6782,7 +7100,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper, - predicate?: ObjectIteratee + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -6790,7 +7108,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIteratee + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -6906,7 +7224,7 @@ declare namespace _ { */ orderBy( collection: List | null | undefined, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): T[]; @@ -6924,7 +7242,7 @@ declare namespace _ { */ orderBy( collection: T | null | undefined, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): Array; @@ -6942,7 +7260,7 @@ declare namespace _ { */ orderBy( collection: NumericDictionary | null | undefined, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): T[]; @@ -6962,7 +7280,7 @@ declare namespace _ { */ orderBy( this: LoDashImplicitWrapper | null | undefined>, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashImplicitWrapper; @@ -6980,7 +7298,7 @@ declare namespace _ { */ orderBy( this: LoDashImplicitWrapper, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashImplicitWrapper>; @@ -6998,7 +7316,7 @@ declare namespace _ { */ orderBy( this: LoDashImplicitWrapper | null | undefined>, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashImplicitWrapper; @@ -7018,7 +7336,7 @@ declare namespace _ { */ orderBy( this: LoDashExplicitWrapper | null | undefined>, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashExplicitWrapper; @@ -7036,7 +7354,7 @@ declare namespace _ { */ orderBy( this: LoDashExplicitWrapper, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashExplicitWrapper>; @@ -7054,7 +7372,7 @@ declare namespace _ { */ orderBy( this: LoDashExplicitWrapper | null | undefined>, - iteratees?: Many>, + iteratees?: Many>, orders?: Many ): LoDashExplicitWrapper; @@ -7823,6 +8141,7 @@ declare namespace _ { flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): () => any; // 1-argument first function flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; @@ -7830,6 +8149,7 @@ declare namespace _ { flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1) => R5; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1) => R6; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1) => R7; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1) => any; // 2-argument first function flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2) => R2; flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2) => R3; @@ -7837,6 +8157,7 @@ declare namespace _ { flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2) => R5; flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2) => R6; flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2) => R7; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2) => any; // 3-argument first function flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3) => R2; flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3) => R3; @@ -7844,6 +8165,7 @@ declare namespace _ { flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3) => R5; flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3) => R6; flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3) => R7; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3) => any; // 4-argument first function flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; @@ -7851,8 +8173,16 @@ declare namespace _ { flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; - // generic function - flow(...funcs: Array any>>): (...args: any[]) => any; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4) => any; + // any-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): (a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any; + flow(funcs: Array any>>): (...args: any[]) => any; } interface LoDashImplicitWrapper { @@ -7866,6 +8196,7 @@ declare namespace _ { flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<() => R5>; flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<() => R6>; flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<() => R7>; + flow(this: LoDashImplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<() => any>; // 1-argument first function flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1) => R2>; flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1) => R3>; @@ -7873,6 +8204,7 @@ declare namespace _ { flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1) => R5>; flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1) => R6>; flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1) => any>; // 2-argument first function flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2) => R2>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2) => R3>; @@ -7880,6 +8212,7 @@ declare namespace _ { flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2) => R5>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2) => R6>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2) => any>; // 3-argument first function flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; @@ -7887,6 +8220,7 @@ declare namespace _ { flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => any>; // 4-argument first function flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; @@ -7894,8 +8228,16 @@ declare namespace _ { flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; - // generic function - flow(...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => any>; + // any-argument first function + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7>; + flow(this: LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any>; + flow(this: LoDashImplicitWrapper<(...args: any[]) => any>, funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; } interface LoDashExplicitWrapper { @@ -7909,6 +8251,7 @@ declare namespace _ { flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<() => R5>; flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<() => R6>; flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<() => R7>; + flow(this: LoDashExplicitWrapper<() => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<() => any>; // 1-argument first function flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1) => R2>; flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1) => R3>; @@ -7916,6 +8259,7 @@ declare namespace _ { flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1) => R5>; flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1) => R6>; flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1) => any>; // 2-argument first function flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2) => R2>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2) => R3>; @@ -7923,6 +8267,7 @@ declare namespace _ { flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2) => R5>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2) => R6>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2) => any>; // 3-argument first function flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; @@ -7930,6 +8275,7 @@ declare namespace _ { flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => any>; // 4-argument first function flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; @@ -7937,8 +8283,16 @@ declare namespace _ { flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; - // generic function - flow(...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => any>; + // any-argument first function + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R2>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R3>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R4>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R5>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R6>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R7>; + flow(this: LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => R1>, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7, ...funcs: Array any>>): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4, ...args: any[]) => any>; + flow(this: LoDashExplicitWrapper<(...args: any[]) => any>, funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.flowRight @@ -7950,21 +8304,150 @@ declare namespace _ { * @param funcs Functions to invoke. * @return Returns the new function. */ - flowRight(...funcs: Array any>>): (...args: any[]) => any; + // 0-argument first function + flowRight(f2: (a: R1) => R2, f1: () => R1): () => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): () => R7; + // 1-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): (a1: A1) => R7; + // 2-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): (a1: A1, a2: A2) => R7; + // 3-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): (a1: A1, a2: A2, a3: A3) => R7; + // 4-argument first function + flowRight(f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + // any-argument first function + flowRight(f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R2; + flowRight(f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R3; + flowRight(f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R4; + flowRight(f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R5; + flowRight(f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R6; + flowRight(f7: (a: R6) => R7, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): (...args: any[]) => R7; + flowRight(f7: (a: any) => any, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): (...args: any[]) => any; + flowRight(funcs: Array any>>): (...args: any[]) => any; } interface LoDashImplicitWrapper { /** * @see _.flowRight */ - flowRight(...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + // 0-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: () => R1): LoDashImplicitWrapper<() => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashImplicitWrapper<() => R7>; + // 1-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashImplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashImplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // any-argument first function + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R2>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R3>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R4>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R5>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R6>; + flowRight(this: LoDashImplicitWrapper<(a: R1) => R2>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashImplicitWrapper<(...args: any[]) => R7>; + flowRight(this: LoDashImplicitWrapper<(a: any) => any>, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; + flowRight(this: LoDashImplicitWrapper<(a: any) => any>, funcs: Array any>>): LoDashImplicitWrapper<(...args: any[]) => any>; } interface LoDashExplicitWrapper { /** * @see _.flowRight */ - flowRight(...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + // 0-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: () => R1): LoDashExplicitWrapper<() => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: () => R1): LoDashExplicitWrapper<() => R7>; + // 1-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1) => R1): LoDashExplicitWrapper<(a1: A1) => R7>; + // 2-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2) => R7>; + // 3-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3) => R7>; + // 4-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R2) => R3>, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R3) => R4>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R4) => R5>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R5) => R6>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R6) => R7>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1): LoDashExplicitWrapper<(a1: A1, a2: A2, a3: A3, a4: A4) => R7>; + // any-argument first function + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R2>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R3>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R4>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R5>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R6>; + flowRight(this: LoDashExplicitWrapper<(a: R1) => R2>, f6: (a: R5) => R6, f5: (a: R4) => R5, f4: (a: R3) => R4, f3: (a: R2) => R3, f2: (a: R1) => R2, f1: (...args: any[]) => R1): LoDashExplicitWrapper<(...args: any[]) => R7>; + flowRight(this: LoDashExplicitWrapper<(a: any) => any>, f6: (a: any) => any, f5: (a: any) => any, f4: (a: any) => any, f3: (a: any) => any, f2: (a: any) => any, f1: () => any, ...funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; + flowRight(this: LoDashExplicitWrapper<(a: any) => any>, funcs: Array any>>): LoDashExplicitWrapper<(...args: any[]) => any>; } //_.memoize @@ -8880,14 +9363,16 @@ declare namespace _ { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): boolean; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): boolean; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } interface LoDashExplicitWrapper { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): LoDashExplicitWrapper; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): LoDashExplicitWrapper; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } type CondPair = [(val: T) => boolean, (val: T) => R] @@ -9510,12 +9995,12 @@ declare namespace _ { //_.isFunction interface LoDashStatic { /** - * Checks if value is classified as a Function object. + * Checks if value is a callable function. * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ - isFunction(value?: any): value is ((...args: any[]) => any) | Function; + isFunction(value: any): value is (...args: any[]) => any; } interface LoDashImplicitWrapper { @@ -10158,7 +10643,7 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isWeakMap(value?: any): value is WeakMap; + isWeakMap(value?: any): value is WeakMap; } interface LoDashImplicitWrapper { @@ -10183,7 +10668,7 @@ declare namespace _ { * @param value The value to check. * @returns Returns true if value is correctly classified, else false. */ - isWeakSet(value?: any): value is WeakSet; + isWeakSet(value?: any): value is WeakSet; } interface LoDashImplicitWrapper { @@ -10288,7 +10773,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashImplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10300,7 +10785,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashExplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashExplicitWrapper>; } //_.toPlainObject @@ -13908,13 +14393,29 @@ declare namespace _ { * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ - pick( + pick( + object: T | null | undefined, + ...props: Array> + ): Pick; + + /** + * @see _.pick + */ + pick( object: T | null | undefined, ...props: PropertyPath[] - ): PartialObject; + ): PartialDeep; } interface LoDashImplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + /** * @see _.pick */ @@ -13925,6 +14426,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + /** * @see _.pick */ @@ -16571,14 +17080,17 @@ declare namespace _ { uniqueId(): LoDashExplicitWrapper; } + type NotVoid = {} | null | undefined; type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; - type ListIteratee = ListIterator | string | [string, any] | PartialDeep; + type ListIteratee = ListIterator | string | [string, any] | PartialDeep; + type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; - type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type DictionaryIterator = ObjectIterator, TResult>; @@ -16586,7 +17098,8 @@ declare namespace _ { type DictionaryIteratorTypeGuard = ObjectIteratorTypeGuard, S>; type NumericDictionaryIterator = (value: T, key: number, collection: NumericDictionary) => TResult; - type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; type StringIterator = (char: string, index: number, string: string) => TResult; @@ -16600,9 +17113,10 @@ declare namespace _ { type MemoVoidArrayIterator = (acc: TResult, curr: T, index: number, arr: T[]) => void; type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; - type ValueIteratee = ((value: T) => any) | string | [string, any] | PartialDeep; - type ValueKeyIteratee = ((value: T, key: string) => any) | string | [string, any] | PartialDeep; + type ValueIteratee = ((value: T) => NotVoid) | string | [string, any] | PartialDeep; + type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | string | [string, any] | PartialDeep; type Comparator = (a: T, b: T) => boolean; + type Comparator2 = (a: T1, b: T2) => boolean; type PropertyName = string | number | symbol; type PropertyPath = Many; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index c7fb313dec..dbefb1abaa 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4,86 +4,19 @@ interface IFoodOrganic { name: string; organic: boolean; } - -interface IFoodType { - name: string; - type: string; -} - -interface IFoodCombined { - name: string; - organic: boolean; - type: string; -} - -interface IStoogesQuote { - name: string; - quotes: string[]; -} - interface IStoogesAge { name: string; age: number; } -interface IStoogesCombined { - name: string; - age: number; - quotes: string[]; -} - -interface IKey { - dir: string; - code: number; -} - -interface IDictionary { - [index: string]: T; -} - const foodsOrganic: IFoodOrganic[] = [ { name: 'banana', organic: true }, { name: 'beet', organic: false }, ]; -const foodsType: IFoodType[] = [ - { name: 'apple', type: 'fruit' }, - { name: 'banana', type: 'fruit' }, - { name: 'beet', type: 'vegetable' } -]; -const foodsCombined: IFoodCombined[] = [ - { 'name': 'apple', 'organic': false, 'type': 'fruit' }, - { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } -]; - -const stoogesQuotes: IStoogesQuote[] = [ - { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } -]; const stoogesAges: IStoogesAge[] = [ { 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 } ]; -const stoogesAgesDict: IDictionary = { - first: { 'name': 'moe', 'age': 40 }, - second: { 'name': 'larry', 'age': 50 } -}; -const stoogesCombined: IStoogesCombined[] = [ - { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } -]; - -const keys: IKey[] = [ - { 'dir': 'left', 'code': 97 }, - { 'dir': 'right', 'code': 100 } -]; - -class Dog { - constructor(public name: string) { } - - bark() { - // Woof - } -} let result: any; @@ -297,6 +230,7 @@ namespace TestDifferenceBy { { let result: TResult[]; + result = _.differenceBy(array); result = _.differenceBy(array, arrayParam); result = _.differenceBy(array, listParam, arrayParam); result = _.differenceBy(array, arrayParam, listParam, arrayParam); @@ -304,27 +238,28 @@ namespace TestDifferenceBy { result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam); result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _.differenceBy(array, arrayParam, iteratee); - result = _.differenceBy(array, listParam, arrayParam, iteratee); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, iteratee); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, iteratee); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _.differenceBy(array, arrayParam, 'a'); - result = _.differenceBy(array, listParam, arrayParam, 'a'); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, 'a'); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, 'a'); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); result = _.differenceBy(array, arrayParam, {a: 1}); result = _.differenceBy(array, listParam, arrayParam, {a: 1}); result = _.differenceBy(array, arrayParam, listParam, arrayParam, {a: 1}); result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, {a: 1}); result = _.differenceBy(array, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _.differenceBy(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _.differenceBy(list); result = _.differenceBy(list, listParam); result = _.differenceBy(list, arrayParam, listParam); result = _.differenceBy(list, listParam, arrayParam, listParam); @@ -332,26 +267,26 @@ namespace TestDifferenceBy { result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam); result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _.differenceBy(list, listParam, iteratee); - result = _.differenceBy(list, arrayParam, listParam, iteratee); - result = _.differenceBy(list, listParam, arrayParam, listParam, iteratee); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, iteratee); + result = _.differenceBy(list, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _.differenceBy(list, listParam, 'a'); - result = _.differenceBy(list, arrayParam, listParam, 'a'); - result = _.differenceBy(list, listParam, arrayParam, listParam, 'a'); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, 'a'); + result = _.differenceBy(list, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); result = _.differenceBy(list, listParam, {a: 1}); result = _.differenceBy(list, arrayParam, listParam, {a: 1}); result = _.differenceBy(list, listParam, arrayParam, listParam, {a: 1}); result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, {a: 1}); result = _.differenceBy(list, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _.differenceBy(list, arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); } { @@ -364,26 +299,26 @@ namespace TestDifferenceBy { result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam); result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _(array).differenceBy(arrayParam, iteratee); - result = _(array).differenceBy(listParam, arrayParam, iteratee); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, iteratee); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, iteratee); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).differenceBy(arrayParam, 'a'); - result = _(array).differenceBy(listParam, arrayParam, 'a'); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, 'a'); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, 'a'); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); result = _(array).differenceBy(arrayParam, {a: 1}); result = _(array).differenceBy(listParam, arrayParam, {a: 1}); result = _(array).differenceBy(arrayParam, listParam, arrayParam, {a: 1}); result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); result = _(array).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); result = _(list).differenceBy(listParam); result = _(list).differenceBy(arrayParam, listParam); @@ -392,26 +327,26 @@ namespace TestDifferenceBy { result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam); result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _(list).differenceBy(listParam, iteratee); - result = _(list).differenceBy(arrayParam, listParam, iteratee); - result = _(list).differenceBy(listParam, arrayParam, listParam, iteratee); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, iteratee); + result = _(list).differenceBy(listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).differenceBy(listParam, 'a'); - result = _(list).differenceBy(arrayParam, listParam, 'a'); - result = _(list).differenceBy(listParam, arrayParam, listParam, 'a'); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, 'a'); + result = _(list).differenceBy(listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); result = _(list).differenceBy(listParam, {a: 1}); result = _(list).differenceBy(arrayParam, listParam, {a: 1}); result = _(list).differenceBy(listParam, arrayParam, listParam, {a: 1}); result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); result = _(list).differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); } { @@ -424,26 +359,26 @@ namespace TestDifferenceBy { result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam); result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); - result = _(array).chain().differenceBy(arrayParam, iteratee); - result = _(array).chain().differenceBy(listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, iteratee); - result = _(array).chain().differenceBy(arrayParam, 'a'); - result = _(array).chain().differenceBy(listParam, arrayParam, 'a'); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, 'a'); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, 'a'); result = _(array).chain().differenceBy(arrayParam, {a: 1}); result = _(array).chain().differenceBy(listParam, arrayParam, {a: 1}); result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, {a: 1}); result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, {a: 1}); result = _(array).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); - result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); + result = _(array).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, {a: 1}); result = _(list).chain().differenceBy(listParam); result = _(list).chain().differenceBy(arrayParam, listParam); @@ -452,26 +387,262 @@ namespace TestDifferenceBy { result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam); result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam); - result = _(list).chain().differenceBy(listParam, iteratee); - result = _(list).chain().differenceBy(arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, iteratee); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, iteratee); - result = _(list).chain().differenceBy(listParam, 'a'); - result = _(list).chain().differenceBy(arrayParam, listParam, 'a'); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, 'a'); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, 'a'); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, 'a'); result = _(list).chain().differenceBy(listParam, {a: 1}); result = _(list).chain().differenceBy(arrayParam, listParam, {a: 1}); result = _(list).chain().differenceBy(listParam, arrayParam, listParam, {a: 1}); result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, {a: 1}); result = _(list).chain().differenceBy(listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); - result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + result = _(list).chain().differenceBy(arrayParam, listParam, arrayParam, listParam, arrayParam, listParam, {a: 1}); + } + + { + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + interface T3 { + a: string; + b: boolean; + } + interface T4 { + a: string; + b: any[]; + } + + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 = { a: 'a', b: 30 }; + const t3: T3 = { a: 'a', b: true }; + const t4: T4 = { a: 'a', b: [] }; + + // $ExpectType T1[] + _.differenceBy([t1], [t2], 'name'); + // $ExpectType T1[] + _.differenceBy([t1], [t2], (value) => { + value; // $ExpectType T1 | T2 + return 0; + }); + // $ExpectType T1[] + _.differenceBy([t1], [t2, t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType (T1 | T2)[] + _.differenceBy([t1, t2], [t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType T1[] + _.differenceBy([t1], [t2], [t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType T1[] + _.differenceBy([t1], [t2], [t3], [t4], (value) => { + value; // $ExpectType T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType T1[] + _.differenceBy([t1], [t2], [t3], [t4], [''], (value) => { + value; // $ExpectType string | T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType T1[] + _.differenceBy([t1], [t2], [t3], [t4], [''], [42], (value) => { + value; // $ExpectType string | number | T1 | T2 | T3 | T4 + return 0; + }); + + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], 'name'); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return 0; + }); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2, t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashImplicitWrapper<(T1 | T2)[]> + _([t1, t2]).differenceBy([t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], [t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], [t3], [t4], (value) => { + value; // $ExpectType T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], [t3], [t4], [''], (value) => { + value; // $ExpectType string | T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceBy([t2], [t3], [t4], [''], [42], (value) => { + value; // $ExpectType string | number | T1 | T2 | T3 | T4 + return 0; + }); + + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], 'name'); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return 0; + }); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2, t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashExplicitWrapper<(T1 | T2)[]> + _.chain([t1, t2]).differenceBy([t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], [t3], (value) => { + value; // $ExpectType T1 | T2 | T3 + return 0; + }); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], [t3], [t4], (value) => { + value; // $ExpectType T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], [t3], [t4], [''], (value) => { + value; // $ExpectType string | T1 | T2 | T3 | T4 + return 0; + }); + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceBy([t2], [t3], [t4], [''], [42], (value) => { + value; // $ExpectType string | number | T1 | T2 | T3 | T4 + return 0; + }); + } +} + +// _.differenceWith +{ + let array: TResult[] | null | undefined = [] as any; + let list: _.List | null | undefined = [] as any; + let arrayParam: TResult[] = []; + let listParam: _.List = []; + let comparator = (a: TResult, b: TResult) => true; + + { + // $ExpectType TResult[] + _.differenceWith(array); + // $ExpectType TResult[] + _.differenceWith(array, arrayParam); + // $ExpectType TResult[] + _.differenceWith(array, listParam, arrayParam); + // $ExpectType TResult[] + _.differenceWith(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); + + // $ExpectType TResult[] + _.differenceWith(array, arrayParam, comparator); + // $ExpectType TResult[] + _.differenceWith(array, listParam, arrayParam, comparator); + // $ExpectType TResult[] + _.differenceWith(array, listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, comparator); + } + + { + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(arrayParam); + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(listParam, arrayParam); + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(arrayParam, listParam, arrayParam); + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); + + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(arrayParam, comparator); + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(listParam, arrayParam, comparator); + // $ExpectType LoDashImplicitWrapper + _(array).differenceWith(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, comparator); + } + + { + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(arrayParam); + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(listParam, arrayParam); + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(arrayParam, listParam, arrayParam); + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam); + + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(arrayParam, comparator); + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(listParam, arrayParam, comparator); + // $ExpectType LoDashExplicitWrapper + _.chain(array).differenceWith(listParam, arrayParam, listParam, arrayParam, listParam, arrayParam, comparator); + } + + { + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 | undefined = any; + + // $ExpectType T1[] + _.differenceWith([t1], [t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 | undefined + return true; + }); + + // $ExpectType LoDashImplicitWrapper + _([t1]).differenceWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 | undefined + return true; + }); + + // $ExpectType LoDashExplicitWrapper + _.chain([t1]).differenceWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 | undefined + return true; + }); } } @@ -1214,6 +1385,197 @@ namespace TestIntersection { } } +// _.intersectionBy +{ + let array: TResult[] = [] as any; + let list: _.List = [] as any; + let arrayParam: TResult[] = [] as any; + let listParam: _.List = [] as any; + + // $ExpectType TResult[] + result = _.intersectionBy(array, list); + // $ExpectType TResult[] + result = _.intersectionBy(list, array, list); + // $ExpectType TResult[] + result = _.intersectionBy(array, list, 'a'); + // $ExpectType TResult[] + result = _.intersectionBy(array, list, { a: 42 }); + // $ExpectType TResult[] + result = _.intersectionBy(list, array, list, { a: 42 }); + // $ExpectType TResult[] + result = _.intersectionBy(array, list, ['a', 42]); + // $ExpectType TResult[] + result = _.intersectionBy(array, list, (value) => { + value; // $ExpectType TResult + return 0; + }); + // $ExpectType TResult[] + result = _.intersectionBy(list, array, list, (value) => { + value; // $ExpectType TResult + return 0; + }); + + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(arrayParam); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(listParam, arrayParam); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(list, 'a'); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(list, { a: 42 }); + // $ExpectType LoDashImplicitWrapper + result = _(list).intersectionBy(array, list, { a: 42 }); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(list, ['a', 42]); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionBy(list, (value) => { + value; // $ExpectType TResult + return ""; + }); + // $ExpectType LoDashImplicitWrapper + result = _(list).intersectionBy(array, list, (value) => { + value; // $ExpectType TResult + return 1; + }); + + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(arrayParam); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(listParam, arrayParam); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(list, 'a'); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(list, { a: 42 }); + // $ExpectType LoDashExplicitWrapper + result = _.chain(list).intersectionBy(array, list, { a: 42 }); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(list, ['a', 42]); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionBy(list, (value) => { + value; // $ExpectType TResult + return false; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain(list).intersectionBy(array, list, (value) => { + value; // $ExpectType TResult + return null; + }); + + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 = { a: 'a', b: 1 }; + // $ExpectType T1[] + result = _.intersectionBy([t1], [t2], (value) => { + value; // $ExpectType T1 | T2 + return undefined; + }); + // $ExpectType LoDashImplicitWrapper + result = _([t1]).intersectionBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return {}; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain([t1]).intersectionBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return {}; + }); +} + +// _.intersectionWith +{ + let array: TResult[] = [] as any; + let list: _.List = [] as any; + let arrayParam: TResult[] = [] as any; + let listParam: _.List = [] as any; + + // $ExpectType TResult[] + result = _.intersectionWith(array, list); + // $ExpectType TResult[] + result = _.intersectionWith(list, array, list); + // $ExpectType TResult[] + result = _.intersectionWith(array, list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType TResult[] + result = _.intersectionWith(list, array, list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionWith(arrayParam); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionWith(listParam, arrayParam); + // $ExpectType LoDashImplicitWrapper + result = _(array).intersectionWith(list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType LoDashImplicitWrapper + result = _(list).intersectionWith(array, list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionWith(arrayParam); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionWith(listParam, arrayParam); + // $ExpectType LoDashExplicitWrapper + result = _.chain(array).intersectionWith(list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain(list).intersectionWith(array, list, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 = { a: 'a', b: 1 }; + // $ExpectType T1[] + result = _.intersectionWith([t1], [t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); + // $ExpectType LoDashImplicitWrapper + result = _([t1]).intersectionWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain([t1]).intersectionWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); +} + // _.join namespace TestJoin { let array = [1, 2]; @@ -1487,6 +1849,265 @@ namespace TestPullAt { } } +// _.pullAll +{ + let array: TResult[] = any; + let list: _.List = any; + let values: _.List = any; + + // $ExpectType TResult[] + _.pullAll(array); + // $ExpectType TResult[] + _.pullAll(array, values); + // $ExpectType ArrayLike + _.pullAll(list); + // $ExpectType ArrayLike + _.pullAll(list, values); + + // $ExpectType LoDashImplicitWrapper + _(array).pullAll(); + // $ExpectType LoDashImplicitWrapper + _(array).pullAll(values); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAll(); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAll(values); + + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAll(); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAll(values); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAll(); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAll(values); +} + +// _.pullAllBy +{ + let array: TResult[] = any; + let list: _.List = any; + let values: _.List = any; + + // $ExpectType TResult[] + _.pullAllBy(array); + // $ExpectType TResult[] + _.pullAllBy(array, values); + // $ExpectType TResult[] + _.pullAllBy(array, values, 'a'); + // $ExpectType TResult[] + _.pullAllBy(array, values, { a: 42 }); + // $ExpectType TResult[] + _.pullAllBy(array, values, ['a', 42]); + // $ExpectType TResult[] + _.pullAllBy(array, values, (value) => { + value; // $ExpectType TResult + return []; + }); + // $ExpectType ArrayLike + _.pullAllBy(list); + // $ExpectType ArrayLike + _.pullAllBy(list, values); + // $ExpectType ArrayLike + _.pullAllBy(list, values, 'a'); + // $ExpectType ArrayLike + _.pullAllBy(list, values, { a: 42 }); + // $ExpectType ArrayLike + _.pullAllBy(list, values, ['a', 42]); + // $ExpectType ArrayLike + _.pullAllBy(list, values, (value) => { + value; // $ExpectType TResult + return () => {}; + }); + + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(values); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(values, 'a'); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(values, { a: 42 }); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(values, ['a', 42]); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllBy(values, (value) => { + value; // $ExpectType TResult + return 0; + }); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(values); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(values, 'a'); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(values, { a: 42 }); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(values, ['a', 42]); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllBy(values, (value) => { + value; // $ExpectType TResult + return 0; + }); + + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(values); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(values, 'a'); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(values, { a: 42 }); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(values, ['a', 42]); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllBy(values, (value) => { + value; // $ExpectType TResult + return 0; + }); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(values); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(values, 'a'); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(values, { a: 42 }); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(values, ['a', 42]); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllBy(values, (value) => { + value; // $ExpectType TResult + return 0; + }); + + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 = { a: 'a', b: 1 }; + // $ExpectType T1[] + result = _.pullAllBy([t1], [t2], (value) => { + value; // $ExpectType T1 | T2 + return ""; + }); + // $ExpectType LoDashImplicitWrapper + result = _([t1]).pullAllBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return ""; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain([t1]).pullAllBy([t2], (value) => { + value; // $ExpectType T1 | T2 + return ""; + }); +} + +// _.pullAllWith +{ + let array: TResult[] = any; + let list: _.List = any; + let values: _.List = any; + + // $ExpectType TResult[] + _.pullAllWith(array); + // $ExpectType TResult[] + _.pullAllWith(array, values); + // $ExpectType TResult[] + _.pullAllWith(array, values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType ArrayLike + _.pullAllWith(list); + // $ExpectType ArrayLike + _.pullAllWith(list, values); + // $ExpectType ArrayLike + _.pullAllWith(list, values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + // $ExpectType LoDashImplicitWrapper + _(array).pullAllWith(); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllWith(values); + // $ExpectType LoDashImplicitWrapper + _(array).pullAllWith(values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllWith(); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllWith(values); + // $ExpectType LoDashImplicitWrapper> + _(list).pullAllWith(values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllWith(); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllWith(values); + // $ExpectType LoDashExplicitWrapper + _.chain(array).pullAllWith(values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllWith(); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllWith(values); + // $ExpectType LoDashExplicitWrapper> + _.chain(list).pullAllWith(values, (a, b) => { + a; // $ExpectType TResult + b; // $ExpectType TResult + return true; + }); + + interface T1 { + a: string; + b: string; + } + interface T2 { + a: string; + b: number; + } + const t1: T1 = { a: 'a', b: 'b' }; + const t2: T2 = { a: 'a', b: 1 }; + // $ExpectType T1[] + result = _.pullAllWith([t1], [t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); + // $ExpectType LoDashImplicitWrapper + result = _([t1]).pullAllWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); + // $ExpectType LoDashExplicitWrapper + result = _.chain([t1]).pullAllWith([t2], (a, b) => { + a; // $ExpectType T1 + b; // $ExpectType T2 + return true; + }); +} + // _.remove namespace TestRemove { let array: TResult[] = []; @@ -3903,9 +4524,9 @@ namespace TestFilter { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -4321,6 +4942,21 @@ namespace TestFlatMap { result = _(objNumericDictionary).chain().flatMap(['a', 42]); result = _(objNumericDictionary).chain().flatMap({a: 42}); } + + { + interface SampleObject { + bar: number; + foo: string[]; + } + const obj: SampleObject = { + bar: 1, + foo: [''], + }; + + const result1: Array = _.flatMap(obj); + const result2: _.LoDashImplicitWrapper> = _(obj).flatMap(); + const result3: _.LoDashExplicitWrapper> = _.chain(obj).flatMap(); + } } // _.flatMapDeep @@ -4504,7 +5140,7 @@ namespace TestFlatMapDepth { let listIterator: (value: number|number[], index: number, collection: _.List) => _.ListOfRecursiveArraysOrValues = (a, b, c) =>[ 1]; - let dictionaryIterator: (value: number|number[], key: number, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; + let dictionaryIterator: (value: number|number[], key: string, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; let numericDictionaryIterator: (value: number|number[], key: number, collection: _.NumericDictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; @@ -5073,8 +5709,8 @@ namespace TestGroupBy { { let result: _.Dictionary; - result = _.groupBy(''); - result = _.groupBy('', stringIterator); + result = _.groupBy(''); + result = _.groupBy('', stringIterator); } { @@ -5206,16 +5842,16 @@ namespace TestKeyBy { let dictionary: _.Dictionary | null | undefined = obj; let numericDictionary: _.NumericDictionary | null | undefined = obj; - let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; - let listIterator: (value: SampleObject, index: number, collection: _.List) => any = (value: SampleObject, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any = (value: SampleObject, key: string, collection: _.Dictionary) => 1; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any = (value: SampleObject, key: number, collection: _.NumericDictionary) => 1; + let stringIterator = (value: string, index: number, collection: string) => "a"; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 1; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => Symbol.name; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => "a"; { let result: _.Dictionary; - result = _.keyBy('abcd'); - result = _.keyBy('abcd', stringIterator); + result = _.keyBy('abcd'); + result = _.keyBy('abcd', stringIterator); } { @@ -5761,9 +6397,9 @@ namespace TestReject { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -6215,12 +6851,11 @@ result = _(foodsOrganic).sortBy('organic', (food) => food.name, namespace TestorderBy { type SampleObject = {a: number; b: string; c: boolean}; - let array: SampleObject[] | null | undefined = [] as any; - let list: _.List | null | undefined = [] as any; - let obj: any = {}; - let numericDictionary: _.NumericDictionary | null | undefined = obj; - let dictionary: _.Dictionary | null | undefined = obj; - let orders: boolean|string|(boolean|string)[] = true as any; + const array: SampleObject[] | null | undefined = any; + const list: _.List | null | undefined = any; + const numericDictionary: _.NumericDictionary | null | undefined = any; + const dictionary: _.Dictionary | null | undefined = any; + const orders: boolean|string|Array = any; { let iteratees: (value: string) => any|((value: string) => any)[] = (value) => 1; @@ -6231,7 +6866,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => 1; + const iteratees: ((value: SampleObject) => _.NotVoid)|string|_.PartialDeep|Array<((value: SampleObject) => _.NotVoid)|string|_.PartialDeep> = any; let result: SampleObject[]; result = _.orderBy(array, iteratees); @@ -6256,7 +6891,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; + const iteratees: ((value: SampleObject) => _.NotVoid)|string|_.PartialDeep|Array<((value: SampleObject) => _.NotVoid)|string|_.PartialDeep> = any; let result: _.LoDashImplicitArrayWrapper; result = _(array).orderBy(iteratees); @@ -6279,7 +6914,7 @@ namespace TestorderBy { } { - let iteratees: (value: SampleObject) => any|string|{a: number}|((value: SampleObject) => any|string|{a: number})[] = (value) => ""; + const iteratees: ((value: SampleObject) => _.NotVoid)|string|_.PartialDeep|Array<((value: SampleObject) => _.NotVoid)|string|_.PartialDeep> = any; let result: _.LoDashExplicitArrayWrapper; result = _(array).chain().orderBy(iteratees); @@ -6822,28 +7457,28 @@ namespace TestFlow { { let result: (m: number, n: number) => number; - result = _.flow(Fn1, Fn2); - result = _.flow(Fn1, Fn1, Fn2); - result = _.flow(Fn1, Fn1, Fn1, Fn2); + result = _.flow(Fn2, Fn1); + result = _.flow(Fn2, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn1, Fn1); result = _.flow([Fn1, Fn1, Fn1, Fn2]); } { let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).flow(Fn2); - result = _(Fn1).flow(Fn1, Fn2); - result = _(Fn1).flow(Fn1, Fn1, Fn2); - result = _(Fn1).flow([Fn1, Fn1, Fn2]); + result = _(Fn2).flow(Fn1); + result = _(Fn2).flow(Fn1, Fn1); + result = _(Fn2).flow(Fn1, Fn1, Fn1); + result = _(Fn2).flow([Fn1, Fn1, Fn1]); } { let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; - result = _(Fn1).chain().flow(Fn2); - result = _(Fn1).chain().flow(Fn1, Fn2); - result = _(Fn1).chain().flow(Fn1, Fn1, Fn2); - result = _(Fn1).chain().flow([Fn1, Fn1, Fn2]); + result = _(Fn2).chain().flow(Fn1); + result = _(Fn2).chain().flow(Fn1, Fn1); + result = _(Fn2).chain().flow(Fn1, Fn1, Fn1); + result = _(Fn2).chain().flow([Fn1, Fn1, Fn1]); } } @@ -7965,9 +8600,7 @@ namespace TestIsEqual { // _.isEqualWith namespace TestIsEqualWith { - let customizer = (value: any, other: any, indexOrKey: number|string|undefined, parent: any, otherParent: any, stack: any) => { - return value ? undefined : true; - }; + let customizer = (value: any, other: any, indexOrKey: number|string|symbol|undefined, parent: any, otherParent: any, stack: any) => true; { let result: boolean; @@ -8060,7 +8693,11 @@ namespace TestIsFunction { let result: Function = value; } else { - let result: number = value; + let result: number|Function = value; + } + + if (_.isFunction(any)) { + any(); } } @@ -8167,7 +8804,7 @@ namespace TestIsMatch { // _.isMatchWith namespace TestIsMatchWith { - let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string) => true; + let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; let result: boolean; @@ -8537,12 +9174,10 @@ namespace TestIsUndefined { // _.isWeakMap namespace TestIsWeakMap { { - interface Obj { a: string }; - - let value: number|WeakMap = 0; + let value: number | WeakMap = 0; if (_.isWeakMap(value)) { - let result: WeakMap = value; + let result: WeakMap = value; } else { let result: number = value; @@ -8570,10 +9205,10 @@ namespace TestIsWeakMap { // _.isWeakSet namespace TestIsWeakSet { { - let value: number|WeakSet = 0; + let value: number | WeakSet = 0; - if (_.isWeakSet(value)) { - let result: WeakSet = value; + if (_.isWeakSet(value)) { + let result: WeakSet = value; } else { let result: number = value; @@ -11183,6 +11818,12 @@ namespace TestPick { result = _.pick(obj, ['b', 1], 0, 'a'); } + { + let result: Pick; + result = _.pick(obj, 'a', 'b'); + result = _.pick(obj, ['a' as 'a', 'b' as 'b']); + } + { let result: _.LoDashImplicitWrapper>; @@ -11191,6 +11832,13 @@ namespace TestPick { result = _(obj).pick(['b', 1], 0, 'a'); } + { + let result: _.LoDashImplicitWrapper>; + + result = _(obj).pick('a', 'b'); + result = _(obj).pick(['a' as 'a', 'b' as 'b']); + } + { let result: _.LoDashExplicitWrapper>; @@ -11198,6 +11846,13 @@ namespace TestPick { result = _(obj).chain().pick(0, 'a'); result = _(obj).chain().pick(['b', 1], 0, 'a'); } + + { + let result: _.LoDashExplicitWrapper>; + + result = _(obj).chain().pick('a', 'b'); + result = _(obj).chain().pick(['a' as 'a', 'b' as 'b']); + } } // _.pickBy @@ -12629,8 +13284,8 @@ namespace TestIdentity { } { - let input: {} | null | undefined = any; - _.identity(input); // $ExpectType {} | null | undefined + let input: { a: number; } | null | undefined = any; + _.identity(input); // $ExpectType { a: number; } | null | undefined _.identity(); // $ExpectType undefined } } diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..8bd56c0b87 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/lolex/index.d.ts b/types/lolex/index.d.ts index de08060883..68f87793d9 100644 --- a/types/lolex/index.d.ts +++ b/types/lolex/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for lolex 1.5 +// Type definitions for lolex 2.1 // Project: https://github.com/sinonjs/lolex -// Definitions by: Wim Looman , Josh Goldberg +// Definitions by: Wim Looman +// Josh Goldberg +// Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -34,7 +36,7 @@ type BrowserClock = LolexClock; type NodeClock = LolexClock & { /** * Mimicks process.hrtime(). - * + * * @param prevTime Previous system time to calculate time elapsed. * @returns High resolution real time as [seconds, nanoseconds]. */ @@ -49,7 +51,7 @@ type Clock = BrowserClock | NodeClock; /** * Names of clock methods that may be faked by install. */ -type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date"; +type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime"; /** * Controls the flow of time. @@ -67,39 +69,41 @@ export interface LolexClock { /** * Schedules a callback to be fired once timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait to run the callback. + * @param args Any extra arguments to pass to the callback. * @returns Time identifier for cancellation. */ - setTimeout(callback: () => any, timeout: number): TTimerId; + setTimeout(callback: () => any, timeout: number, ...args: any[]): TTimerId; /** * Clears a timer, as long as it was created using setTimeout. - * + * * @param id Timer ID or object. */ clearTimeout(id: TTimerId): void; /** * Schedules a callback to be fired every time timeout milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @param timeout How many ticks to wait between callbacks. + * @param args Any extra arguments to pass to the callback. * @returns Time identifier for cancellation. */ - setInterval(callback: () => any, timeout: number): TTimerId; + setInterval(callback: () => any, timeout: number, ...args: any[]): TTimerId; /** * Clears a timer, as long as it was created using setInterval. - * + * * @param id Timer ID or object. */ clearInterval(id: TTimerId): void; /** * Schedules the callback to be fired once 0 milliseconds have ticked by. - * + * * @param callback Callback to be fired. * @remarks You'll still have to call clock.tick() for the callback to fire. * @remarks If called during a tick the callback won't fire until 1 millisecond has ticked by. @@ -108,11 +112,16 @@ export interface LolexClock { /** * Clears a timer, as long as it was created using setImmediate. - * + * * @param id Timer ID or object. */ clearImmediate(id: TTimerId): void; + /** + * Simulates process.nextTick(); + */ + nextTick(callback: () => void): void; + /** * Advances the clock to the the moment of the first scheduled timer, firing it. */ @@ -120,14 +129,14 @@ export interface LolexClock { /** * Advance the clock, firing callbacks if necessary. - * + * * @param time How many ticks to advance by. */ tick(time: number | string): void; /** * Runs all pending timers until there are none remaining. - * + * * @remarks If new timers are added while it is executing they will be run as well. */ runAll(): void; @@ -140,7 +149,7 @@ export interface LolexClock { /** * Simulates a user changing the system clock. - * + * * @param now New system time. * @remarks This affects the current time but it does not in itself cause timers to fire. */ @@ -155,7 +164,7 @@ export interface LolexClock { /** * Creates a clock. - * + * * @param now Current time for the clock. * @param loopLimit Maximum number of timers that will be run when calling runAll() * before assuming that we have an infinite loop and throwing an error @@ -165,23 +174,47 @@ export interface LolexClock { */ export declare function createClock(now?: number | Date, loopLimit?: number): TClock; -/** - * Creates a clock and installs it globally. - * - * @param now Current time for the clock, as with lolex.createClock(). - * @param toFake Names of methods that should be faked. - * @type TClock Type of clock to create. - * @usage lolex.install(["setTimeout", "clearTimeout"]); - */ -export declare function install(now?: number | Date, toFake?: FakeMethod[]): TClock; + +export interface LolexInstallOpts { + /** + * Installs lolex onto the specified target context (default: global) + */ + target?: any; + + /** + * Installs lolex with the specified unix epoch (default: 0) + */ + now?: number; + + /** + * An array with explicit function names to hijack. When not set, lolex will automatically fake all methods except nextTick + * e.g., lolex.install({ toFake: ["setTimeout", "nextTick"]}) will fake only setTimeout and nextTick + */ + toFake?: FakeMethod[]; + + /** + * The maximum number of timers that will be run when calling runAll() (default: 1000) + */ + loopLimit?: number; + + /** + * Tells lolex to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by + * 20ms for every 20ms change in the real system time) (default: false) + */ + shouldAdvanceTime?: boolean; + + /** + * Relevant only when using with shouldAdvanceTime: true. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change + * in the real system time (default: 20) + */ + advanceTimeDelta?: number; +} /** - * Creates a clock and installs it onto the context object. - * - * @param context Context to install the clock onto. + * Creates a clock and installs it globally. + * * @param now Current time for the clock, as with lolex.createClock(). * @param toFake Names of methods that should be faked. * @type TClock Type of clock to create. - * @usage lolex.install(context, ["setTimeout", "clearTimeout"]); */ -export declare function install(context?: any, now?: number | Date, toFake?: FakeMethod[]): TClock; +export declare function install(opts?: LolexInstallOpts): TClock; diff --git a/types/lolex/lolex-tests.ts b/types/lolex/lolex-tests.ts index 876e4280c5..95b6a2be78 100644 --- a/types/lolex/lolex-tests.ts +++ b/types/lolex/lolex-tests.ts @@ -16,25 +16,14 @@ lolex.createClock(new Date()); lolex.createClock(7, 9001); lolex.createClock(new Date(), 9001); -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install(7); -lolex.install(new Date()); -lolex.install(7, ["setTimeout"]); -lolex.install(new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); - -lolex.install({}, 7); -lolex.install({}, new Date()); -lolex.install({}, 7, ["setTimeout"]); -lolex.install({}, new Date(), ["setTimeout"]); +lolex.install({ + advanceTimeDelta: 20, + loopLimit: 10, + now: 0, + shouldAdvanceTime: true, + target: {}, + toFake: ["setTimeout", "nextTick", "hrtime"] +}); const browserNow: number = browserClock.now; const browserDate: Date = new browserClock.Date(); @@ -80,5 +69,7 @@ nodeClock.setSystemTime(); nodeClock.setSystemTime(7); nodeClock.setSystemTime(new Date()); +nodeClock.nextTick(() => undefined); + browserClock.uninstall(); nodeClock.uninstall(); diff --git a/types/loopback-boot/index.d.ts b/types/loopback-boot/index.d.ts index 258800981b..5dc5fa7f60 100644 --- a/types/loopback-boot/index.d.ts +++ b/types/loopback-boot/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/strongloop/loopback-boot // Definitions by: Andres D Jimenez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /************************************************ * * diff --git a/types/lozad/index.d.ts b/types/lozad/index.d.ts index eb0213f6c3..6257c47043 100644 --- a/types/lozad/index.d.ts +++ b/types/lozad/index.d.ts @@ -1,25 +1,25 @@ -// Type definitions for lozad 1.0 +// Type definitions for lozad 1.1 // Project: https://github.com/ApoorvSaxena/lozad.js // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface Option { - rootMargin?: string; - threshold?: number; - load?(element: HTMLElement | HTMLCanvasElement): void; -} - -interface Observer { - observe(): void; -} - -declare function lozad(selector?: string, options?: Option): Observer; - declare namespace lozad { + interface Option { + rootMargin?: string; + threshold?: number; + load?(element: HTMLElement | HTMLCanvasElement): void; + } + + interface Observer { + observe(): void; + } + const prototype: { }; } +declare function lozad(selector?: string, options?: lozad.Option): lozad.Observer; + export as namespace lozad; export = lozad; diff --git a/types/lusca/index.d.ts b/types/lusca/index.d.ts new file mode 100644 index 0000000000..8527ef3411 --- /dev/null +++ b/types/lusca/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for lusca 1.5 +// Project: https://github.com/krakenjs/lusca#readme +// Definitions by: Corbin Crutchley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require('express'); + +declare function lusca(options?: lusca.LuscaOptions): express.RequestHandler; + +declare namespace lusca { + /*~ Documentation declares that: + *~ Setting any value to false will disable it. + */ + interface LuscaOptions { + csrf?: csrfOptions | boolean; + csp?: cspOptions | false; + xframe?: string | false; + p3p?: string | false; + hsts?: hstsOptions | false; + xssProtection?: xssProtectionOptions | boolean; + nosniff?: boolean; + referrerPolicy?: string | false; + } + + interface cspOptions { + policy?: string | object | Array; + reportOnly?: boolean; + reportUri?: string; + styleNonce?: boolean; + scriptNonce?: boolean; + } + + interface hstsOptions { + maxAge?: number; + includeSubDomains?: boolean; + preload?: boolean; + } + + type csrfOptions = csrfOptionsAngular | csrfOptionsNonAngular; + + interface csrfOptionsAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + options?: object; + }; + angular: true; + } + + interface csrfOptionsNonAngular { + key?: string; + secret?: string; + impl?: () => any; + cookie?: string | { + name: string; + options?: object; + }; + angular?: false; + } + + interface xssProtectionOptions { + enabled?: boolean; + mode?: string; + } + + function csrf(options?: csrfOptions): express.RequestHandler; + function csp(options?: cspOptions): express.RequestHandler; + function xframe(value: string): express.RequestHandler; + function p3p(value: string): express.RequestHandler; + function hsts(options?: hstsOptions): express.RequestHandler; + function xssProtection(options?: xssProtectionOptions | true): express.RequestHandler; + function nosniff(): express.RequestHandler; + function referrerPolicy(value: string): express.RequestHandler; +} + +export = lusca; diff --git a/types/lusca/lusca-tests.ts b/types/lusca/lusca-tests.ts new file mode 100644 index 0000000000..8a74ec5e8a --- /dev/null +++ b/types/lusca/lusca-tests.ts @@ -0,0 +1,24 @@ +import express = require('express'); +import lusca = require('lusca'); + +const app = express(); + +app.use(lusca({ + csrf: true, + csp: { policy: "referrer no-referrer"}, + xframe: 'SAMEORIGIN', + p3p: 'ABCDEF', + hsts: {maxAge: 31536000, includeSubDomains: true, preload: true}, + xssProtection: true, + nosniff: true, + referrerPolicy: 'same-origin' +})); + +app.use(lusca.csrf()); +app.use(lusca.csp({policy: [{ "img-src": "'self' http:" }, "block-all-mixed-content"], reportOnly: false})); +app.use(lusca.xframe('SAMEORIGIN')); +app.use(lusca.p3p('ABCDEF')); +app.use(lusca.hsts({ maxAge: 31536000 })); +app.use(lusca.xssProtection(true)); +app.use(lusca.nosniff()); +app.use(lusca.referrerPolicy('same-origin')); diff --git a/types/lusca/tsconfig.json b/types/lusca/tsconfig.json new file mode 100644 index 0000000000..ede7926c1c --- /dev/null +++ b/types/lusca/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lusca-tests.ts" + ] +} diff --git a/types/lusca/tslint.json b/types/lusca/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lusca/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/main-bower-files/tsconfig.json b/types/main-bower-files/tsconfig.json index a5555d9521..bde61fa6db 100644 --- a/types/main-bower-files/tsconfig.json +++ b/types/main-bower-files/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/make-dir/index.d.ts b/types/make-dir/index.d.ts index a47b86dfac..1805280240 100644 --- a/types/make-dir/index.d.ts +++ b/types/make-dir/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Ika // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// import * as fs from 'fs'; diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 6be9a465ef..ddaafced3d 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.40.1 +// Type definitions for Mapbox GL JS v0.41.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -901,7 +901,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; metadata?: any; ref?: string; diff --git a/types/mapbox/index.d.ts b/types/mapbox/index.d.ts index 187004fb6d..334d644e21 100644 --- a/types/mapbox/index.d.ts +++ b/types/mapbox/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.mapbox.com/mapbox.js/ // Definitions by: Maxime Fabre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Leaflet from "leaflet"; diff --git a/types/markerclustererplus/index.d.ts b/types/markerclustererplus/index.d.ts index 3277d1ba64..1485971e4c 100644 --- a/types/markerclustererplus/index.d.ts +++ b/types/markerclustererplus/index.d.ts @@ -85,7 +85,6 @@ declare class ClusterIcon extends google.maps.OverlayView { /** * A cluster icon. * - * @extends google.maps.OverlayView * @param cluster The cluster with which the icon is to be associated. * @param [styles] An array of {@link ClusterIconStyle} defining the cluster icons * to use for various cluster sizes. @@ -378,7 +377,6 @@ interface MarkerClustererOptions { declare class MarkerClusterer extends google.maps.OverlayView { /** * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}. - * @extends google.maps.OverlayView * @param map The Google map to attach to. * @param [markers] The markers to be added to the cluster. * @param [options] The optional parameters. diff --git a/types/material-ui-datatables/index.d.ts b/types/material-ui-datatables/index.d.ts new file mode 100644 index 0000000000..3a8eab86f1 --- /dev/null +++ b/types/material-ui-datatables/index.d.ts @@ -0,0 +1,119 @@ +// Type definitions for material-ui-datatables 0.18 +// Project: https://github.com/hyojin/material-ui-datatables#readme +// Definitions by: Ravi L. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; + +export interface Column { + /** The element key */ + key?: string; + /** Style for column */ + style?: React.CSSProperties; + /** Label */ + label?: string; + /** Cell tooltip */ + tooltip?: string; + /** If the column is sortable */ + sortable?: boolean; + /** Align right */ + alignRight?: boolean; + /** Class name to use */ + className?: string; + /** + * Render function. Given the value extracted + * from the row; and the row also. Can return JSX content. + * @param value - the extracted value from data + * @param row - the data object representing this row + * @returns Any react node (JSX compatible return) + */ + render?: (value: any, row: any) => any; +} + +export interface DataTableProps { + /** Table title */ + title: string; + /** React Style object for the title */ + titleStyle: React.CSSProperties; + /** Filter hint text */ + filterHintText: string; + /** If the header should be fixed */ + fixedHeader: boolean; + /** If the footer should be fixed */ + fixedFooter: boolean; + /** React Style object applied to footer toolbar */ + footerToolbarStyle: React.CSSProperties; + /** To display striped rows in the table */ + stripedRows: boolean; + /** Display a hover in the row under the mouse */ + showRowHover: boolean; + /** If the table rows are select-able */ + selectable: boolean; + /** If multiple table rows are select-able */ + multiSelectable: boolean; + /** Adds a select all button */ + enableSelectAll: boolean; + /** If clicking away de-selects all */ + deselectOnClickaway: boolean; + /** Show check-boxes for selected rows */ + showCheckboxes: boolean; + /** The hight of the table */ + height: any; + /** Shows a header toolbar */ + showHeaderToolbar: boolean; + /** Shows a footer toolbar */ + showFooterToolbar: boolean; + rowSize: number; + rowSizeLabel: string; + rowSizeList: number[]; + showRowSizeControls: boolean; + /** Override the pagination display, ie. "1 - 5 of 11" Return any React node or string */ + summaryLabelTemplate: (start: number, end: number, count: number) => any; + /** + * The column structure. + * ```let columns: Column[] = [{ + * key: 'bookName', + * label: 'Book Name & Author', + * render: (__value: any, book: any) => book.name + ' by ' book.author + * },``` + */ + columns: Column[]; + /** The array of objects used as data for the table */ + data: any[]; + page: number; + toolbarIconRight: any; + count: number; + /** React style object for the table tag */ + tableStyle: React.CSSProperties; + /** React style object for the tbody tag */ + tableBodyStyle: React.CSSProperties; + /** React style object for the th/td tag */ + tableHeaderColumnStyle: React.CSSProperties; + /** React style object for the th tag */ + tableHeaderStyle: React.CSSProperties; + /** React style object for the tr tag */ + tableRowStyle: React.CSSProperties; + /** React style object for the tr/td tag */ + tableRowColumnStyle: React.CSSProperties; + tableWrapperStyle: React.CSSProperties; + /** 'default' or 'filter', filter mode shows a search box to reduce visible rows */ + headerToolbarMode: "default" | "filter" | string; // BUG https://github.com/Microsoft/TypeScript/issues/11465 + /** The current filter value */ + filterValue: string; + /** Show the icon to turn on the filtering feature */ + showHeaderToolbarFilterIcon: boolean; + onRowSizeChange: (index: number, value: any) => void; + onSortOrderChange: (key: string, order: string) => void; + /** Callback when the cell is clicked. This callback is only active when selectable is false. */ + onCellClick: (rowIndex: number, columnIndex: number, row: any, columnValue: any, event: any) => void; + /** Similar to onCellClick, activated when the cell is double clicked. Fires even if rows are selectable. */ + onCellDoubleClick: (rowIndex: number, columnIndex: number, row: any, columnValue: any, event: any) => void; + /** Notification if the filter value changes */ + onFilterValueChange: (value: string) => void; + onNextPageClick: (event: any) => void; + onPreviousPageClick: (event: any) => void; + onRowSelection: (selectedRows: any) => void; +} + +export default class DataTable extends React.Component> { } diff --git a/types/material-ui-datatables/material-ui-datatables-tests.tsx b/types/material-ui-datatables/material-ui-datatables-tests.tsx new file mode 100644 index 0000000000..bea8635f59 --- /dev/null +++ b/types/material-ui-datatables/material-ui-datatables-tests.tsx @@ -0,0 +1,84 @@ +import * as React from 'react'; +import DataTable, { Column } from 'material-ui-datatables'; + +interface Book { + name: string; + author: string; +} + +const title = ''; +const titleStyle: React.CSSProperties = {}; +const filterHintText = ''; +const fixedHeader = false; +const fixedFooter = false; +const footerToolbarStyle: React.CSSProperties = {}; +const stripedRows = false; +const showRowHover = false; +const selectable = false; +const multiSelectable = false; +const enableSelectAll = false; +const deselectOnClickaway = false; +const showCheckboxes = false; +const height: any = {}; +const showHeaderToolbar = false; +const showFooterToolbar = false; +const rowSize = 1; +const rowSizeLabel = ''; +const rowSizeList: number[] = [1]; +const showRowSizeControls = false; +const summaryLabelTemplate: (start: number, end: number, count: number) => any = (start, end, count) => ""; +const columns: Column[] = [{ key: '', render: (value, row: Book) => "" }]; +const book: Book = { author: 'asdf', name: 'asdf' }; +const data: Book[] = [book]; +const page = 1; +const toolbarIconRight: any = {}; +const count = 1; +const tableStyle: React.CSSProperties = {}; +const tableBodyStyle: React.CSSProperties = {}; +const tableHeaderColumnStyle: React.CSSProperties = {}; +const tableHeaderStyle: React.CSSProperties = {}; +const tableRowColumnStyle: React.CSSProperties = {}; +const tableRowStyle: React.CSSProperties = {}; +const tableWrapperStyle: React.CSSProperties = {}; +const headerToolbarMode = 'filter'; +const filterValue = ''; +const showHeaderToolbarFilterIcon = false; + +const test = ( +); diff --git a/types/material-ui-datatables/tsconfig.json b/types/material-ui-datatables/tsconfig.json new file mode 100644 index 0000000000..805afdbb17 --- /dev/null +++ b/types/material-ui-datatables/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "jsx": "react", + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "material-ui-datatables-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/material-ui-datatables/tslint.json b/types/material-ui-datatables/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/material-ui-datatables/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/material-ui-pagination/material-ui-pagination-tests.tsx b/types/material-ui-pagination/material-ui-pagination-tests.tsx index 09246a2646..a7f85d8184 100644 --- a/types/material-ui-pagination/material-ui-pagination-tests.tsx +++ b/types/material-ui-pagination/material-ui-pagination-tests.tsx @@ -18,7 +18,7 @@ interface PagerState { class Pager extends React.Component<{}, PagerState> { constructor() { - super(); + super({}); this.state = { pageIndex: 0 }; diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 91bcef28d9..5ae63560cc 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -947,6 +947,7 @@ declare namespace __MaterialUI { export interface ChipProps { backgroundColor?: string; className?: string; + containerElement?: React.ReactNode | string; labelColor?: string; labelStyle?: React.CSSProperties; onRequestDelete?: React.TouchEventHandler; @@ -1439,6 +1440,7 @@ declare namespace __MaterialUI { hintText?: React.ReactNode; iconStyle?: React.CSSProperties; id?: string; + name?: string; labelStyle?: React.CSSProperties; multiple?: boolean; onBlur?: React.FocusEventHandler<{}>; diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 1034d47cad..ab1abc4577 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -3030,6 +3030,8 @@ const ChipExampleSimple = () => ( Blue Label Color UI Avatar Styled + String Container + {}}>ReactNode Container ); @@ -7002,7 +7004,7 @@ class BottomNavigationExample extends Component<{}, { index?: number }> { constructor() { - super(); + super({}); this.state = { index: 0 }; diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index 13b32c985d..a457c3ad1a 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -4,6 +4,7 @@ // Leon Yu // Sukhdeep Singh // Jean-Francois Cere +// Sebastien Cote // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -555,9 +556,17 @@ interface JQuery { * Collapsibles are accordion elements that expand when clicked on. * They allow you to hide content that is not immediately relevant to the user. * - * @param CollapsibleOptions options the collapsible options + * @param CollapsibleOptions | string options the collapsible options or the string "destroy" to destroy the collapsible */ - collapsible(options?: Materialize.CollapsibleOptions): JQuery; + collapsible(options?: Materialize.CollapsibleOptions | string): JQuery; + + /** + * Programmatically trigger an event on a selected index + * + * @param string method the string "open" or "close" to open or to close the collapsible element on specified index + * @param number index the element index to trigger "open" or "close" function + */ + collapsible(method: string, index: number): JQuery; /** * Tooltips are small, interactive, textual hints for mainly graphical elements. diff --git a/types/materialize-css/materialize-css-tests.ts b/types/materialize-css/materialize-css-tests.ts index 50586ab104..02d35c7f40 100644 --- a/types/materialize-css/materialize-css-tests.ts +++ b/types/materialize-css/materialize-css-tests.ts @@ -39,6 +39,8 @@ let collapseHtml = '