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/notNeededPackages.json b/notNeededPackages.json index 498e2e1c4a..c5173ffc24 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -330,6 +330,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/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/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/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index d2b458de7d..5d87946c3c 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -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) @@ -846,6 +917,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 +1139,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 +1154,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 +1164,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 +1181,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 +1252,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/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-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-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 9c0671601f..88a59bdd2a 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -707,7 +707,7 @@ class SampleDirective implements ng.IDirective { restrict = 'A'; name = 'doh'; - compile(templateElement: ng.IAugmentedJQuery) { + compile(templateElement: JQLite) { return { post: this.link }; @@ -723,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 }; @@ -741,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); @@ -869,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; @@ -916,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'; } }; @@ -1017,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' @@ -1098,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; @@ -1312,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/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/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/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/args/tsconfig.json b/types/args/tsconfig.json new file mode 100644 index 0000000000..d287417769 --- /dev/null +++ b/types/args/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", + "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/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..18f57af4ff 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -1,4106 +1,6560 @@ -// 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: 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: 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: PointLike; + + /** A Point representing the end of the Range. */ + end: PointLike; + + // 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(source: 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 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..57ca68a915 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; 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..c2eb8da77e 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,27 @@ var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; +/* API Gateway Event request context */ +str = apiGwEvtReqCtx.accountId; +str = apiGwEvtReqCtx.apiId; +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 +96,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..342d489d68 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -8,9 +8,35 @@ // 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; + 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 +47,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 +331,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/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index 75560d4e42..d39a4fd466 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,7 +182,7 @@ 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); 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/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/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/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/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/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/chart.js/index.d.ts b/types/chart.js/index.d.ts index ed4339f60f..ef9e8b0675 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -154,7 +154,7 @@ declare namespace Chart { responsiveAnimationDuration?: number; maintainAspectRatio?: boolean; events?: string[]; - onClick?(any?: any): any; + onClick?(event?: MouseEvent, activeElements?: Array<{}>): any; title?: ChartTitleOptions; legend?: ChartLegendOptions; tooltips?: ChartTooltipOptions; @@ -411,8 +411,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..511fce354d 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; diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index ca7b35bf0e..1d7c1ca651 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; } //////////////////// @@ -5126,7 +5138,7 @@ declare namespace chrome.runtime { actions?: { type: string; }[]; - conditions?: chrome.declarativeContent.PageStateMatcher[] + conditions?: chrome.declarativeContent.PageStateMatcherProperties[] }[]; externally_connectable?: { ids?: string[]; @@ -7018,8 +7030,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..150bc7e7a6 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. @@ -814,7 +814,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/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/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/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/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-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/cors/index.d.ts b/types/cors/index.d.ts index 6c1fc3e4c3..0a99217f1f 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 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/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..4093b696e9 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 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-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/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/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx index dae23b90ef..87172d9471 100644 --- a/types/draft-js/draft-js-tests.tsx +++ b/types/draft-js/draft-js-tests.tsx @@ -30,7 +30,7 @@ type SyntheticKeyboardEvent = React.KeyboardEvent<{}>; class RichEditorExample extends React.Component<{}, { editorState: EditorState }> { constructor() { - super(); + super({}); const sampleMarkup = 'Bold text, Italic text

' + @@ -182,9 +182,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) => { diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 088d083a7f..bf7c2bac71 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, 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/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/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/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/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/test/array-proxy.ts b/types/ember/test/array-proxy.ts index 280ab52ded..763034bbd0 100755 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,6 +21,7 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x: MyNewProxy = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); -assertType(x.get('firstObject')); -assertType(x.isNew); +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); +// TODO: type inference can't infer 'number', just '{}' +// x.get('firstObject'); // $ExpectType number | undefined +x.isNew; // $ExpectType boolean 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/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/index.d.ts b/types/enzyme/index.d.ts index 101215462f..2b679d5f7b 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -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); 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/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-ejs-layouts/index.d.ts b/types/express-ejs-layouts/index.d.ts index b9c87cf5c1..958cd158e2 100644 --- a/types/express-ejs-layouts/index.d.ts +++ b/types/express-ejs-layouts/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Soarez/express-ejs-layouts // Definitions by: Erik Mavrinac // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// 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/index.d.ts b/types/express-formidable/index.d.ts index 57342521c2..f2228d2b0f 100644 --- a/types/express-formidable/index.d.ts +++ b/types/express-formidable/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/noraesae/express-formidable // Definitions by: Torkild Dyvik Olsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { RequestHandler } from "express"; 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-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..9119c8497f 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,17 +809,13 @@ 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. @@ -883,165 +823,149 @@ interface Application extends IRouter, Express.Application { (req: Request, res: Response): 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/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/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/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/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/index.d.ts b/types/fs-extra/index.d.ts index 84548e48a4..934f6ce5e1 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -38,9 +38,10 @@ export function mkdirp(dir: string, callback: (err: Error | null) => 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, options?: WriteFileOptions | string): 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, callback: (err: Error | null) => 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; @@ -234,8 +235,8 @@ export function write(fd: number, buffer: Buffer, offset: number, length: number 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, options?: WriteFileOptions | string): Promise; +export function writeFile(file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: NodeJS.ErrnoException | null) => 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. @@ -280,15 +281,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/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..4adb7f88f2 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -67,16 +67,16 @@ let featureWithPolygon: GeoJSON.Feature = { }; let point: GeoJSON.Point = { - type: "Point", - coordinates: [100.0, 0.0] + type: "Point", + coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package let pointCoordinates: number[] = point.coordinates; let lineString: GeoJSON.LineString = { - type: "LineString", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + type: "LineString", + coordinates: [ [100.0, 0.0], [101.0, 1.0] ] }; let polygon: GeoJSON.Polygon = { @@ -112,7 +112,7 @@ let multiPolygon: GeoJSON.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]]] ] }; @@ -172,31 +172,31 @@ 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: { @@ -210,17 +210,41 @@ featureCollection = { // Allow access to custom properties const pt: GeoJSON.Feature = { - type: '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]; + +// Optional generic for properties + +interface TestProperty { + foo: "bar" | "baz"; + hello: string; +} + +const typedPropertiesFeature: GeoJSON.Feature = { + type: "Feature", + properties: { + foo: "bar", + hello: "world", + }, + geometry: { + type: "Point", + coordinates: [0, 0] + } +}; + +const typedPropertiesFeatureCollection: GeoJSON.FeatureCollection = { + type: "FeatureCollection", + features: [typedPropertiesFeature] +}; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index 9c55aa19c9..b916179fac 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,13 +1,15 @@ // Type definitions for GeoJSON Format Specification Revision 1.0 // Project: http://geojson.org/ // Definitions by: Jacob Bruun +// Arne Schubert // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace GeoJSON; /*** -* http://geojson.org/geojson-spec.html#geojson-objects -*/ + * http://geojson.org/geojson-spec.html#geojson-objects + */ export interface GeoJsonObject { type: string; bbox?: number[]; @@ -15,13 +17,13 @@ export interface GeoJsonObject { } /*** -* http://geojson.org/geojson-spec.html#positions -*/ + * http://geojson.org/geojson-spec.html#positions + */ export type Position = number[]; /*** -* http://geojson.org/geojson-spec.html#geometry-objects -*/ + * http://geojson.org/geojson-spec.html#geometry-objects + */ export interface DirectGeometryObject extends GeoJsonObject { coordinates: Position[][][] | Position[][] | Position[] | Position; } @@ -31,82 +33,82 @@ export interface DirectGeometryObject extends GeoJsonObject { export type GeometryObject = DirectGeometryObject | GeometryCollection; /*** -* http://geojson.org/geojson-spec.html#point -*/ + * http://geojson.org/geojson-spec.html#point + */ export interface Point extends DirectGeometryObject { - type: 'Point'; + type: "Point"; coordinates: Position; } /*** -* http://geojson.org/geojson-spec.html#multipoint -*/ + * http://geojson.org/geojson-spec.html#multipoint + */ export interface MultiPoint extends DirectGeometryObject { - type: 'MultiPoint'; + type: "MultiPoint"; coordinates: Position[]; } /*** -* http://geojson.org/geojson-spec.html#linestring -*/ + * http://geojson.org/geojson-spec.html#linestring + */ export interface LineString extends DirectGeometryObject { - type: 'LineString'; + type: "LineString"; coordinates: Position[]; } /*** -* http://geojson.org/geojson-spec.html#multilinestring -*/ + * http://geojson.org/geojson-spec.html#multilinestring + */ export interface MultiLineString extends DirectGeometryObject { - type: 'MultiLineString'; + type: "MultiLineString"; coordinates: Position[][]; } /*** -* http://geojson.org/geojson-spec.html#polygon -*/ + * http://geojson.org/geojson-spec.html#polygon + */ export interface Polygon extends DirectGeometryObject { - type: 'Polygon'; + type: "Polygon"; coordinates: Position[][]; } /*** -* http://geojson.org/geojson-spec.html#multipolygon -*/ + * http://geojson.org/geojson-spec.html#multipolygon + */ export interface MultiPolygon extends DirectGeometryObject { - type: 'MultiPolygon'; + type: "MultiPolygon"; coordinates: Position[][][]; } /*** -* http://geojson.org/geojson-spec.html#geometry-collection -*/ + * http://geojson.org/geojson-spec.html#geometry-collection + */ export interface GeometryCollection extends GeoJsonObject { - type: 'GeometryCollection'; + type: "GeometryCollection"; geometries: GeometryObject[]; } /*** -* https://tools.ietf.org/html/rfc7946#section-3.2 -*/ -export interface Feature extends GeoJsonObject { - type: 'Feature'; - geometry: T; - properties: any; + * https://tools.ietf.org/html/rfc7946#section-3.2 + */ +export interface Feature extends GeoJsonObject { + type: "Feature"; + geometry: G; + properties: P; id?: string | number; } /*** -* http://geojson.org/geojson-spec.html#feature-collection-objects -*/ -export interface FeatureCollection extends GeoJsonObject { - type: 'FeatureCollection'; - features: Array>; + * 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 -*/ + * http://geojson.org/geojson-spec.html#coordinate-reference-system-objects + */ export interface CoordinateReferenceSystem { type: string; properties: any; 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/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.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/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/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-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-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/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/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/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..3ce85ed9e2 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 @@ -5614,7 +5608,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 +6575,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/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/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-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-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/index.d.ts b/types/hystrixjs/index.d.ts index b11305c13b..865f2b3916 100644 --- a/types/hystrixjs/index.d.ts +++ b/types/hystrixjs/index.d.ts @@ -2,6 +2,7 @@ // 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"; 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/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/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/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/index.d.ts b/types/jasmine/index.d.ts index 900c235990..e4249f116e 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -2,8 +2,7 @@ // 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 diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index d1aad60716..2d3a4b3fa9 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -961,13 +961,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"); }); 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-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/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/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/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/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/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/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..ba7815ef54 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,7 +34,7 @@ declare module Router { export interface IRouterOptions { /** - * Router prefixes + * Router prefixes */ prefix?: string; /** 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..d46920bf07 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 =================== 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/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/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-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/index.d.ts b/types/leaflet/index.d.ts index b4c71d06f7..b1e7ead796 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -581,9 +581,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 +591,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 +614,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 +666,12 @@ 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 { +export class LayerGroup

    extends Layer { constructor(layers?: Layer[]); /** * 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,7 +725,7 @@ export class LayerGroup extends Layer { */ getLayerId(layer: Layer): number; - feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; + feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; } /** @@ -737,11 +737,11 @@ export function layerGroup(layers: Layer[]): 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 +765,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 +781,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 +795,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 +807,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 +820,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 +833,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 +872,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 +886,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 +896,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'; @@ -1457,8 +1452,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 +1465,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..fc84a78267 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,15 @@ 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"; 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..22cecf47e8 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 @@ -7823,6 +7824,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 +7832,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 +7840,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 +7848,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 +7856,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 +7879,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 +7887,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 +7895,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 +7903,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 +7911,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 +7934,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 +7942,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 +7950,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 +7958,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 +7966,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 +7987,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 @@ -9510,12 +9676,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 +10324,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 +10349,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 { @@ -13908,10 +14074,15 @@ declare namespace _ { * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ - pick( + pick( + object: T | null | undefined, + ...props: Array> + ): Pick; + + pick( object: T | null | undefined, ...props: PropertyPath[] - ): PartialObject; + ): PartialDeep; } interface LoDashImplicitWrapper { diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index c7fb313dec..05d0db4e27 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -6822,28 +6822,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]); } } @@ -8060,7 +8060,11 @@ namespace TestIsFunction { let result: Function = value; } else { - let result: number = value; + let result: number|Function = value; + } + + if (_.isFunction(any)) { + any(); } } @@ -8537,12 +8541,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 +8572,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 +11185,12 @@ namespace TestPick { result = _.pick(obj, ['b', 1], 0, 'a'); } + { + let result: Pick; + result = _.pick(obj, 'a', 'b'); + result = _.pick(obj, ['a', 'b']); + } + { let result: _.LoDashImplicitWrapper>; 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/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/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..22b5d1711f 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; 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 = '
      ' + $(collapseHtml).collapsible({ accordion: false, onClose: () => { alert('Closed'); } }); $(collapseHtml).collapsible({ accordion: true, onOpen: () => { alert('Opened'); } }); +$(collapseHtml).collapsible('destroy'); +$(collapseHtml).collapsible('open', 0); // Dialogs - Toasts Materialize.toast('I am a toast!', 4000); diff --git a/types/merge2/tsconfig.json b/types/merge2/tsconfig.json index aeb71329c3..e39e70032b 100644 --- a/types/merge2/tsconfig.json +++ b/types/merge2/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/meteor/server-render.d.ts b/types/meteor/server-render.d.ts index cbf814ed61..1695142ee4 100644 --- a/types/meteor/server-render.d.ts +++ b/types/meteor/server-render.d.ts @@ -7,10 +7,10 @@ declare module "meteor/server-render" { body?: string; htmlById?: { [key: string]: string }; maybeMadeChanges?: boolean; - appendToHead(html: string): void; - appendToBody(html: string): void; - appendToElementById(id: string, html: string): void; - renderIntoElementById(id: string, html: string): void; + appendToHead?(html: string): void; + appendToBody?(html: string): void; + appendToElementById?(id: string, html: string): void; + renderIntoElementById?(id: string, html: string): void; } function onPageLoad(sink: Sink): Promise | any; } diff --git a/types/microrouter/index.d.ts b/types/microrouter/index.d.ts index 052bd707d3..6d65adc8a1 100644 --- a/types/microrouter/index.d.ts +++ b/types/microrouter/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/pedronauck/micro-router#readme // Definitions by: Mathieu Dutour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/microsoft-sdk-soap/index.d.ts b/types/microsoft-sdk-soap/index.d.ts index ceba101e53..69c9d86c22 100644 --- a/types/microsoft-sdk-soap/index.d.ts +++ b/types/microsoft-sdk-soap/index.d.ts @@ -2,6 +2,7 @@ // Project: https://code.msdn.microsoft.com/SdkSoapjs-9b51b99a // Definitions by: Markus Mauch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from "q"; diff --git a/types/mixpanel/index.d.ts b/types/mixpanel/index.d.ts index fdb6721fab..4964a55c79 100644 --- a/types/mixpanel/index.d.ts +++ b/types/mixpanel/index.d.ts @@ -1,133 +1,615 @@ -// Type definitions for Mixpanel 2.13.0 +// Type definitions for Mixpanel 2.13 // Project: https://mixpanel.com/ // https://github.com/mixpanel/mixpanel-js // Definitions by: Knut Eirik Leira Hjelle +// Manduro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface Mixpanel -{ - people:Mixpanel.People; +interface Mixpanel { + people: Mixpanel.People; - init(token:string, config?:Mixpanel.Config, libraryName?:string):Mixpanel; + /** + * This function initializes a new instance of the Mixpanel tracking object. + * All new instances are added to the main mixpanel object as sub properties (such as + * mixpanel.library_name) and also returned by this function. To define a + * second instance on the page, you would call: + * + * mixpanel.init('new token', { your: 'config' }, 'library_name'); + * + * and use it like so: + * + * mixpanel.library_name.track(...); + * + * @param token Your Mixpanel API token + * @param config A dictionary of config options to override + * @param libraryName The name for the new mixpanel instance that you want created + */ + init(token: string, config?: Mixpanel.Config, libraryName?: string): Mixpanel; - push(item:any[]):void; + /** + * `push()` keeps the standard async-array-push + * behavior around after the lib is loaded. + * This is only useful for external integrations that + * do not wish to rely on our convenience methods + * (created in the snippet). + * + * ### Usage: + * mixpanel.push(['register', { a: 'b' }]); + * + * @param item A [function_name, args...] array to be executed + */ + push(item: any[]): void; - disable(events?:string[]):void; + /** + * Disable events on the Mixpanel object. If passed no arguments, + * this function disables tracking of any event. If passed an + * array of event names, those events will be disabled, but other + * events will continue to be tracked. + * + * Note: this function does not stop other mixpanel functions from + * firing, such as `register()` or `people.set()`. + * + * @param events An array of event names to disable + */ + disable(events?: string[]): void; - time_event(eventName:string):void; + /** + * Track an event. This is the most important and + * frequently used Mixpanel function. + * + * ### Usage: + * + * // track an event named 'Registered' + * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21}); + * + * To track link clicks or form submissions, see `track_links()` or `track_forms()`. + * + * @param eventName The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc. + * @param properties A set of properties to include with the event you're sending. These describe the user who did the event or details about the event itself. + * @param callback If provided, the callback function will be called after tracking the event. + */ + track(eventName: string, properties?: { [index: string]: any }, callback?: () => void): void; - track(eventName:string, params?:{[index:string]:any}, callback?:() => void):void; + /** + * Track clicks on a set of document elements. Selector must be a + * valid query. Elements must exist on the page at the time `track_links` is called. + * + * ### Usage: + * + * // track click for link id #nav + * mixpanel.track_links('#nav', 'Clicked Nav Link'); + * + * ### Notes: + * + * This function will wait up to 300 ms for the Mixpanel + * servers to respond. If they have not responded by that time + * it will head to the link without ensuring that your event + * has been tracked. To configure this timeout please see the + * `set_config()` documentation below. + * + * If you pass a function in as the properties argument, the + * function will receive the DOMElement that triggered the + * event as an argument. You are expected to return an object + * from the function; any properties defined on this object + * will be sent to mixpanel as event properties. + * + * @param querySelector A valid DOM query, element or jQuery-esque list + * @param eventName The name of the event to track + * @param properties A properties object or function that returns a dictionary of properties when passed a DOMElement + */ + track_links(querySelector: string, eventName: string, properties?: { [index: string]: any }): void; - track_links(querySelector:string, eventName:string, params?:{[index:string]:any}):void; + /** + * Track form submissions. Selector must be a valid query. + * + * ### Usage: + * + * // track submission for form id 'register' + * mixpanel.track_forms('#register', 'Created Account'); + * + * ### Notes: + * + * This function will wait up to 300 ms for the mixpanel + * servers to respond, if they have not responded by that time + * it will head to the link without ensuring that your event + * has been tracked. To configure this timeout please see the + * `set_config()` documentation below. + * + * If you pass a function in as the properties argument, the + * function will receive the `DOMElement` that triggered the + * event as an argument. You are expected to return an object + * from the function; any properties defined on this object + * will be sent to mixpanel as event properties. + * + * @param querySelector A valid DOM query, element or jQuery-esque list + * @param eventName The name of the event to track + * @param properties This can be a set of properties, or a function that returns a set of properties after being passed a DOMElement + */ + track_forms(querySelector: string, eventName: string, properties?: { [index: string]: any }): void; - track_forms(querySelector:string, eventName:string, params?:{[index:string]:any}):void; + /** + * Time an event by including the time between this call and a + * later `track` call for the same event in the properties sent + * with the event. + * + * ### Usage: + * + * // time an event named 'Registered' + * mixpanel.time_event('Registered'); + * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21}); + * + * When called for a particular event name, the next track call for that event + * name will include the elapsed time between the `time_event` and `track` + * calls. This value is stored as seconds in the `$duration` property. + * + * @param eventName The name of the event. + */ + time_event(eventName: string): void; - register(params:{[index:string]:any}, days?:number):void; + /** + * Register a set of super properties, which are included with all + * events. This will overwrite previous super property values. + * + * ### Usage: + * + * // register 'Gender' as a super property + * mixpanel.register({'Gender': 'Female'}); + * + * // register several super properties when a user signs up + * mixpanel.register({ + * 'Email': 'jdoe@example.com', + * 'Account Type': 'Free' + * }); + * + * @param properties An associative array of properties to store about the user + * @param days How many days since the user's last visit to store the super properties + */ + register(properties: { [index: string]: any }, days?: number): void; - register_once(params:{[index:string]:any}, defaultValue?:string, days?:number):void; + /** + * Register a set of super properties only once. This will not + * overwrite previous super property values, unlike `register()`. + * + * ### Usage: + * + * // register a super property for the first time only + * mixpanel.register_once({ + * 'First Login Date': new Date().toISOString() + * }); + * + * ### Notes: + * + * If default_value is specified, current super properties + * with that value will be overwritten. + * + * @param properties An associative array of properties to store about the user + * @param defaultValue Value to override if already set in super properties (ex: 'False') Default: 'None' + * @param days How many days since the users last visit to store the super properties + */ + register_once(properties: { [index: string]: any }, defaultValue?: string, days?: number): void; - reset():void; + /** + * Delete a super property stored with the current user. + * + * @param propertyName The name of the super property to remove + */ + unregister(propertyName: string): void; - unregister(propertyName:string):void; + /** + * Identify a user with a unique ID. All subsequent + * actions caused by this user will be tied to this unique ID. This + * property is used to track unique visitors. If the method is + * never called, then unique visitors will be identified by a UUID + * generated the first time they visit the site. + * + * ### Notes: + * + * You can call this function to overwrite a previously set + * unique ID for the current user. Mixpanel cannot translate + * between IDs at this time, so when you change a user's ID + * they will appear to be a new user. + * + * `identify()` should not be called to link anonymous activity to + * subsequent activity when a unique ID is first assigned. + * Use `alias()` when a unique ID is first assigned (registration), and + * use `identify()` to identify the user with that unique ID on an ongoing + * basis (e.g., each time a user logs in after registering). + * Do not call `identify()` at the same time as `alias()`. + * + * @param unique_id A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used. + */ + identify(uniqueId?: string): void; - identify(id?:string):void; + /** + * Clears super properties and generates a new random `distinct_id` for this instance. + * Useful for clearing data when a user logs out. + */ + reset(): void; - get_distinct_id():string; + /** + * Returns the current distinct id of the user. This is either the id automatically + * generated by the library or the id that has been passed by a call to `identify()`. + * + * ### Notes: + * + * `get_distinct_id()` can only be called after the Mixpanel library has finished loading. + * `init()` has a loaded function available to handle this automatically. For example: + * + * // set distinct_id after the mixpanel library has loaded + * mixpanel.init('YOUR PROJECT TOKEN', { + * loaded: function(mixpanel) { + * distinct_id = mixpanel.get_distinct_id(); + * } + * }); + */ + get_distinct_id(): string; - alias(alias:string, currentId?:string):void; + /** + * Create an alias, which Mixpanel will use to link two distinct_ids going forward (not retroactively). + * Multiple aliases can map to the same original ID, but not vice-versa. Aliases can also be chained - the + * following is a valid scenario: + * + * mixpanel.alias('new_id', 'existing_id'); + * ... + * mixpanel.alias('newer_id', 'new_id'); + * + * If the original ID is not passed in, we will use the current distinct_id - probably the auto-generated GUID. + * + * ### Notes: + * + * The best practice is to call `alias()` when a unique ID is first created for a user + * (e.g., when a user first registers for an account and provides an email address). + * `alias()` should never be called more than once for a given user, except to + * chain a newer ID to a previously new ID, as described above. + * + * @param alias A unique identifier that you want to use for this user in the future. + * @param currentId The current identifier being used for this user. + */ + alias(alias: string, currentId?: string): void; - set_config(config:{[index:string]:any}):void; + /** + * Update the configuration of a mixpanel library instance. + * + * @param config A dictionary of new configuration values to update + */ + set_config(config: Mixpanel.Config): void; - get_config():{[index:string]:any}; + /** + * Returns the current config object for the library. + */ + get_config(): Mixpanel.Config; - get_property(propertyName:string):any; + /** + * Returns the value of the super property named property_name. If no such + * property is set, `get_property()` will return the undefined value. + * + * ### Notes: + * + * `get_property()` can only be called after the Mixpanel library has finished loading. + * `init()` has a loaded function available to handle this automatically. For example: + * + * // grab value for 'user_id' after the mixpanel library has loaded + * mixpanel.init('YOUR PROJECT TOKEN', { + * loaded: function(mixpanel) { + * user_id = mixpanel.get_property('user_id'); + * } + * }); + * + * @param propertyName The name of the super property you want to retrieve + */ + get_property(propertyName: string): any; } -declare namespace Mixpanel -{ - interface People - { - set(keys:{[index:string]:any}, callback?:() => void):void; +declare namespace Mixpanel { + interface People { + /** + * Set properties on a user record. + * + * ### Usage: + * + * mixpanel.people.set('gender', 'm'); + * + * // or set multiple properties at once + * mixpanel.people.set({ + * 'Company': 'Acme', + * 'Plan': 'Premium', + * 'Upgrade date': new Date() + * }); + * // properties can be strings, integers, dates, or lists + * + * @param prop If a string, this is the name of the property. If an object, this is an associative array of names and values. + * @param value A value to set on the given property name + * @param callback If provided, the callback will be called after the tracking event + */ + set(prop: string, value: any, callback?: () => void): void; + set(keys: { [index: string]: any }, callback?: () => void): void; - set(key:string, value:any, callback?:() => void):void; + /** + * Set properties on a user record, only if they do not yet exist. + * This will not overwrite previous people property values, unlike + * `people.set()`. + * + * ### Usage: + * + * mixpanel.people.set_once('First Login Date', new Date()); + * + * // or set multiple properties at once + * mixpanel.people.set_once({ + * 'First Login Date': new Date(), + * 'Starting Plan': 'Premium' + * }); + * + * // properties can be strings, integers or dates + * + * @param prop If a string, this is the name of the property. If an object, this is an associative array of names and values. + * @param value A value to set on the given property name + * @param callback If provided, the callback will be called after the tracking event + */ + set_once(prop: string, value: any, callback?: () => void): void; + set_once(keys: { [index: string]: any }, callback?: () => void): void; - set_once(keys:{[index:string]:any}, callback?:() => void):void; + /** + * Increment/decrement numeric people analytics properties. + * + * ### Usage: + * + * mixpanel.people.increment('page_views', 1); + * + * // or, for convenience, if you're just incrementing a counter by + * // 1, you can simply do + * mixpanel.people.increment('page_views'); + * + * // to decrement a counter, pass a negative number + * mixpanel.people.increment('credits_left', -1); + * + * // like mixpanel.people.set(), you can increment multiple + * // properties at once: + * mixpanel.people.increment({ + * counter1: 1, + * counter2: 6 + * }); + * + * @param prop If a string, this is the name of the property. If an object, this is an associative array of names and numeric values. + * @param value An amount to increment the given property + * @param callback If provided, the callback will be called after the tracking event + */ + increment(prop: string, value?: number, callback?: () => void): void; + increment(keys: { [index: string]: number}, callback?: () => void): void; - set_once(key:string, value:any, callback?:() => void):void; + /** + * Merge a given list with a list-valued people analytics property, + * excluding duplicate values. + * + * ### Usage: + * + * // merge a value to a list, creating it if needed + * mixpanel.people.union('pages_visited', 'homepage'); + * + * // like mixpanel.people.set(), you can append multiple + * // properties at once: + * mixpanel.people.union({ + * list1: 'bob', + * list2: 123 + * }); + * + * // like mixpanel.people.append(), you can append multiple + * // values to the same list: + * mixpanel.people.union({ + * list1: ['bob', 'billy'] + * }); + * + * @param prop If a string, this is the name of the property. If an object, this is an associative array of names and values. + * @param value Value / values to merge with the given property + * @param callback If provided, the callback will be called after the tracking event + */ + union(prop: string, values: any, callback?: () => void): void; + union(keys: { [index: string]: any }, callback?: () => void): void; - union(prop: string, values:any, callback?:() => void):void; + /** + * Append a value to a list-valued people analytics property. + * + * ### Usage: + * + * // append a value to a list, creating it if needed + * mixpanel.people.append('pages_visited', 'homepage'); + * + * // like mixpanel.people.set(), you can append multiple + * // properties at once: + * mixpanel.people.append({ + * list1: 'bob', + * list2: 123 + * }); + * + * @param prop If a string, this is the name of the property. If an object, this is an associative array of names and values. + * @param value An item to append to the list + * @param callback If provided, the callback will be called after the tracking event + */ + append(prop: string, value: any, callback?: () => void): void; + append(keys: { [index: string]: any }, callback?: () => void): void; - union(keys:{[index:string]:any}, callback?:() => void):void; + /** + * Record that you have charged the current user a certain amount + * of money. Charges recorded with `track_charge()` will appear in the + * Mixpanel revenue report. + * + * ### Usage: + * + * // charge a user $50 + * mixpanel.people.track_charge(50); + * + * // charge a user $30.50 on the 2nd of january + * mixpanel.people.track_charge(30.50, { + * '$time': new Date('jan 1 2012') + * }); + * + * @param amount The amount of money charged to the current user + * @param properties An associative array of properties associated with the charge + * @param callback If provided, the callback will be called when the server responds + */ + track_charge(amount: number, properties?: { [index: string]: any }, callback?: () => void): void; - increment(key:string):void; + /** + * Permanently clear all revenue report transactions from the + * current user's people analytics profile. + * + * ### Usage: + * + * mixpanel.people.clear_charges(); + * + * @param callback If provided, the callback will be called after the tracking event + */ + clear_charges(callback?: () => void): void; - increment(keys:{[index:string]:number}):void; - - increment(key:string, value:number):void; - - append(keys:{[index:string]:any}):void; - - append(key:string, value:any):void; - - track_charge(amount:number, params?:{[index:string]:any}, callback?:() => void):void; - - clear_charges():void; - - delete_user():void; + /** + * Permanently deletes the current people analytics profile from + * Mixpanel (using the current `distinct_id`). + * + * ### Usage: + * + * // remove the all data you have stored about the current user + * mixpanel.people.delete_user(); + * + */ + delete_user(): void; } - interface Config - { + interface Config { + /** + * @default HTTP_PROTOCOL + 'api.mixpanel.com' + */ api_host?: string; - + /** + * @default HTTP_PROTOCOL + 'mixpanel.com' + */ app_host?: string; - - cdn?: string; - - persistence?: string; - - persistence_name?: string; - - cookie_name?: string; - + /** + * @default true + */ autotrack?: boolean; - + /** + * @default HTTP_PROTOCOL + 'cdn.mxpnl.com' + */ + cdn?: string; + /** + * Super properties span subdomains + * + * @default true + */ cross_subdomain_cookie?: boolean; - + /** + * Type of persistent store for super properties + * + * If set to 'localStorage', any existing mixpanel cookie + * value with the same `persistence_name` will be transferred + * to localStorage and deleted. + * + * @default 'cookie' + */ + persistence?: 'localStorage' | 'cookie'; + /** + * Name for super properties persistent store + * + * @default '' + */ + persistence_name?: string; + /** + * @deprecated Use `persistence_name` instead + * @default '' + */ + cookie_name?: string; + /** + * @default function() {} + */ + loaded?: (lib: Mixpanel) => void; + /** + * @default true + */ store_google?: boolean; - + /** + * @default true + */ save_referrer?: boolean; - + /** + * @default false + */ test?: boolean; - + /** + * @default false + */ verbose?: boolean; - + /** + * @default false + */ img?: boolean; - + /** + * Should we track a page view on page load + * + * @default true + */ track_pageview?: boolean; - + /** + * Debug mode + * + * @default false + */ debug?: boolean; - - upgrade?: boolean; - - disable_persistence?: boolean; - - disable_cookie?: boolean; - - secure_cookie?: boolean; - - ip?: boolean; - - loaded?: (lib:Mixpanel) => void; - + /** + * The amount of time track_links will wait for Mixpanel's + * servers to respond + * + * @default 300 + */ track_links_timeout?: number; - + /** + * Super properties cookie expiration (in days) + * + * @default 365 + */ cookie_expiration?: number; - + /** + * If you set upgrade to be true, the library will check for + * a cookie from our old js library and import super + * properties from it, then the old cookie is deleted + * The upgrade config option only works in the initialization, + * so make sure you set it when you create the library. + * + * @default false + */ + upgrade?: boolean; + /** + * If this is true, the mixpanel cookie or localStorage entry + * will be deleted, and no user persistence will take place + * + * @default false + */ + disable_persistence?: boolean; + /** + * @deprecated Use `disable_persistence` instead + * @default false + */ + disable_cookie?: boolean; + /** + * If this is true, mixpanel cookies will be marked as secure, + * meaning they will only be transmitted over https + * + * @default false + */ + secure_cookie?: boolean; + /** + * If this is true, Mixpanel will automatically determine City, + * Region and Country data using the IP address of the client + * + * @default true + */ + ip?: boolean; + /** + * Names of (super) properties which should never be sent + * with track() calls + * + * @default [] + */ property_blacklist?: string[]; - - [other:string]:any } } -declare var mixpanel:Mixpanel; +declare var mixpanel: Mixpanel; diff --git a/types/mixpanel/mixpanel-tests.ts b/types/mixpanel/mixpanel-tests.ts index bb5f0794cb..b1d735c22e 100644 --- a/types/mixpanel/mixpanel-tests.ts +++ b/types/mixpanel/mixpanel-tests.ts @@ -1,35 +1,67 @@ - -function mixpanel_base() -{ - mixpanel.init("new token"); - mixpanel.init("new token", { your: "config" }); - mixpanel.init("new token", { your: "config" }, "library_name"); +function mixpanel_base() { + mixpanel.init('new token'); + mixpanel.init('new token', { persistence_name: 'config' }); + mixpanel.init('new token', { persistence_name: 'config' }, 'library_name'); mixpanel.push(['register', { a: 'b' }]); + mixpanel.disable(); mixpanel.disable(['my_event']); + mixpanel.track('Registered'); + mixpanel.track('Registered', {Gender: 'Male', Age: 21}); + mixpanel.track('Registered', {Gender: 'Male', Age: 21}, () => {}); + + mixpanel.track_links('#nav', 'Clicked Nav Link'); + mixpanel.track_links('#nav', 'Clicked Nav Link', { prop: 'A' }); + + mixpanel.track_forms('#register', 'Created Account', { prop: 'A' }); + mixpanel.time_event('Registered'); - mixpanel.track("Registered", {"Gender": "Male", "Age": 21}); - - mixpanel.track_links("#nav", "Clicked Nav Link"); - - mixpanel.track_forms("#register", "Created Account"); - mixpanel.register({device: 'android', version: '4.0.1'}); + mixpanel.register({device: 'android', version: '4.0.1'}, 5); mixpanel.register_once({device: 'android', version: '4.0.1'}); + mixpanel.register_once({device: 'android', version: '4.0.1'}, 'default', 4); mixpanel.unregister('device'); + mixpanel.identify(); mixpanel.identify('234234sdfdsf'); mixpanel.get_distinct_id(); + mixpanel.alias('w3erwfsdf'); mixpanel.alias('w3erwfsdf', '234234sdfdsf'); - mixpanel.set_config({test: true}); + mixpanel.set_config({ test: true }); + mixpanel.set_config({ + api_host: '', + app_host: '', + autotrack: true, + cdn: '', + cross_subdomain_cookie: true, + persistence: 'cookie', + persistence_name: '', + cookie_name: '', + loaded: (lib) => {}, + store_google: true, + save_referrer: true, + test: false, + verbose: false, + img: false, + track_pageview: true, + debug: false, + track_links_timeout: 300, + cookie_expiration: 365, + upgrade: false, + disable_persistence: false, + disable_cookie: false, + secure_cookie: false, + ip: true, + property_blacklist: ['token'] + }); mixpanel.get_config(); @@ -38,45 +70,72 @@ function mixpanel_base() mixpanel.reset(); } -function mixpanel_people() -{ +function mixpanel_people() { mixpanel.people.set('gender', 'm'); + mixpanel.people.set('gender', 'm', () => {}); mixpanel.people.set({ - 'Company': 'Acme', - 'Plan': 'Premium', + Company: 'Acme', + Plan: 'Premium', 'Upgrade date': new Date() }); + mixpanel.people.set({ + Company: 'Acme', + Plan: 'Premium', + 'Upgrade date': new Date() + }, () => {}); mixpanel.people.set_once('First Login Date', new Date()); + mixpanel.people.set_once('First Login Date', new Date(), () => {}); mixpanel.people.set_once({ 'First Login Date': new Date(), 'Starting Plan': 'Premium' }); + mixpanel.people.set_once({ + 'First Login Date': new Date(), + 'Starting Plan': 'Premium' + }, () => {}); - mixpanel.people.increment('page_views', 1); mixpanel.people.increment('page_views'); + mixpanel.people.increment('page_views', 1); mixpanel.people.increment('credits_left', -1); + mixpanel.people.increment('page_views', 1, () => {}); mixpanel.people.increment({ counter1: 1, counter2: 1 }); + mixpanel.people.increment({ + counter1: 1, + counter2: 1 + }, () => {}); + mixpanel.people.union('pages_visited', 'homepage', () => {}); mixpanel.people.union('pages_visited', 'homepage'); mixpanel.people.union({ list1: 'bob', list2: 123 }); + mixpanel.people.union({ + list1: 'bob', + list2: 123 + }, () => {}); mixpanel.people.append('pages_visited', 'homepage'); + mixpanel.people.append('pages_visited', 'homepage', () => {}); mixpanel.people.append({ list1: 'bob', list2: 123 }); + mixpanel.people.append({ + list1: 'bob', + list2: 123 + }, () => {}); mixpanel.people.track_charge(50); - mixpanel.people.track_charge(30.50, {'$time': new Date('jan 1 2012')}); + mixpanel.people.track_charge(30.50, {$time: new Date('jan 1 2012')}); + mixpanel.people.track_charge(30.50, {$time: new Date('jan 1 2012')}, () => {}); mixpanel.people.clear_charges(); + mixpanel.people.clear_charges(() => {}); mixpanel.people.delete_user(); } diff --git a/types/mixpanel/tslint.json b/types/mixpanel/tslint.json index a41bf5d19a..10d875b8db 100644 --- a/types/mixpanel/tslint.json +++ b/types/mixpanel/tslint.json @@ -1,79 +1,4 @@ { "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 - } + "rules": {} } diff --git a/types/mock-knex/index.d.ts b/types/mock-knex/index.d.ts new file mode 100644 index 0000000000..a21ab2eb0a --- /dev/null +++ b/types/mock-knex/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for mock-knex 0.3 +// Project: https://github.com/colonyamerican/mock-knex +// Definitions by: Jesse Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as Knex from "knex"; +import { EventEmitter } from "events"; + +/** + * Attaches mocked client to knex instance + * + * @param knex initialized knex client + */ +export function mock(knex: Knex): void; + +/** + * Detaches mocked client from knex instance + * + * @param knex initialized knex client + */ +export function unmock(knex: Knex): void; + +/** + * Returns query Tracker instance + */ +export function getTracker(): Tracker; + +/** + * The tracker enables you to catch and respond to queries that occur during testing, see Test for more examples. + */ +export interface Tracker extends EventEmitter { + /** + * Enables query tracking mock on mocked knex client + */ + install(): void; + + /** + * Disables query tracking mock on mocked knex client. Also resets 'step' counter. + */ + uninstall(): void; + + /** + * Add event listener for 'query' event. It gets esecuted for each query that should end up in database. + * Instead of this callback gets executed and its up to you to assert queries and mock database responses. + * + * @param callback A function that gets executed on 'query' event. + */ + on(event: 'query', callback: (query: QueryDetails, step: number) => void): this; +} + +/** + * The object containing query details that is being sent to knex database dialect on query execution. + * Object properties signature matches with knex toSQL() output with additional method returns(values). + */ +export interface QueryDetails extends Knex.Sql { + /** + * Function that needs to be called to mock database query result for knex. + * + * @param error The Error, string or instance of Error, which represents why the result was rejected + */ + reject(error: Error | string): void; + + /** + * Function that needs to be called to mock database query result for knex. + * + * @param values An array of mock data to be returned by database. For Bookshelf this is mostly array of objects. Knex could return any type of data. + */ + response(values: any[], options?: QueryDetailsResponseOption): void; +} + +export interface QueryDetailsResponseOption { + /** + * Is this a stream response, defaults to false + */ + stream: boolean; +} diff --git a/types/mock-knex/mock-knex-tests.ts b/types/mock-knex/mock-knex-tests.ts new file mode 100644 index 0000000000..ec4ef0024e --- /dev/null +++ b/types/mock-knex/mock-knex-tests.ts @@ -0,0 +1,29 @@ +import * as knex from "knex"; +import * as mockDb from "mock-knex"; + +const db = knex({ + client: 'sqlite' +}); + +mockDb.mock(db); + +const tracker = mockDb.getTracker(); +tracker.install(); +tracker.on('query', (query, step) => { + if (query.method === "first" || step === 1) { + query.response([{ + a: 1 + }, { + a: 2 + }, { + a: 3 + }], { + stream: false + }); + } else { + query.reject(new Error("bad query")); + } +}); +tracker.uninstall(); + +mockDb.unmock(db); diff --git a/types/mock-knex/tsconfig.json b/types/mock-knex/tsconfig.json new file mode 100644 index 0000000000..427ad9f843 --- /dev/null +++ b/types/mock-knex/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", + "mock-knex-tests.ts" + ] +} diff --git a/types/mock-knex/tslint.json b/types/mock-knex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mock-knex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moji/index.d.ts b/types/moji/index.d.ts new file mode 100644 index 0000000000..ae45f6ac26 --- /dev/null +++ b/types/moji/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for moji 0.5 +// Project: https://github.com/niwaringo/moji +// Definitions by: Yasunori Ohoka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace moji { + type Mojisyu = "ZE" | "HE" | "ZS" | "HS" | "HG" | "KK" | "ZK" | "HK"; + + interface MojisyuRange { + start: number; + end: number; + } + + interface MojisyuRegExp { + regexp: RegExp; + list: string[]; + } + + interface Moji { + convert(beforeType: Mojisyu, afterType: Mojisyu): Moji; + trim(): Moji; + filter(type: Mojisyu): Moji; + reject(type: Mojisyu): Moji; + toString(): string; + } + + function addMojisyu(type: string, mojisyu: MojisyuRange | MojisyuRegExp): void; +} + +declare function moji(moji: string): moji.Moji; +export = moji; diff --git a/types/moji/moji-tests.ts b/types/moji/moji-tests.ts new file mode 100644 index 0000000000..05be3e43c1 --- /dev/null +++ b/types/moji/moji-tests.ts @@ -0,0 +1,23 @@ +import moji = require('moji'); + +moji('ABCD01234').convert('ZE', 'HE').toString(); +moji('ABCD01234').convert('HE', 'ZE').toString(); +// tslint:disable-next-line:no-irregular-whitespace +moji(' ').convert('ZS', 'HS').toString(); +moji('あいうえお').convert('HG', 'KK').toString(); +moji('アイウエオ').convert('KK', 'HG').toString(); +moji('アイウエオ').convert('ZK', 'HK').toString(); +moji('アイウエオ').convert('HK', 'ZK').toString(); +moji('アイウエオ').convert('HK', 'ZK').convert('KK', 'HG').toString(); + +moji(' アイウエオ ').trim().toString(); + +moji('abcあいうアイウ123').filter('HG').toString(); + +moji('abcあいうアイウ123').reject('HG').toString(); + +moji.addMojisyu('ZE', { start: 0xff01, end: 0xff5e }); +moji.addMojisyu('HK', { + regexp: /([\uff66-\uff9c]\uff9e)|([\uff8a-\uff8e]\uff9f)|([\uff61-\uff9f])/g, + list: ["。", "「", "」"] +}); diff --git a/types/moji/tsconfig.json b/types/moji/tsconfig.json new file mode 100644 index 0000000000..a6b2e51f26 --- /dev/null +++ b/types/moji/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moji-tests.ts" + ] +} diff --git a/types/moji/tslint.json b/types/moji/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moji/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moment-holiday/index.d.ts b/types/moment-holiday/index.d.ts new file mode 100644 index 0000000000..fffe81ed73 --- /dev/null +++ b/types/moment-holiday/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for moment-holiday 1.5 +// Project: https://github.com/kodie/moment-holiday +// Definitions by: Robert Winslow Dalpe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as moment from 'moment'; + +declare module 'moment' { + interface Moment extends Object { + holiday( + holidays?: string[] | string, + adjust?: boolean): Moment | false | { [holidayName: string]: Moment }; + + holidays( + holidays?: string[] | string, + adjust?: boolean): Moment | false | { [holidayName: string]: Moment }; + + isHoliday( + holidays?: string[] | string | null, + adjust?: boolean): boolean | string | string[]; + + previousHoliday(count?: number, adjust?: boolean): Moment[] | Moment; + + previousHolidays(count?: number, adjust?: boolean): Moment[] | Moment; + + nextHoliday(count?: number, adjust?: boolean): Moment[] | Moment; + + nextHolidays(count?: number, adjust?: boolean): Moment[] | Moment; + + holidaysBetween(m: Moment, adjust?: boolean): Moment[] | false; + } + + interface HolidayDefinition { + date: string; + keywords?: string[]; + keywords_y?: string[]; + keywords_n?: string[]; + regions?: string[]; + regions_n?: string[]; + } + + interface HolidaysMapping { + [holidayName: string]: HolidayDefinition; + } + + interface Holidays { + active: HolidaysMapping; + active_last: HolidaysMapping; + } + + interface HolidayModifier { + set( + holidays: HolidaysMapping | string | string[], + specifics?: any): HolidayModifier; + + add( + holidays: HolidaysMapping | string, + specifics?: any): HolidayModifier; + + remove(holidays: string | string[]): HolidayModifier; + + undo(): HolidayModifier; + + load(locales: string | string[]): HolidayModifier; + + extendParser(parserFunc: (m: Moment, date: string) => Moment | Moment[] | false | void): HolidayModifier; + } + + let holidays: Holidays; + let modifyHolidays: HolidayModifier; +} diff --git a/types/moment-holiday/moment-holiday-tests.ts b/types/moment-holiday/moment-holiday-tests.ts new file mode 100644 index 0000000000..474cf246fb --- /dev/null +++ b/types/moment-holiday/moment-holiday-tests.ts @@ -0,0 +1,127 @@ +import moment = require('moment'); +import 'moment-holiday'; + +let holidayResult: moment.Moment | false | { [holidayName: string]: moment.Moment }; +holidayResult = moment().holiday([]); +holidayResult = moment().holiday([], false); +holidayResult = moment().holiday([], true); +holidayResult = moment().holiday('string'); +holidayResult = moment().holiday('string', false); +holidayResult = moment().holiday('string', true); +holidayResult = moment().holiday(['array', 'of', 'strings']); +holidayResult = moment().holiday(['array', 'of', 'strings'], false); +holidayResult = moment().holiday(['array', 'of', 'strings'], true); + +holidayResult = moment().holidays([]); +holidayResult = moment().holidays([], false); +holidayResult = moment().holidays([], true); +holidayResult = moment().holidays('string'); +holidayResult = moment().holidays('string', false); +holidayResult = moment().holidays('string', true); +holidayResult = moment().holidays(['array', 'of', 'strings']); +holidayResult = moment().holidays(['array', 'of', 'strings'], false); +holidayResult = moment().holidays(['array', 'of', 'strings'], true); + +let isHolidayResult: boolean | string | string[]; +isHolidayResult = moment().isHoliday(); +isHolidayResult = moment().isHoliday([]); +isHolidayResult = moment().isHoliday([], false); +isHolidayResult = moment().isHoliday([], true); +isHolidayResult = moment().isHoliday(['array', 'of', 'strings']); +isHolidayResult = moment().isHoliday(['array', 'of', 'strings'], false); +isHolidayResult = moment().isHoliday(['array', 'of', 'strings'], true); +isHolidayResult = moment().isHoliday('string'); +isHolidayResult = moment().isHoliday('string', false); +isHolidayResult = moment().isHoliday('string', true); +isHolidayResult = moment().isHoliday(null); +isHolidayResult = moment().isHoliday(null, false); +isHolidayResult = moment().isHoliday(null, true); + +let previousHolidayResult: moment.Moment[] | moment.Moment; +previousHolidayResult = moment().previousHoliday(); +previousHolidayResult = moment().previousHoliday(1); +previousHolidayResult = moment().previousHoliday(1, false); +previousHolidayResult = moment().previousHoliday(1, true); +previousHolidayResult = moment().previousHolidays(); +previousHolidayResult = moment().previousHolidays(1); +previousHolidayResult = moment().previousHolidays(1, false); +previousHolidayResult = moment().previousHolidays(1, true); + +let nextHolidayResult: moment.Moment[] | moment.Moment; +nextHolidayResult = moment().nextHoliday(); +nextHolidayResult = moment().nextHoliday(1); +nextHolidayResult = moment().nextHoliday(1, false); +nextHolidayResult = moment().nextHoliday(1, true); +nextHolidayResult = moment().nextHolidays(); +nextHolidayResult = moment().nextHolidays(1); +nextHolidayResult = moment().nextHolidays(1, false); +nextHolidayResult = moment().nextHolidays(1, true); + +let holidaysBetweenResult: moment.Moment[] | false; +holidaysBetweenResult = moment().holidaysBetween(moment()); +holidaysBetweenResult = moment().holidaysBetween(moment(), false); +holidaysBetweenResult = moment().holidaysBetween(moment(), true); + +let holidayDefinition: moment.HolidayDefinition = { + date: 'string' +}; +holidayDefinition = { + date: 'string', + keywords: ['array'], +}; +holidayDefinition = { + date: 'string', + keywords: ['array'], + keywords_n: ['array'], +}; +holidayDefinition = { + date: 'string', + keywords: ['array'], + keywords_n: ['array'], + keywords_y: ['array'], +}; +holidayDefinition = { + date: 'string', + keywords: ['array'], + keywords_n: ['array'], + keywords_y: ['array'], + regions: ['array'], +}; +holidayDefinition = { + date: 'string', + keywords: ['array'], + keywords_n: ['array'], + keywords_y: ['array'], + regions: ['array'], + regions_n: ['array'] +}; + +const holidays: moment.Holidays = moment.holidays; +let activeHolidays: moment.HolidaysMapping = moment.holidays.active; +activeHolidays = { + 'Some holiday name': holidayDefinition +}; + +let lastActiveHolidays: moment.HolidaysMapping = moment.holidays.active_last; +lastActiveHolidays = { + 'Some holiday name': holidayDefinition +}; + +let holidayModifier: moment.HolidayModifier = moment.modifyHolidays; +holidayModifier = holidayModifier.set('string'); +holidayModifier = holidayModifier.set(['array']); +holidayModifier = holidayModifier.set(activeHolidays); +holidayModifier = holidayModifier.set('string', {}); +holidayModifier = holidayModifier.set(['array'], {}); +holidayModifier = holidayModifier.set(activeHolidays, {}); +holidayModifier = holidayModifier.add(activeHolidays); +holidayModifier = holidayModifier.add('string'); +holidayModifier = holidayModifier.add(activeHolidays, {}); +holidayModifier = holidayModifier.add('string', {}); +holidayModifier = holidayModifier.remove('string'); +holidayModifier = holidayModifier.remove(['array']); +holidayModifier = holidayModifier.undo(); +holidayModifier = holidayModifier.load('string'); +holidayModifier = holidayModifier.load(['string']); +holidayModifier = holidayModifier.extendParser((m: moment.Moment, d: string): moment.Moment | moment.Moment[] | false | void => { +}); diff --git a/types/moment-holiday/package.json b/types/moment-holiday/package.json new file mode 100644 index 0000000000..4c7554a28e --- /dev/null +++ b/types/moment-holiday/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": ">=2.0.0" + } +} diff --git a/types/moment-holiday/tsconfig.json b/types/moment-holiday/tsconfig.json new file mode 100644 index 0000000000..d03f37e12c --- /dev/null +++ b/types/moment-holiday/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", + "moment-holiday-tests.ts" + ] +} diff --git a/types/moment-holiday/tslint.json b/types/moment-holiday/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-holiday/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moment-strftime2/package.json b/types/moment-strftime2/package.json new file mode 100644 index 0000000000..ac2bb42bad --- /dev/null +++ b/types/moment-strftime2/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": "^2.18.1" + } +} diff --git a/types/mongoose-geojson-schema/index.d.ts b/types/mongoose-geojson-schema/index.d.ts index 2cd97a8141..b732bec098 100644 --- a/types/mongoose-geojson-schema/index.d.ts +++ b/types/mongoose-geojson-schema/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/rideamigoscorp/mongoose-geojson-schema#readme // Definitions by: Bond // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import mongoose = require('mongoose'); diff --git a/types/mongoose-seeder/index.d.ts b/types/mongoose-seeder/index.d.ts index f3d9b8f1e4..6d13a84f70 100644 --- a/types/mongoose-seeder/index.d.ts +++ b/types/mongoose-seeder/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/SamVerschueren/mongoose-seeder // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from 'q'; diff --git a/types/mongoose-simple-random/index.d.ts b/types/mongoose-simple-random/index.d.ts index fb8edd3500..893dc73537 100644 --- a/types/mongoose-simple-random/index.d.ts +++ b/types/mongoose-simple-random/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/larryprice/mongoose-simple-random // Definitions by: Roberts Slisans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import mongoose = require('mongoose'); declare function pluginFunc(schema: mongoose.Schema): void; diff --git a/types/mongoose-unique-validator/index.d.ts b/types/mongoose-unique-validator/index.d.ts index 3cc2a13d80..3c08ab6607 100644 --- a/types/mongoose-unique-validator/index.d.ts +++ b/types/mongoose-unique-validator/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/blakehaswell/mongoose-unique-validator#readme // Definitions by: Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { Schema } from "mongoose"; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 3e1002fd3c..261b8ade84 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -727,7 +727,7 @@ declare module "mongoose" { minimize?: boolean; read?: string; /** defaults to true. */ - safe?: boolean; + safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; /** defaults to null */ shardKey?: boolean; /** defaults to true */ diff --git a/types/morgan/index.d.ts b/types/morgan/index.d.ts index 1558f24ee4..097758465a 100644 --- a/types/morgan/index.d.ts +++ b/types/morgan/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: James Roland Cabresos // Paolo Scanferla // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 import express = require('express'); diff --git a/types/msgpack-lite/index.d.ts b/types/msgpack-lite/index.d.ts index 27c4fb619b..2148e03624 100644 --- a/types/msgpack-lite/index.d.ts +++ b/types/msgpack-lite/index.d.ts @@ -125,7 +125,7 @@ export interface CodecOptions { * @see https://github.com/kawanet/msgpack-lite#compatibility-mode * @default false */ - raw?: boolean; + useraw?: boolean; /** * It decodes msgpack's int64/uint64 formats with int64-buffer object. * int64-buffer is a cutom integer type with 64 bits of precision instead @@ -140,8 +140,14 @@ export interface CodecOptions { binarraybuffer?: boolean; /** * It returns Uint8Array object when encoding, instead of Buffer object. + * @default false */ uint8array?: boolean; + /** + * It uses the global JavaScript Map type, if available, to unpack MessagePack map elements. + * @default false + */ + usemap?: boolean; } export interface EncoderOptions { diff --git a/types/msgpack-lite/msgpack-lite-tests.ts b/types/msgpack-lite/msgpack-lite-tests.ts index 7e357c4b6a..781063e6d4 100644 --- a/types/msgpack-lite/msgpack-lite-tests.ts +++ b/types/msgpack-lite/msgpack-lite-tests.ts @@ -9,6 +9,18 @@ function encodingAndDecoding() { const data = msgpack.decode(buffer); // => {"foo": "bar"} } +function customCodec() { + msgpack.createCodec({ + preset: true, + safe: true, + useraw: true, + int64: true, + binarraybuffer: true, + uint8array: true, + usemap: true + }); +} + // https://github.com/kawanet/msgpack-lite#writing-to-messagepack-stream function writingToStream() { const fs = require("fs"); diff --git a/types/msportalfx-test/index.d.ts b/types/msportalfx-test/index.d.ts index c2d64f95d4..b7432ba973 100644 --- a/types/msportalfx-test/index.d.ts +++ b/types/msportalfx-test/index.d.ts @@ -2,6 +2,7 @@ // Project: https://msazure.visualstudio.com/DefaultCollection/AzureUX/_git/portalfx-msportalfx-test // Definitions by: Julio Casal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from "q"; diff --git a/types/multer-gridfs-storage/index.d.ts b/types/multer-gridfs-storage/index.d.ts index b9af5ed757..0a827bedcb 100644 --- a/types/multer-gridfs-storage/index.d.ts +++ b/types/multer-gridfs-storage/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/devconcept/multer-gridfs-storage // Definitions by: devconcept // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { EventEmitter } from 'events'; import { Express } from 'express'; diff --git a/types/multer-gridfs-storage/v1/index.d.ts b/types/multer-gridfs-storage/v1/index.d.ts index 67e6abe70b..c68e464a4c 100644 --- a/types/multer-gridfs-storage/v1/index.d.ts +++ b/types/multer-gridfs-storage/v1/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/devconcept/multer-gridfs-storage // Definitions by: devconcept // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { EventEmitter } from 'events'; import { Express } from 'express'; diff --git a/types/multer-s3/index.d.ts b/types/multer-s3/index.d.ts index d4e0bc476c..a03e6ae36e 100644 --- a/types/multer-s3/index.d.ts +++ b/types/multer-s3/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // Gal Talmor // Definitions: https://github.com/DefinitelyType/DefinitelyTyped +// TypeScript Version: 2.2 import * as AWS from "aws-sdk"; import { StorageEngine } from "multer"; diff --git a/types/multer/index.d.ts b/types/multer/index.d.ts index 5c300a5585..d019b9fdcb 100644 --- a/types/multer/index.d.ts +++ b/types/multer/index.d.ts @@ -6,7 +6,7 @@ // Michael Ledin // HyunSeob Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 import * as express from 'express'; diff --git a/types/mysql/index.d.ts b/types/mysql/index.d.ts index d7661a3214..7260dc2e85 100644 --- a/types/mysql/index.d.ts +++ b/types/mysql/index.d.ts @@ -3,9 +3,10 @@ // Definitions by: William Johnston // Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// // TypeScript Version: 2.1 +/// + import stream = require("stream"); import tls = require("tls"); diff --git a/types/nano/index.d.ts b/types/nano/index.d.ts index 788de4f241..152954190d 100644 --- a/types/nano/index.d.ts +++ b/types/nano/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Tim Jacobi // Kovács Vince // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/neo4j/index.d.ts b/types/neo4j/index.d.ts index dc9567f725..f42ff7079e 100644 --- a/types/neo4j/index.d.ts +++ b/types/neo4j/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/thingdom/node-neo4j // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index c5526049de..a6ed90a7b7 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index 1f5945741b..d8222d2e3c 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kirill-konshin/next-redux-wrapper // Definitions by: Steve // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// /*~ Note that ES6 modules cannot directly export callable functions. diff --git a/types/ngprogress-lite/ngprogress-lite-tests.ts b/types/ngprogress-lite/ngprogress-lite-tests.ts index c4b903d78b..2cdfa53661 100644 --- a/types/ngprogress-lite/ngprogress-lite-tests.ts +++ b/types/ngprogress-lite/ngprogress-lite-tests.ts @@ -4,7 +4,7 @@ app.config( ['ngProgressLiteProvider', (ngProgressLiteProvider: ng.progressLite.INgProgressLiteProvider) => { ngProgressLiteProvider.settings.ease = 'ease'; - ngProgressLiteProvider.settings.minimum = 0.08, + ngProgressLiteProvider.settings.minimum = 0.08; ngProgressLiteProvider.settings.speed = 300; ngProgressLiteProvider.settings.trickleRate = 0.02; ngProgressLiteProvider.settings.trickleSpeed = 500; diff --git a/types/node-persist/index.d.ts b/types/node-persist/index.d.ts index bb8df33369..632c4e8736 100644 --- a/types/node-persist/index.d.ts +++ b/types/node-persist/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/simonlast/node-persist // Definitions by: Spencer Williams // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/node-sass-middleware/index.d.ts b/types/node-sass-middleware/index.d.ts index 51be3992f1..badbd843d1 100644 --- a/types/node-sass-middleware/index.d.ts +++ b/types/node-sass-middleware/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sass/node-sass-middleware // Definitions by: Pascal Garber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 diff --git a/types/node-slack/index.d.ts b/types/node-slack/index.d.ts index e4d8616c16..d81926f633 100644 --- a/types/node-slack/index.d.ts +++ b/types/node-slack/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/xoxco/node-slack // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import request = require('request'); diff --git a/types/node-sprite-generator/index.d.ts b/types/node-sprite-generator/index.d.ts index 6bd2b88973..05bad5fe8e 100644 --- a/types/node-sprite-generator/index.d.ts +++ b/types/node-sprite-generator/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/selaux/node-sprite-generator#readme // Definitions by: Gyusun Yeom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as e from "express"; diff --git a/types/node-static/index.d.ts b/types/node-static/index.d.ts index 23e5ba1f87..53b1f4cb07 100644 --- a/types/node-static/index.d.ts +++ b/types/node-static/index.d.ts @@ -42,7 +42,7 @@ export class Server { finish: (status: number, headers: Headers, req: http.ServerRequest, res: http.ServerResponse, promise: events.EventEmitter, callback: Callback) => void; servePath: (pathname: string, status: number, headers: Headers, req: http.ServerRequest, res: http.ServerResponse, finish: Finish) => events.EventEmitter; resolve: (pathname: string) => string; - serve: (req: http.ServerRequest, res: http.ServerResponse, callback: Callback) => events.EventEmitter; + serve: (req: http.ServerRequest, res: http.ServerResponse, callback?: Callback) => events.EventEmitter; gzipOk: (req: http.ServerRequest, contentType: string) => boolean; respondGzip: (pathname: string, status: number, contentType: string, _headers: Headers, files: string[], stat: fs.Stats, req: http.ServerRequest, res: http.ServerResponse, finish: Finish) => void; parseByteRange: (req: http.ServerRequest, stat: fs.Stats) => ByteRange; diff --git a/types/node-telegram-bot-api/index.d.ts b/types/node-telegram-bot-api/index.d.ts index 4e33b64253..cfc55d2d33 100644 --- a/types/node-telegram-bot-api/index.d.ts +++ b/types/node-telegram-bot-api/index.d.ts @@ -4,7 +4,8 @@ // Agadar // Giorgio Garasto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 + /// import { EventEmitter } from 'events'; diff --git a/types/node-vault/index.d.ts b/types/node-vault/index.d.ts index 939da2bd2a..653db37e85 100644 --- a/types/node-vault/index.d.ts +++ b/types/node-vault/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kr1sp1n/node-vault // Definitions by: Jianrong Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as mustache from "mustache"; import * as request from "request"; diff --git a/types/node-zookeeper-client/index.d.ts b/types/node-zookeeper-client/index.d.ts index 8a63177f83..0e095cd822 100644 --- a/types/node-zookeeper-client/index.d.ts +++ b/types/node-zookeeper-client/index.d.ts @@ -171,8 +171,8 @@ export class Exception { code: number; name: string; - path: number; - constructor(code: number, name: string, path: number); + path?: string; + constructor(code: number, name: string, path?: string); toString(): string; getCode(): number; getName(): string; diff --git a/types/node-zookeeper-client/node-zookeeper-client-tests.ts b/types/node-zookeeper-client/node-zookeeper-client-tests.ts index 90f19642cc..554077e5af 100644 --- a/types/node-zookeeper-client/node-zookeeper-client-tests.ts +++ b/types/node-zookeeper-client/node-zookeeper-client-tests.ts @@ -255,3 +255,8 @@ const client = zookeeper.createClient( { new zookeeper.Event(zookeeper.Event.NODE_CREATED, 'test', '/test'); } + +{ + new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test'); + new zookeeper.Exception(zookeeper.Exception.NO_NODE, 'test', '/test'); +} diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 5b0e8b4b19..188e1315d6 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -13,8 +13,8 @@ // Deividas Bakanas // Kelvin Jin // Alvis HT Tang +// Oliver Joseph Ash // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 /************************************************ * * @@ -1956,6 +1956,7 @@ declare module "child_process" { uid?: number; gid?: number; shell?: boolean | string; + windowsVerbatimArguments?: boolean; } export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; @@ -2015,6 +2016,7 @@ declare module "child_process" { killSignal?: string; uid?: number; gid?: number; + windowsVerbatimArguments?: boolean; } export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { encoding: BufferEncoding; @@ -2081,6 +2083,7 @@ declare module "child_process" { stdio?: any[]; uid?: number; gid?: number; + windowsVerbatimArguments?: boolean; } export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; @@ -2096,6 +2099,7 @@ declare module "child_process" { maxBuffer?: number; encoding?: string; shell?: boolean | string; + windowsVerbatimArguments?: boolean; } export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { encoding: BufferEncoding; @@ -4423,6 +4427,29 @@ declare module "path" { name: string; } + export interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + /** * Normalize a string path, reducing '..' and '.' parts. * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. @@ -4501,7 +4528,7 @@ declare module "path" { * * @param pathString path to evaluate. */ - export function format(pathObject: ParsedPath): string; + export function format(pathObject: FormatInputPathObject): string; export module posix { export function normalize(p: string): string; @@ -5375,16 +5402,18 @@ declare module "util" { export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function promisify(fn: CustomPromisify): TCustom; - export function promisify(fn: (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1) => Promise; - export function promisify(fn: (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: (callback: (err: Error, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err: Error) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: Error, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err: Error) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; export function promisify(fn: Function): Function; export namespace promisify { const custom: symbol; diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts index 445f55410d..955239b486 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -690,6 +690,11 @@ declare module "inspector" { * Stack trace captured when the call was made. */ stackTrace?: Runtime.StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string; } export interface InspectRequestedEventDataType { @@ -1434,6 +1439,10 @@ declare module "inspector" { * Source ranges inside the function with coverage data. */ ranges: Profiler.CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; } /** diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index db0b30897e..315ec48d2f 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -758,6 +758,10 @@ namespace util_tests { // util.promisify var readPromised = util.promisify(fs.readFile); var sampleRead: Promise = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); + var arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); + var arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); + var arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); + var arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); assert(typeof util.promisify.custom === 'symbol'); // util.deprecate const foo = () => {}; @@ -1616,19 +1620,7 @@ namespace path_tests { // returns // ['foo', 'bar', 'baz'] - console.log(process.env.PATH); - // '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' - - process.env.PATH.split(path.delimiter); - // returns - // ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] - - console.log(process.env.PATH); - // 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' - - process.env.PATH.split(path.delimiter); - // returns - // ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] + process.env["PATH"]; // $ExpectType string path.parse('/home/user/dir/file.txt'); // returns @@ -1659,6 +1651,15 @@ namespace path_tests { }); // returns // '/home/user/dir/file.txt' + + path.format({ + root: "/", + dir: "/home/user/dir", + ext: ".txt", + name: "file" + }); + // returns + // '/home/user/dir/file.txt' } //////////////////////////////////////////////////// @@ -3071,11 +3072,11 @@ client.listbreakpoints((err, body, packet) => { }); //////////////////////////////////////////////////// namespace async_hooks_tests { const hooks: async_hooks.HookCallbacks = { - init: (asyncId: number, type: string, triggerAsyncId: number, resource: object) => void {}, - before: (asyncId: number) => void {}, - after: (asyncId: number) => void {}, - destroy: (asyncId: number) => void {}, - promiseResolve: (asyncId: number) => void {} + init() {}, + before() {}, + after() {}, + destroy() {}, + promiseResolve() {}, }; const asyncHook = async_hooks.createHook(hooks); @@ -3342,7 +3343,8 @@ namespace http2_tests { settings, allowHTTP1: true }; - let secureServerOptions: http2.SecureServerOptions = { ...serverOptions }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + let secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); secureServerOptions.ca = ''; let onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { // Http2ServerRequest @@ -3439,7 +3441,8 @@ namespace http2_tests { selectPadding: (frameLen: number, maxFrameLen: number) => 0, settings }; - let secureClientSessionOptions: http2.SecureClientSessionOptions = { ...clientSessionOptions }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + let secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); secureClientSessionOptions.ca = ''; let onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; @@ -3692,8 +3695,9 @@ namespace inspector_tests { session.disconnect(); // Unknown post method - session.post('A.b', { key: 'value' }, (err: Error, params: object) => {}); - session.post('A.b', (err: Error, params: object) => {}); + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); session.post('A.b'); // Known post method const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; @@ -3706,7 +3710,9 @@ namespace inspector_tests { session.post('Runtime.evaluate'); // General event - session.on('inspectorNotification', (message: inspector.InspectorNotification) => {}); + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); // Known events session.on('Debugger.paused', (message: inspector.InspectorNotification) => { const method: string = message.method; diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index e3ac3b2f91..9f4317b9f4 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -5,6 +5,7 @@ ], "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], diff --git a/types/nodegit/blame-options.d.ts b/types/nodegit/blame-options.d.ts index 6452eb08cb..1fdc6f6281 100644 --- a/types/nodegit/blame-options.d.ts +++ b/types/nodegit/blame-options.d.ts @@ -8,4 +8,5 @@ export class BlameOptions { oldestCommit?: Oid; minLine?: number; maxLine?: number; + [key: string]: any; } diff --git a/types/nodegit/checkout-options.d.ts b/types/nodegit/checkout-options.d.ts index 4122dfbe28..d711ae7ba9 100644 --- a/types/nodegit/checkout-options.d.ts +++ b/types/nodegit/checkout-options.d.ts @@ -23,4 +23,5 @@ export class CheckoutOptions { theirLabel?: string; perfdataCb?: any; perfdataPayload?: undefined; + [key: string]: any; } diff --git a/types/nodegit/commit.d.ts b/types/nodegit/commit.d.ts index 8a7a259cbf..5c9a82bf70 100644 --- a/types/nodegit/commit.d.ts +++ b/types/nodegit/commit.d.ts @@ -85,25 +85,25 @@ export class Commit { * * */ - getParents(limit: number, callback: Function): Promise; + getParents(limit: number, callback?: Function): Promise; /** * Retrieve the commit's parent shas. * * */ - parents(callback: Function): Oid[]; + parents(): Oid[]; /** * Generate an array of diff trees showing changes between this commit and its parent(s). * * */ - getDiff(callback: Function): Promise; + getDiff(callback?: Function): Promise; /** * Generate an array of diff trees showing changes between this commit and its parent(s). * * */ - getDiffWithOptions(options: Object, callback: Function): Promise; + getDiffWithOptions(options: Object, callback?: Function): Promise; /** * The sha of this commit * diff --git a/types/nodegit/convenient-hunk.d.ts b/types/nodegit/convenient-hunk.d.ts new file mode 100644 index 0000000000..a844fd4e9b --- /dev/null +++ b/types/nodegit/convenient-hunk.d.ts @@ -0,0 +1,37 @@ +import { DiffLine } from './diff-line'; + +export class ConvenientHunk { + /** + * Diff header string that represents the context of this hunk + * of the diff. Something like `@@ -169,14 +167,12 @@ ...` + */ + header(): string; + /** + * The length of the header + */ + headerLen(): number; + /** + * The lines in this hunk + */ + lines(): Promise; + /** + * The number of new lines in the hunk + */ + newLines(): number; + /** + * The starting offset of the first new line in the file + */ + newStart(): number; + /** + * The number of old lines in the hunk + */ + oldLines(): number; + /** + * The starting offset of the first old line in the file + */ + oldStart(): number; + /** + * Number of lines in this hunk + */ + size(): number; +} diff --git a/types/nodegit/convenient-patch.d.ts b/types/nodegit/convenient-patch.d.ts index 68951ded3c..05fa0def4f 100644 --- a/types/nodegit/convenient-patch.d.ts +++ b/types/nodegit/convenient-patch.d.ts @@ -1,3 +1,4 @@ +import { ConvenientHunk } from './convenient-hunk'; import { DiffFile } from './diff-file'; export class ConvenientPatch { @@ -16,7 +17,7 @@ export class ConvenientPatch { /** * The hunks in this patch */ - hunks(): Promise; + hunks(): Promise; /** * The status of this patch (unmodified, added, deleted) */ diff --git a/types/nodegit/describe-format-options.d.ts b/types/nodegit/describe-format-options.d.ts index 2ada190800..b4213f0d68 100644 --- a/types/nodegit/describe-format-options.d.ts +++ b/types/nodegit/describe-format-options.d.ts @@ -3,4 +3,5 @@ export class DescribeFormatOptions { abbreviatedSize?: number; alwaysUseLongFormat?: number; dirtySuffix?: string; + [key: string]: any; } diff --git a/types/nodegit/describe-options.d.ts b/types/nodegit/describe-options.d.ts index 9712228ec2..2934006a93 100644 --- a/types/nodegit/describe-options.d.ts +++ b/types/nodegit/describe-options.d.ts @@ -5,4 +5,5 @@ export class DescribeOptions { pattern?: string; onlyFollowFirstParent?: number; showCommitOidAsFallback?: number; + [key: string]: any; } diff --git a/types/nodegit/diff-hunk.d.ts b/types/nodegit/diff-hunk.d.ts deleted file mode 100644 index 14a1a9a304..0000000000 --- a/types/nodegit/diff-hunk.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export class DiffHunk { - oldStart: number; - oldLines: number; - newStart: number; - newLines: number; - headerLen: number; - header: string; -} diff --git a/types/nodegit/diff-options.d.ts b/types/nodegit/diff-options.d.ts index 06821b9608..408a0530e1 100644 --- a/types/nodegit/diff-options.d.ts +++ b/types/nodegit/diff-options.d.ts @@ -14,4 +14,5 @@ export interface DiffOptions { newPrefix?: string; payload?: any; progressCb?: any; + [key: string]: any; } diff --git a/types/nodegit/diff.d.ts b/types/nodegit/diff.d.ts index 6d8a161e9d..62de0de6c4 100644 --- a/types/nodegit/diff.d.ts +++ b/types/nodegit/diff.d.ts @@ -7,6 +7,7 @@ import { DiffDelta } from './diff-delta'; import { DiffPerfdata } from './diff-perf-data'; import { DiffOptions } from './diff-options'; import { Buf } from './buf'; +import { ConvenientPatch } from './convenient-patch'; export interface DiffFindOptions { version?: number; @@ -134,12 +135,12 @@ export class Diff { static blobToBuffer(oldBlob: Blob, oldAsPath: string, buffer: string, bufferAsPath: string, opts: DiffOptions, fileCb: Function, binaryCb: Function, hunkCb: Function, lineCb: Function): Promise; static fromBuffer(content: string, contentLen: number): Promise; - static indexToWorkdir(repo: Repository, index: Index, opts: DiffOptions): Promise; - static indexToIndex(repo: Repository, oldIndex: Index, newIndex: Index, opts: DiffOptions): Promise; - static treeToIndex(repo: Repository, oldTree: Tree, index: Index, opts: DiffOptions): Promise; - static treeToTree(repo: Repository, oldTree: Tree, new_tree: Tree, opts: DiffOptions): Promise; - static treeToWorkdir(repo: Repository, oldTree: Tree, opts: DiffOptions): Promise; - static treeToWorkdirWithIndex(repo: Repository, oldTree: Tree, opts: DiffOptions): Promise; + static indexToWorkdir(repo: Repository, index: Index, opts?: DiffOptions): Promise; + static indexToIndex(repo: Repository, oldIndex: Index, newIndex: Index, opts?: DiffOptions): Promise; + static treeToIndex(repo: Repository, oldTree: Tree, index: Index, opts?: DiffOptions): Promise; + static treeToTree(repo: Repository, oldTree: Tree, new_tree: Tree, opts?: DiffOptions): Promise; + static treeToWorkdir(repo: Repository, oldTree: Tree, opts?: DiffOptions): Promise; + static treeToWorkdirWithIndex(repo: Repository, oldTree: Tree, opts?: DiffOptions): Promise; findSimilar(options: DiffFindOptions): Promise; getDelta(idx: number): DiffDelta; @@ -150,7 +151,7 @@ export class Diff { * * */ - patches(): Promise; + patches(): Promise; merge(from: Diff): Promise; toBuf(format: Diff.FORMAT): Promise; } diff --git a/types/nodegit/fetch-options.d.ts b/types/nodegit/fetch-options.d.ts index b2fd38cfbb..77b5a9586c 100644 --- a/types/nodegit/fetch-options.d.ts +++ b/types/nodegit/fetch-options.d.ts @@ -9,4 +9,5 @@ export interface FetchOptions { downloadTags?: number; customHeaders?: Strarray; proxyOpts?: any; + [key: string]: any; } diff --git a/types/nodegit/index.d.ts b/types/nodegit/index.d.ts index b0a68f67b5..e6d95ba83e 100644 --- a/types/nodegit/index.d.ts +++ b/types/nodegit/index.d.ts @@ -22,6 +22,7 @@ export { CloneOptions } from './clone-options'; export { Clone } from './clone'; export { Commit } from './commit'; export { Config } from './config'; +export { ConvenientHunk } from './convenient-hunk'; export { ConvenientPatch } from './convenient-patch'; export { CredUserpassPayload } from './cred-user-pass-payload'; export { CredUsername } from './cred-username'; @@ -33,7 +34,6 @@ export { DiffBinaryFile } from './diff-binary-file'; export { DiffBinary } from './diff-binary'; export { DiffDelta } from './diff-delta'; export { DiffFile } from './diff-file'; -export { DiffHunk } from './diff-hunk'; export { DiffLine } from './diff-line'; export { DiffOptions } from './diff-options'; export { DiffPerfdata } from './diff-perf-data'; @@ -87,6 +87,8 @@ export { Revert } from './revert'; export { Signature } from './signature'; export { Stash } from './stash'; export { StatusEntry } from './status-entry'; +export { StatusFileOptions } from './status-file-options'; +export { StatusFile } from './status-file'; export { StatusList } from './status-list'; export { StatusOptions } from './status-options'; export { Status } from './status'; diff --git a/types/nodegit/index_.d.ts b/types/nodegit/index_.d.ts index e2aed770f6..3bf55c229d 100644 --- a/types/nodegit/index_.d.ts +++ b/types/nodegit/index_.d.ts @@ -21,13 +21,13 @@ export namespace Index { } export class Index { - static entryIsConflict(entry: IndexEntry): number; + static entryIsConflict(entry: IndexEntry): boolean; static entryStage(entry: IndexEntry): number; static open(indexPath: string): Promise; add(sourceEntry: IndexEntry): number; - addAll(pathspec: Strarray, flags: number, callback: Function, payload: void): Promise; - addByPath(path: string): number; + addAll(pathspec: Strarray, flags: number, callback?: Function): Promise; + addByPath(path: string): Promise; caps(): number; checksum(): Oid; clear(): number; @@ -38,17 +38,17 @@ export class Index { entryCount(): number; getByIndex(n: number): IndexEntry; getByPath(path: string, stage: number): IndexEntry; - hasConflicts(): number; + hasConflicts(): boolean; owner(): Repository; path(): string; read(force: number): number; readTree(tree: Tree): number; remove(path: string, stage: number): number; - removeAll(pathspec: Strarray, callback: Function, payload: void): Promise; - removeByPath(path: string): number; + removeAll(pathspec: Strarray, callback?: Function): Promise; + removeByPath(path: string): Promise; removeDirectory(dir: string, stage: number): number; setCaps(caps: number): number; - updateAll(pathspec: Strarray, callback: Function, payload: void): Promise; + updateAll(pathspec: Strarray, callback?: Function): Promise; write(): number; writeTree(): Promise; writeTreeTo(repo: Repository): Promise; diff --git a/types/nodegit/merge-file-options.d.ts b/types/nodegit/merge-file-options.d.ts index 9fe6394b4e..861abaf9b8 100644 --- a/types/nodegit/merge-file-options.d.ts +++ b/types/nodegit/merge-file-options.d.ts @@ -5,4 +5,5 @@ export interface MergeFileOptions { theirLabel?: string; favor?: number; flags?: number; + [key: string]: any; } diff --git a/types/nodegit/merge-options.d.ts b/types/nodegit/merge-options.d.ts index eb5aac909a..5149422008 100644 --- a/types/nodegit/merge-options.d.ts +++ b/types/nodegit/merge-options.d.ts @@ -7,4 +7,5 @@ export class MergeOptions { defaultDriver?: string; flags?: number; recursionLimit?: number; + [key: string]: any; } diff --git a/types/nodegit/merge.d.ts b/types/nodegit/merge.d.ts index a7b262e61c..4233b725e7 100644 --- a/types/nodegit/merge.d.ts +++ b/types/nodegit/merge.d.ts @@ -55,5 +55,5 @@ export class Merge { static commits(repo: Repository, ourCommit: Commit, theirCommit: Commit, options?: MergeOptions): any; static fileInitInput(opts: MergeFileInput, version: number): number; static initOptions(opts: MergeOptions, version: number): number; - static trees(repo: Repository, ancestorTree: Tree, ourTree: Tree, theirTree: Tree, opts: MergeOptions): Promise; + static trees(repo: Repository, ancestorTree: Tree, ourTree: Tree, theirTree: Tree, opts?: MergeOptions): Promise; } diff --git a/types/nodegit/proxy-options.d.ts b/types/nodegit/proxy-options.d.ts index 19bba458cb..88f734833d 100644 --- a/types/nodegit/proxy-options.d.ts +++ b/types/nodegit/proxy-options.d.ts @@ -5,4 +5,5 @@ export class ProxyOptions { type?: number; url?: string; version?: number; + [key: string]: any; } diff --git a/types/nodegit/push-options.d.ts b/types/nodegit/push-options.d.ts index 7c589bfb91..b736325f91 100644 --- a/types/nodegit/push-options.d.ts +++ b/types/nodegit/push-options.d.ts @@ -8,4 +8,5 @@ export interface PushOptions { callbacks?: RemoteCallbacks; customHeaders?: Strarray; proxyOpts?: ProxyOptions; + [key: string]: any; } diff --git a/types/nodegit/rebase.d.ts b/types/nodegit/rebase.d.ts index 383642137e..be0b5d2c92 100644 --- a/types/nodegit/rebase.d.ts +++ b/types/nodegit/rebase.d.ts @@ -14,9 +14,9 @@ export interface RebaseOptions { } export class Rebase { - static init(repo: Repository, branch: AnnotatedCommit, upstream: AnnotatedCommit, onto: AnnotatedCommit, opts: RebaseOptions): Promise; + static init(repo: Repository, branch: AnnotatedCommit, upstream: AnnotatedCommit, onto: AnnotatedCommit, opts?: RebaseOptions): Promise; static initOptions(opts: RebaseOptions, version: number): number; - static open(repo: Repository, opts: RebaseOptions): Promise; + static open(repo: Repository, opts?: RebaseOptions): Promise; abort(): number; commit(author: Signature, committer: Signature, messageEncoding: string, message: string): Oid; diff --git a/types/nodegit/reference.d.ts b/types/nodegit/reference.d.ts index 10b21a0add..80e16c9350 100644 --- a/types/nodegit/reference.d.ts +++ b/types/nodegit/reference.d.ts @@ -21,12 +21,12 @@ export namespace Reference { export class Reference { static create(repo: Repository, name: string, id: Oid, force: number, logMessage: string): Promise; static createMatching(repo: Repository, name: string, id: Oid, force: number, currentId: Oid, logMessage: string): Promise; - static dwim(repo: Repository, id: string | Reference, callback: Function): Promise; + static dwim(repo: Repository, id: string | Reference, callback?: Function): Promise; static ensureLog(repo: Repository, refname: string): number; static hasLog(repo: Repository, refname: string): number; static isValidName(refname: string): number; static list(repo: Repository): Promise; - static lookup(repo: Repository, id: string | Reference, callback: Function): Promise; + static lookup(repo: Repository, id: string | Reference, callback?: Function): Promise; static nameToId(repo: Repository, name: string): Promise; static normalizeName(bufferOut: string, bufferSize: number, name: string, flags: number): number; static remove(repo: Repository, name: string): number; diff --git a/types/nodegit/remote.d.ts b/types/nodegit/remote.d.ts index 5f118629ea..61fdc63d1c 100644 --- a/types/nodegit/remote.d.ts +++ b/types/nodegit/remote.d.ts @@ -31,21 +31,21 @@ export class Remote { static createWithFetchspec(repo: Repository, name: string, url: string, fetch: string): Promise; static delete(repo: Repository, name: string): Promise; static initCallbacks(opts: RemoteCallbacks, version: number): number; - static isValidName(remoteName: string): number; + static isValidName(remoteName: string): boolean; static list(repo: Repository): Promise; - static lookup(repo: Repository, name: string | Remote, callback: Function): Promise; + static lookup(repo: Repository, name: string | Remote, callback?: Function): Promise; static setAutotag(repo: Repository, remote: string, value: number): number; static setPushurl(repo: Repository, remote: string, url: string): number; static setUrl(repo: Repository, remote: string, url: string): number; autotag(): number; - connect(direction: Enums.DIRECTION, callbacks: RemoteCallbacks, callback: Function): Promise; + connect(direction: Enums.DIRECTION, callbacks: RemoteCallbacks, callback?: Function): Promise; connected(): number; defaultBranch(): Promise; disconnect(): Promise; - download(refSpecs: any[], opts: FetchOptions, callback: Function): Promise; + download(refSpecs: any[], opts?: FetchOptions, callback?: Function): Promise; dup(): Promise; - fetch(refSpecs: any[], opts: FetchOptions, message: string, callback: Function): Promise; + fetch(refSpecs: any[], opts: FetchOptions, message: string, callback?: Function): Promise; free(): void; getFetchRefspecs(): Promise; @@ -55,14 +55,14 @@ export class Remote { owner(): Repository; prune(callbacks: RemoteCallbacks): number; pruneRefs(): number; - push(refSpecs: any[], options: PushOptions, callback: Function): Promise; + push(refSpecs: any[], options?: PushOptions, callback?: Function): Promise; pushurl(): string; refspecCount(): number; stats(): TransferProgress; stop(): void; updateTips(callbacks: RemoteCallbacks, updateFetchhead: number, downloadTags: number, reflogMessage: string): number; - upload(refspecs: Strarray, opts: PushOptions): number; + upload(refspecs: Strarray, opts?: PushOptions): number; url(): string; /** * Lists advertised references from a remote. You must connect to the remote before using referenceList. diff --git a/types/nodegit/repository.d.ts b/types/nodegit/repository.d.ts index fa3d235b37..b94d7bd626 100644 --- a/types/nodegit/repository.d.ts +++ b/types/nodegit/repository.d.ts @@ -18,6 +18,10 @@ import { Merge } from './merge'; import { MergeOptions } from './merge-options'; import { Refdb } from './ref-db'; import { Revwalk } from './rev-walk'; +import { StatusFile } from './status-file'; +import { StatusOptions } from './status-options'; +import { DiffLine } from './diff-line'; +import { Treebuilder } from './tree-builder'; export interface RepositoryInitOptions { description: string; @@ -46,7 +50,7 @@ export class Repository { config(): Promise; configSnapshot(): Promise; detachHead(): number; - fetchheadForeach(callback: Function): Promise; + fetchheadForeach(callback?: Function): Promise; free(): void; getNamespace(): string; @@ -57,7 +61,7 @@ export class Repository { isBare(): number; isEmpty(): number; isShallow(): number; - mergeheadForeach(callback: Function): Promise; + mergeheadForeach(callback?: Function): Promise; messageRemove(): number; odb(): Promise; path(): string; @@ -103,7 +107,7 @@ export class Repository { * Lookup reference names for a repository. */ getReferenceNames(type: Reference.TYPE): Promise; - getCommit(string: string | Oid): Promise; + getCommit(string: string | Commit| Oid): Promise; /** * Retrieve the blob represented by the oid. */ @@ -128,7 +132,7 @@ export class Repository { /** * Deletes a tag from a repository by the tag name. */ - deleteTagByName(Short: string): Promise; + deleteTagByName(Short: string): Promise; /** * Instantiate a new revision walker for browsing the Repository"s history. See also Commit.prototype.history() */ @@ -141,16 +145,16 @@ export class Repository { * Retrieve the commit that HEAD is currently pointing to */ getHeadCommit(): Promise; - createCommit(updateRef: string, author: Signature, committer: Signature, message: string, Tree: Tree | Oid | string, parents: any[]): Promise; + createCommit(updateRef: string, author: Signature, committer: Signature, message: string, Tree: Tree | Oid | string, parents: Array, callback?: Function): Promise; /** * Creates a new commit on HEAD from the list of passed in files */ - createCommitOnHead(filesToAdd: any[], author: Signature, committer: Signature, message: string): Promise; + createCommitOnHead(filesToAdd: string[], author: Signature, committer: Signature, message: string): Promise; /** * Create a blob from a buffer */ createBlobFromBuffer(buffer: Buffer): Oid; - treeBuilder(tree: Tree): any; + treeBuilder(tree: Tree): Promise; /** * Gets the default signature for the default user and now timestamp */ @@ -158,20 +162,20 @@ export class Repository { /** * Lists out the remotes in the given repository. */ - getRemotes(Optional: Function): Promise; + getRemotes(callback?: Function): Promise; /** * Gets a remote from the repo */ - getRemote(remote: string | Remote, callback: Function): Promise; + getRemote(remote: string | Remote, callback?: Function): Promise; /** * Fetches from a remote */ - fetch(remote: string | Remote, fetchOptions: Object | FetchOptions): Promise; + fetch(remote: string | Remote, fetchOptions?: FetchOptions): Promise; /** * Fetches from all remotes. This is done in series due to deadlocking issues with fetching from many remotes that can happen. */ - fetchAll(fetchOptions: Object | FetchOptions, callback: Function): Promise; - mergeBranches(to: string | Reference, from: string | Reference, signature: Signature, mergePreference: Merge.PREFERENCE, mergeOptions: MergeOptions): Promise; + fetchAll(fetchOptions?: FetchOptions, callback?: Function): Promise; + mergeBranches(to: string | Reference, from: string | Reference, signature: Signature, mergePreference: Merge.PREFERENCE, mergeOptions?: MergeOptions): Promise; /** * Rebases a branch onto another branch */ @@ -180,11 +184,11 @@ export class Repository { /** * Get the status of a repo to it's working directory */ - getStatus(opts: any): Promise; + getStatus(opts?: StatusOptions): Promise; /** * Get extended statuses of a repo to it's working directory. Status entries have status, headToIndex delta, and indexToWorkdir deltas */ - getStatusExt(opts: any): Promise; + getStatusExt(opts?: StatusOptions): Promise; /** * Get the names of the submodules in the repository. */ @@ -192,19 +196,19 @@ export class Repository { /** * This will set the HEAD to point to the reference and then attempt to update the index and working tree to match the content of the latest commit on that reference */ - checkoutRef(reference: Reference, opts: Object | CheckoutOptions): Promise; + checkoutRef(reference: Reference, opts?: CheckoutOptions): Promise; /** * This will set the HEAD to point to the local branch and then attempt to update the index and working tree to match the content of the latest commit on that branch */ - checkoutBranch(branch: string | Reference, opts: Object | CheckoutOptions): Promise; + checkoutBranch(branch: string | Reference, opts?: CheckoutOptions): Promise; /** * Stages or unstages line selection of a specified file */ - stageFilemode(filePath: string | any[], stageNew: boolean): Promise; + stageFilemode(filePath: string | string[], stageNew: boolean): Promise; /** * Stages or unstages line selection of a specified file */ - stageLines(filePath: string, newLines: any[], isStaged: boolean): Promise; + stageLines(filePath: string, newLines: DiffLine[], isStaged: boolean): Promise; /** * Returns true if the repository is in the default NONE state. */ @@ -236,7 +240,7 @@ export class Repository { /** * Discard line selection of a specified file. Assumes selected lines are unstaged. */ - discardLines(filePath: string, selectedLines: any[]): Promise; + discardLines(filePath: string, selectedLines: DiffLine[]): Promise; /** * Grabs a fresh copy of the index from the repository. Invalidates all previously grabbed indexes */ diff --git a/types/nodegit/rev-walk.d.ts b/types/nodegit/rev-walk.d.ts index 59611cf62b..065c515743 100644 --- a/types/nodegit/rev-walk.d.ts +++ b/types/nodegit/rev-walk.d.ts @@ -38,7 +38,7 @@ export class Revwalk { /** * Walk the history from the given oid. The callback is invoked for each commit; When the walk is over, the callback is invoked with (null, null). */ - walk(oid: Oid, callback: Function): Commit; + walk(oid: Oid, callback?: Function): Commit; /** * Walk the history grabbing commits until the checkFn called with the current commit returns false. */ diff --git a/types/nodegit/revert.d.ts b/types/nodegit/revert.d.ts index 16154aea76..1f9d4a2677 100644 --- a/types/nodegit/revert.d.ts +++ b/types/nodegit/revert.d.ts @@ -5,10 +5,11 @@ import { Commit } from './commit'; import { Index } from './index'; export interface RevertOptions { - version: number; - mainline: number; - mergeOpts: MergeOptions; - checkoutOpts: CheckoutOptions; + version?: number; + mainline?: number; + mergeOpts?: MergeOptions; + checkoutOpts?: CheckoutOptions; + [key: string]: any; } export class Revert { @@ -16,5 +17,5 @@ export class Revert { /** * Reverts the given commit against the given "our" commit, producing an index that reflects the result of the revert. */ - static commit(repo: Repository, revertCommit: Commit, ourCommit: Commit, mainline: number, mergeOptions: MergeOptions): Promise; + static commit(repo: Repository, revertCommit: Commit, ourCommit: Commit, mainline: number, mergeOptions?: MergeOptions): Promise; } diff --git a/types/nodegit/stash.d.ts b/types/nodegit/stash.d.ts index 494631928c..68d61d0e0f 100644 --- a/types/nodegit/stash.d.ts +++ b/types/nodegit/stash.d.ts @@ -37,10 +37,10 @@ export interface StashApplyOptions { } export class Stash { - static apply(repo: Repository, index: number, options: StashApplyOptions): Promise; + static apply(repo: Repository, index: number, options?: StashApplyOptions): Promise; static applyInitOptions(opts: StashApplyOptions, version: number): number; static drop(repo: Repository, index: number): Promise; - static foreach(repo: Repository, callback: Function, payload: any): Promise; - static pop(repo: Repository, index: number, options: StashApplyOptions): Promise; + static foreach(repo: Repository, callback?: Function): Promise; + static pop(repo: Repository, index: number, options?: StashApplyOptions): Promise; static save(repo: Repository, stasher: Signature, message: string, flags: number): Promise; } diff --git a/types/nodegit/status-entry.d.ts b/types/nodegit/status-entry.d.ts index bc2ab62a12..59de1a9760 100644 --- a/types/nodegit/status-entry.d.ts +++ b/types/nodegit/status-entry.d.ts @@ -1,7 +1,7 @@ import { DiffDelta } from './diff-delta'; export class StatusEntry { - status: number; - headToIndex: DiffDelta; - indexToWorkdir: DiffDelta; + status(): number; + headToIndex(): DiffDelta; + indexToWorkdir(): DiffDelta; } diff --git a/types/nodegit/status-file-options.d.ts b/types/nodegit/status-file-options.d.ts new file mode 100644 index 0000000000..e3852cf0e6 --- /dev/null +++ b/types/nodegit/status-file-options.d.ts @@ -0,0 +1,8 @@ +import { StatusEntry } from './status-entry'; + +export interface StatusFileOptions { + path?: string; + status?: number; + entry?: StatusEntry; + [key: string]: any; +} diff --git a/types/nodegit/status-file.d.ts b/types/nodegit/status-file.d.ts new file mode 100644 index 0000000000..b34a0f234f --- /dev/null +++ b/types/nodegit/status-file.d.ts @@ -0,0 +1,20 @@ +import { DiffDelta } from './diff-delta'; +import { StatusFileOptions } from './status-file-options'; + +export class StatusFile { + constructor(args: StatusFileOptions); + headToIndex(): DiffDelta; + indexToWorkdir(): DiffDelta; + inIndex(): boolean; + inWorkingTree(): boolean; + isConflicted(): boolean; + isDeleted(): boolean; + isIgnored(): boolean; + isModified(): boolean; + isNew(): boolean; + isRenamed(): boolean; + isTypechange(): boolean; + path(): string; + status(): string[]; + statusBit(): number; +} diff --git a/types/nodegit/status-list.d.ts b/types/nodegit/status-list.d.ts index 42119bbfd4..1b470ceb71 100644 --- a/types/nodegit/status-list.d.ts +++ b/types/nodegit/status-list.d.ts @@ -3,7 +3,7 @@ import { DiffPerfdata } from './diff-perf-data'; import { StatusOptions } from './status-options'; export class StatusList { - static create(repo: Repository, opts: StatusOptions): Promise; + static create(repo: Repository, opts?: StatusOptions): Promise; entrycount(): number; diff --git a/types/nodegit/status-options.d.ts b/types/nodegit/status-options.d.ts index 9f75bbe96d..363dcd1fbb 100644 --- a/types/nodegit/status-options.d.ts +++ b/types/nodegit/status-options.d.ts @@ -5,4 +5,5 @@ export interface StatusOptions { show?: number; flags?: number; pathspec?: Strarray; + [key: string]: any; } diff --git a/types/nodegit/status.d.ts b/types/nodegit/status.d.ts index 1059dd6bff..5b657d1cc5 100644 --- a/types/nodegit/status.d.ts +++ b/types/nodegit/status.d.ts @@ -1,7 +1,7 @@ import { Repository } from './repository'; import { StatusList } from './status-list'; -import { StatusEntry } from './status-entry'; import { StatusOptions } from './status-options'; +import { StatusEntry } from './status-entry'; export namespace Status { const enum STATUS { @@ -50,7 +50,7 @@ export namespace Status { export class Status { static byIndex(statuslist: StatusList, idx: number): StatusEntry; static file(repo: Repository, path: string): number; - static foreach(repo: Repository, callback: Function, payload: any): Promise; - static foreachExt(repo: Repository, opts: StatusOptions, callback: Function, payload: any): Promise; + static foreach(repo: Repository, callback?: Function): Promise; + static foreachExt(repo: Repository, opts?: StatusOptions, callback?: Function): Promise; static shouldIgnore(ignored: number, repo: Repository, path: string): number; } diff --git a/types/nodegit/submodule-update-options.d.ts b/types/nodegit/submodule-update-options.d.ts index d96320204b..5be827b368 100644 --- a/types/nodegit/submodule-update-options.d.ts +++ b/types/nodegit/submodule-update-options.d.ts @@ -6,4 +6,5 @@ export interface SubmoduleUpdateOptions { checkoutOpts?: CheckoutOptions; fetchOpts?: FetchOptions; cloneCheckoutStrategy?: number; + [key: string]: any; } diff --git a/types/nodegit/submodule.d.ts b/types/nodegit/submodule.d.ts index c53aee7a3d..4ac5ce3ac6 100644 --- a/types/nodegit/submodule.d.ts +++ b/types/nodegit/submodule.d.ts @@ -46,7 +46,7 @@ export namespace Submodule { export class Submodule { static addSetup(repo: Repository, url: string, path: string, useGitLink: number): Promise; - static foreach(repo: Repository, callback: Function, payload: any): Promise; + static foreach(repo: Repository, callback?: Function): Promise; static lookup(repo: Repository, name: string): Promise; static resolveUrl(repo: Repository, url: string): Promise; static setBranch(repo: Repository, name: string, branch: string): number; @@ -80,7 +80,7 @@ export class Submodule { * * */ - update(init: number, options: SubmoduleUpdateOptions): Promise; + update(init: number, options?: SubmoduleUpdateOptions): Promise; updateStrategy(): number; url(): string; wdId(): Oid; diff --git a/types/nodegit/tree.d.ts b/types/nodegit/tree.d.ts index fd2674a025..50c29e8a3f 100644 --- a/types/nodegit/tree.d.ts +++ b/types/nodegit/tree.d.ts @@ -20,7 +20,7 @@ export class Tree { /** * Retrieves the tree pointed to by the oid */ - static lookup(repo: Repository, id: string | Oid | Tree, callback: Function): Promise; + static lookup(repo: Repository, id: string | Oid | Tree, callback?: Function): Promise; entryById(id: Oid): TreeEntry; _entryByIndex(idx: number): TreeEntry; @@ -38,11 +38,11 @@ export class Tree { /** * Diff two trees */ - diff(tree: Tree, callback: Function): Promise; + diff(tree: Tree, callback?: Function): Promise; /** * Diff two trees with options */ - diffWithOptions(tree: Tree, options: Object, callback: Function): Promise; + diffWithOptions(tree: Tree, options?: Object, callback?: Function): Promise; /** * Get an entry at the ith position. */ diff --git a/types/nodegit/tsconfig.json b/types/nodegit/tsconfig.json index 4ba1bdece6..e097a77133 100644 --- a/types/nodegit/tsconfig.json +++ b/types/nodegit/tsconfig.json @@ -36,6 +36,7 @@ "clone.d.ts", "commit.d.ts", "config.d.ts", + "convenient-hunk.d.ts", "convenient-patch.d.ts", "cred-user-pass-payload.d.ts", "cred-username.d.ts", @@ -47,7 +48,6 @@ "diff-binary.d.ts", "diff-delta.d.ts", "diff-file.d.ts", - "diff-hunk.d.ts", "diff-line.d.ts", "diff-options.d.ts", "diff-perf-data.d.ts", @@ -102,6 +102,8 @@ "signature.d.ts", "stash.d.ts", "status-entry.d.ts", + "status-file-options.d.ts", + "status-file.d.ts", "status-list.d.ts", "status-options.d.ts", "status.d.ts", @@ -117,4 +119,4 @@ "tree-update.d.ts", "tree.d.ts" ] -} \ No newline at end of file +} diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index 6a587bb720..bee4649e94 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Nodemailer 4.2 +// Type definitions for Nodemailer 4.3 // Project: https://github.com/nodemailer/nodemailer // Definitions by: Rogier Schouten // Piotr Roszatycki diff --git a/types/nodemailer/lib/addressparser.d.ts b/types/nodemailer/lib/addressparser.d.ts index dbf5cda468..be42c1deed 100644 --- a/types/nodemailer/lib/addressparser.d.ts +++ b/types/nodemailer/lib/addressparser.d.ts @@ -19,6 +19,6 @@ declare namespace addressparser { * @param str Address field * @return An array of address objects */ -declare function addressparser(address: string): addressparser.Address; +declare function addressparser(address: string): addressparser.Address[]; export = addressparser; diff --git a/types/nodemailer/lib/mailer/mail-message.d.ts b/types/nodemailer/lib/mailer/mail-message.d.ts index 78f9c5d23d..2216680edc 100644 --- a/types/nodemailer/lib/mailer/mail-message.d.ts +++ b/types/nodemailer/lib/mailer/mail-message.d.ts @@ -16,6 +16,8 @@ declare class MailMessage { resolveAll(callback: (err?: Error | null, data?: Mail.Options) => void): void; + normalize(callback: (err?: Error | null, data?: Mail.Options) => void): void; + setMailerHeader(): void; setPriorityHeaders(): void; diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index cb2cd9641f..6bf4935e0a 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1069,7 +1069,9 @@ namespace mailcomposer_build_test { namespace addressparser_test { const input = 'andris@tr.ee'; - addressparser(input); + const result = addressparser(input); + const address: string = result[0].address; + const name: string = result[0].name; } // base64 diff --git a/types/nouislider/index.d.ts b/types/nouislider/index.d.ts index 4389b87d49..0e070e89c7 100644 --- a/types/nouislider/index.d.ts +++ b/types/nouislider/index.d.ts @@ -8,102 +8,102 @@ export = noUiSlider; export as namespace noUiSlider; declare namespace noUiSlider { - /** + /** * To create a slider, call noUiSlider.create() with an element and your options. */ - function create(target: HTMLElement, options: Options): void; + function create(target: HTMLElement, options: Options): void; - interface Options { - /** + interface Options { + /** * The start option sets the number of handles and their start positions, relative to range. */ - start: number | number[] | number[][]; - /** + start: number | number[] | number[][]; + /** * All values on the slider are part of a range. The range has a minimum and maximum value. * The minimum value cannot be equal to the maximum value. */ - range: Object; - /** + range: { [key: string]: number | number[] }; + /** * The connect setting can be used to control the (green) bar between the handles, or the edges of the slider. - * Pass an array with a boolean for every connecting element, including the edges of the slider. + * Pass an array with a boolean for every connecting element, including the edges of the slider. * The length of this array must match the handle count + 1. * Setting true sets the bars between the handles, but not between the handles and the sliders edges. */ - connect?: boolean | boolean[]; - /** + connect?: boolean | boolean[]; + /** * When using two handles, the minimum distance between the handles can be set using the margin option. * The margin value is relative to the value set in 'range'. * This option is only available on standard linear sliders. */ - margin?: number; - /** + margin?: number; + /** * The limit option is the opposite of the margin option, * limiting the maximum distance between two handles. * As with the margin option, the limit option can only be used on linear sliders. */ - limit?: number; - /** + limit?: number; + /** * Padding limits how close to the slider edges handles can be. */ - padding?: number; - /** + padding?: number; + /** * By default, the slider slides fluently. * In order to make the handles jump between intervals, you can use this option. * The step option is relative to the values provided to range. */ - step?: number; - /** + step?: number; + /** * The orientation setting can be used to set the slider to "vertical" or "horizontal". * Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one. * You can use any unit you want, including % or px. */ - orientation?: "vertical" | "horizontal"; - /** + orientation?: 'vertical' | 'horizontal'; + /** * By default the sliders are top-to-bottom and left-to-right, * but you can change this using the direction option, * which decides where the upper side of the slider is. */ - direction?: "ltr" | "rtl"; - /** - * noUiSlider can provide a basic tooltip without using its events system. - * Set the tooltips option to true to enable. - * This option can also accept formatting options to format the tooltips content. + direction?: 'ltr' | 'rtl'; + /** + * noUiSlider can provide a basic tooltip without using its events system. + * Set the tooltips option to true to enable. + * This option can also accept formatting options to format the tooltips content. * In that case, pass an array with a formatter for each handle, true to use the default or false to display no tooltip. */ - tooltips?: boolean | Object | ((...args:any[]) => any); - /** + tooltips?: boolean | Object | ((...args: any[]) => any); + /** * Set the animate option to false to prevent the slider from animating to a new value with when calling .val(). */ - animate?: boolean; - /** + animate?: boolean; + /** * The animationDuration option can be used to set the animation speed assumed by the slider library. * In addition to this, you must manually set the CSS (-webkit-)transition property for the .noUi-state-tap .noUi-origin selector. */ - animationDuration?: number; - /** + animationDuration?: number; + /** * When a non-linear slider has been configured, the snap option can be set to true to force the slider to jump * between the specified values. */ - snap?: boolean; - /** + snap?: boolean; + /** * All values on the slider are part of a range. The range has a minimum and maximum value. */ - behaviour?: string; - /** + behaviour?: string; + /** * To format the slider output, noUiSlider offers a format option. * Simply specify to and from functions to encode and decode the values. * See manual formatting to the right for usage information. * By default, noUiSlider will format output with 2 decimals. */ - format?: Object | ((...args:any[]) => any); - /** + format?: Object | ((...args: any[]) => any); + /** * Allows you to generate points along the slider. */ - pips?: PipsOptions; - } + pips?: PipsOptions; + } - interface PipsOptions { - /** + interface PipsOptions { + /** * The 'range' mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified. * * The 'steps', like 'range', uses the slider range. In steps mode, a pip is generated for every step. @@ -118,83 +118,92 @@ declare namespace noUiSlider { * The 'values' mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode. * */ - mode: "range" | "steps" | "positions" | "count" | "values"; - /** + mode: 'range' | 'steps' | 'positions' | 'count' | 'values'; + /** * Range Mode: percentage for range mode * Step Mode: step number for steps * Positions Mode: percentage-based positions on the slider * Count Mode: positions between pips */ - density?: number; - /** + density?: number; + /** * Step Mode: The filter option can be used to filter the generated pips. * The filter function must return 0 (no value), 1 (large value) or 2 (small value). */ - filter?: (...args: any[]) => PipFilterResult; - /** + filter?: (...args: any[]) => PipFilterResult; + /** * format for step mode * see noUiSlider format */ - format?: Object | ((...args:any[]) => any); - /** + format?: Object | ((...args: any[]) => any); + /** * * values for positions and values mode * number pips for count mode */ - values?: number | number[]; - /** + values?: number | number[]; + /** * stepped option for positions, values and count mode */ - stepped?: boolean; - } + stepped?: boolean; + } - const enum PipFilterResult { - NoValue, - LargeValue, - SmallValue, - } + const enum PipFilterResult { + NoValue, + LargeValue, + SmallValue, + } - interface Callback { - /** + interface Callback { + /** * Array for both one-handle and two-handle sliders. It contains the current slider values, * with formatting applied. */ - (values: any[], handle: number, unencodedValues: number[]): void; - } + (values: any[], handle: number, unencodedValues: number[]): void; + } - interface noUiSlider { - /** + interface noUiSlider { + /** * Bind event to the slider. */ - on(eventName: string, callback: Callback): void; - /** + on(eventName: string, callback: Callback): void; + /** * Unbind event to the slider. */ - off(eventName: string): void; - /** + off(eventName: string): void; + /** * Destroy's the slider. */ - destroy(): void; - /** + destroy(): void; + /** * To get the current slider value. For one-handle sliders, calling .get() will return the value. * For two-handle sliders, an array[value, value] will be returned. */ - get(): number | number[]; - /** + get(): number | number[]; + /** * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. * If you have configured the slider to use one handle, you can change the current value by passing * a number to the .set() method. If you have two handles, pass an array. One-handled sliders * will also accept arrays. Within an array, you can set one position to null * if you want to leave a handle unchanged. */ - set(value: number | (number | null)[]): void; - /** + set(value: number | (number | null)[]): void; + /** * To return to the initial slider values, you can use the .reset() method. This will only reset the slider values. */ - reset(): void; - } + reset(): void; + /** + * Exposes the options used to create the noUiSlider instance + */ + options: Options; + /** + * method that can change the 'margin', 'limit', 'step', 'range', 'animate' and 'snap' options. + * All other options require changes to the slider's HTML or event bindings. + */ + updateOptions(newOptions: Options, fireSetEvent?: boolean): void; + } - interface Instance extends HTMLElement { - noUiSlider: noUiSlider; - } + interface Instance extends HTMLElement { + noUiSlider: noUiSlider; + } } diff --git a/types/nunjucks/index.d.ts b/types/nunjucks/index.d.ts index 002f8b93f8..d307bd27d5 100644 --- a/types/nunjucks/index.d.ts +++ b/types/nunjucks/index.d.ts @@ -1,148 +1,139 @@ -// Type definitions for nunjucks +// Type definitions for nunjucks 3.0 // Project: http://mozilla.github.io/nunjucks/ // Definitions by: Ruben Slabbert // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +export function render(name: string, context?: object): string; +export function render(name: string, context?: object, callback?: (err: any, res: string) => any): void; -declare namespace Nunjucks { - function render(name: string, context?: Object): string; - function render(name: string, context?: Object, callback?: (err: any, res: string) => any): void; +export function renderString(src: string, context: object): string; +export function renderString(src: string, context: object, callback?: (err: any, res: string) => any): void; - function renderString(src: string, context: Object): string; - function renderString(src: string, context: Object, callback?: (err: any, res: string) => any): void; +export function compile(src: string, env?: Environment, callback?: (err: any, res: Template) => any): Template; - function compile(src: string, env?: Environment): Template; - function compile(src: string, env?: Environment, callback?: (err: any, res: Template) => any): Template; +export function precompile(path: string, opts?: PrecompileOptions): string; +export function precompileString(src: string, opts?: PrecompileOptions): string; - function precompile(path: string, opts?: PrecompileOptions): string; - function precompileString(src: string, opts?: PrecompileOptions): string; - - interface PrecompileOptions { - name?: string; - asFunction?: boolean; - force?: boolean; - env?: Environment; - include?: string[]; - exclude?: string[]; - wrapper?(templates: { name: string, template: string }, opts: PrecompileOptions): string; - } - - class Template { - constructor(src: string, env?: Environment, eagerCompile?: boolean); - render(context?: Object): string; - render(context?: Object, callback?: (err: any, res: string) => any): void; - } - - function configure(options: ConfigureOptions): Environment; - function configure(path: string, options?: ConfigureOptions): Environment; - function configure(path: string[], options?: ConfigureOptions): Environment; - - interface ConfigureOptions { - autoescape?: boolean; - throwOnUndefined?: boolean; - trimBlocks?: boolean; - lstripBlocks?: boolean; - watch?: boolean; - noCache?: boolean; - web?: { - useCache?: boolean, - async?: boolean - }; - express?: Object; - tags?: { - blockStart?: string, - blockEnd?: string, - variableStart?: string, - variableEnd?: string, - commentStart?: string, - commentEnd?: string - }; - } - - class Environment { - options: { - autoescape: boolean; - }; - - constructor(); - constructor(loader: ILoader, opts?: ConfigureOptions); - constructor(loaders: ILoader[], opts?: ConfigureOptions); - - render(name: string, context?: Object): string; - render(name: string, context?: Object, callback?: (err: any, res: string) => any): void; - - renderString(name: string, context: Object): string; - renderString(name: string, context: Object, callback?: (err: any, res: string) => any): void; - - addFilter(name: string, func: (...args: any[]) => any, async?: boolean): void; - getFilter(name: string): void; - - addExtension(name: string, ext: Extension): void; - removeExtension(name: string): void; - getExtension(name: string): Extension; - hasExtension(name: string): void; - - addGlobal(name: string, value: any): void; - - getTemplate(name: string, eagerCompile?: boolean): Template; - getTemplate(name: string, eagerCompile?: boolean, callback?: (err: any, templ: Template) => Template): void; - - express(app: Object): void; - } - - interface Extension { - tags: string[]; - // Parser API is undocumented it is suggested to check the source: https://github.com/mozilla/nunjucks/blob/master/src/parser.js - parse(parser: any, nodes: any, lexer: any): any; - } - - function installJinjaCompat(): void; - - interface ILoader { - async?: boolean; - getSource(name: string): LoaderSource; - extend?(extender: ILoader): ILoader; - } - - // Needs both Loader and ILoader since nunjucks uses a custom object system - // Object system is also responsible for the extend methods - class Loader { - on(name: string, func: (...args: any[]) => any): void; - emit(name: string, ...args: any[]): void; - resolve(from: string, to: string): string; - isRelative(filename: string): boolean; - extend(toExtend: ILoader): ILoader; - } - - interface LoaderSource { - src: string; - path: string; - noCache: boolean; - } - - interface FileSystemLoaderOptions { - /** if true, the system will automatically update templates when they are changed on the filesystem */ - watch?: boolean; - - /** if true, the system will avoid using a cache and templates will be recompiled every single time */ - noCache?: boolean; - } - - class FileSystemLoader extends Loader implements ILoader { - init(searchPaths: string[], opts: any): void; - getSource(name: string): LoaderSource; - constructor(searchPaths?: string | string[], opts?: FileSystemLoaderOptions); - } - - export class WebLoader implements ILoader { - constructor(baseUrl: string, opts?: any); - getSource(name: string): LoaderSource; - } - - class PrecompiledLoader extends Loader implements ILoader { - init(searchPaths: string[], opts: any): void; - getSource(name: string): LoaderSource; - } +export interface PrecompileOptions { + name?: string; + asFunction?: boolean; + force?: boolean; + env?: Environment; + include?: string[]; + exclude?: string[]; + wrapper?(templates: { name: string, template: string }, opts: PrecompileOptions): string; } -export = Nunjucks; +export class Template { + constructor(src: string, env?: Environment, eagerCompile?: boolean); + render(context?: object): string; + render(context?: object, callback?: (err: any, res: string) => any): void; +} + +export function configure(options: ConfigureOptions): Environment; +export function configure(path: string | string[], options?: ConfigureOptions): Environment; + +export interface ConfigureOptions { + autoescape?: boolean; + throwOnUndefined?: boolean; + trimBlocks?: boolean; + lstripBlocks?: boolean; + watch?: boolean; + noCache?: boolean; + web?: { + useCache?: boolean, + async?: boolean + }; + express?: object; + tags?: { + blockStart?: string, + blockEnd?: string, + variableStart?: string, + variableEnd?: string, + commentStart?: string, + commentEnd?: string + }; +} + +export class Environment { + options: { + autoescape: boolean; + }; + + constructor(loader?: ILoader | ILoader[] | null, opts?: ConfigureOptions); + render(name: string, context?: object): string; + render(name: string, context?: object, callback?: (err: any, res: string) => any): void; + + renderString(name: string, context: object): string; + renderString(name: string, context: object, callback?: (err: any, res: string) => any): void; + + addFilter(name: string, func: (...args: any[]) => any, async?: boolean): void; + getFilter(name: string): void; + + addExtension(name: string, ext: Extension): void; + removeExtension(name: string): void; + getExtension(name: string): Extension; + hasExtension(name: string): void; + + addGlobal(name: string, value: any): void; + + getTemplate(name: string, eagerCompile?: boolean): Template; + getTemplate(name: string, eagerCompile?: boolean, callback?: (err: any, templ: Template) => Template): void; + + express(app: object): void; +} + +export interface Extension { + tags: string[]; + // Parser API is undocumented it is suggested to check the source: https://github.com/mozilla/nunjucks/blob/master/src/parser.js + parse(parser: any, nodes: any, lexer: any): any; +} + +export function installJinjaCompat(): void; + +export interface ILoader { + async?: boolean; + getSource(name: string): LoaderSource; + extend?(extender: ILoader): ILoader; +} + +// Needs both Loader and ILoader since nunjucks uses a custom object system +// Object system is also responsible for the extend methods +export class Loader { + on(name: string, func: (...args: any[]) => any): void; + emit(name: string, ...args: any[]): void; + resolve(from: string, to: string): string; + isRelative(filename: string): boolean; + extend(toExtend: ILoader): ILoader; +} + +export interface LoaderSource { + src: string; + path: string; + noCache: boolean; +} + +export interface FileSystemLoaderOptions { + /** if true, the system will automatically update templates when they are changed on the filesystem */ + watch?: boolean; + + /** if true, the system will avoid using a cache and templates will be recompiled every single time */ + noCache?: boolean; +} + +export class FileSystemLoader extends Loader implements ILoader { + init(searchPaths: string[], opts: any): void; + getSource(name: string): LoaderSource; + constructor(searchPaths?: string | string[], opts?: FileSystemLoaderOptions); +} + +export class WebLoader implements ILoader { + constructor(baseUrl: string, opts?: any); + getSource(name: string): LoaderSource; +} + +export class PrecompiledLoader extends Loader implements ILoader { + init(searchPaths: string[], opts: any): void; + getSource(name: string): LoaderSource; +} diff --git a/types/nunjucks/nunjucks-tests.ts b/types/nunjucks/nunjucks-tests.ts index 7407cc65ba..9f3afcddfe 100644 --- a/types/nunjucks/nunjucks-tests.ts +++ b/types/nunjucks/nunjucks-tests.ts @@ -1,27 +1,35 @@ - import nunjucks = require("nunjucks"); - nunjucks.configure({ autoescape: false }); let rendered = nunjucks.render("./noexists.html"); -let ctx = { items: ["Hello", "this", "is", "for", "testing"] }; -let src = "{% for item in items %}{{item}}{% endfor %}"; +nunjucks.render('foo.html', { username: 'James' }); +nunjucks.render('async.html', (err: any, res: string) => {}); + +const ctx = { items: ["Hello", "this", "is", "for", "testing"] }; +const src = "{% for item in items %}{{item}}{% endfor %}"; rendered = nunjucks.renderString(src, ctx); +nunjucks.renderString('Hello {{ username }}', { username: 'James' }); -let compiled = nunjucks.compile(src); +const compiled = nunjucks.compile(src); rendered = compiled.render(ctx); +nunjucks.compile('Hello {{ username }}').render({ username: 'James' }); rendered = nunjucks.precompileString(src, { name: "TestyWesty" }); -let template = new nunjucks.Template(src); +const template = new nunjucks.Template(src); rendered = template.render(ctx); let env = nunjucks.configure({ autoescape: false }); +nunjucks.configure('/views'); +nunjucks.configure('views', { + autoescape: true, + watch: true +}); rendered = env.renderString(src, ctx); env.addExtension("SpawnGlitter", { diff --git a/types/nunjucks/tsconfig.json b/types/nunjucks/tsconfig.json index 39cf9bfbca..5824ce2f1f 100644 --- a/types/nunjucks/tsconfig.json +++ b/types/nunjucks/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", "nunjucks-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/nunjucks/tslint.json b/types/nunjucks/tslint.json index a41bf5d19a..2c7c1bed53 100644 --- a/types/nunjucks/tslint.json +++ b/types/nunjucks/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 + "interface-name": false } } diff --git a/types/o.js/index.d.ts b/types/o.js/index.d.ts index 7cca909391..b0fd413068 100644 --- a/types/o.js/index.d.ts +++ b/types/o.js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for o.js v0.3.3 +// Type definitions for o.js v0.3.4 // Project: https://github.com/janhommes/o.js -// Definitions by: Matteo Antony Mistretta , Brad Zacher , Jan Hommes +// Definitions by: Matteo Antony Mistretta , Brad Zacher , Jan Hommes , Jean-Christophe Chalte // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare module 'o.js' { import Q = require("q"); @@ -19,6 +20,9 @@ declare module 'o.js' { username ?: string password ?: string isAsync ?: boolean + isCors ?: boolean + isHashRoute ?: boolean + appending ?: string } interface OHandler { diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index 93e3e9398b..a423f48a58 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robbie Van Gorkom , // Charles Irick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 import { Request, RequestHandler } from "express"; diff --git a/types/oauth2orize/index.d.ts b/types/oauth2orize/index.d.ts index 3e2d31b564..793c41cdc2 100644 --- a/types/oauth2orize/index.d.ts +++ b/types/oauth2orize/index.d.ts @@ -2,47 +2,37 @@ // Project: https://github.com/jaredhanson/oauth2orize/ // Definitions by: Wonshik Kim , Kei Son , Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// import { ServerRequest, ServerResponse } from "http"; -interface OAuth2 { +export interface OAuth2 { client: any; - user: any; - transactionID: string; - redirectURI: string; - req: OAuth2Req; - info: OAuth2Info; } -interface OAuth2Req { +export interface OAuth2Req { clientID: string; - redirectURI: string; - scope: string; - state: string; - type: string; - transactionID: string; } -interface OAuth2Info { +export interface OAuth2Info { scope: string; } export interface MiddlewareRequest extends ServerRequest { oauth2?: OAuth2; - user?: any; } @@ -51,7 +41,7 @@ export interface ServerOptions { loadTransaction: boolean; } -export const createServer: (options?: ServerOptions) => OAuth2Server; +export function createServer(options?: ServerOptions): OAuth2Server; export interface AuthorizeOptions { idLength?: number; @@ -68,33 +58,31 @@ export interface ErrorHandlerOptions { mode?: string; } -type MiddlewareFunction = (req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; +export type MiddlewareFunction = (req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; -type MiddlewareErrorFunction = (err: Error, req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; +export type MiddlewareErrorFunction = (err: Error, req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; -type MiddlewareNextFunction = (err?: Error) => void; +export type MiddlewareNextFunction = (err?: Error) => void; -type ValidateFunction = (clientId: string, redirectURI: string, validated: (err: Error | null, client?: any, redirectURI?: string) => void) => void; +export type ValidateFunction = (clientId: string, redirectURI: string, validated: (err: Error | null, client?: any, redirectURI?: string) => void) => void; -type ImmediateFunction = (client: any, user: any, scope: string[], type: string, areq: any, done: (err: Error | null, allow: boolean, info: any, locals: any) => void) => void; +export type ImmediateFunction = (client: any, user: any, scope: string[], type: string, areq: any, done: (err: Error | null, allow: boolean, info: any, locals: any) => void) => void; -type DecisionParseFunction = (req: MiddlewareRequest, done: (err: Error | null, params: any) => void) => void; +export type DecisionParseFunction = (req: MiddlewareRequest, done: (err: Error | null, params: any) => void) => void; -type SerializeClientFunction = (client: any, done: SerializeClientDoneFunction) => void; -type SerializeClientDoneFunction = (err: Error | null, id: string) => void; +export type SerializeClientFunction = (client: any, done: SerializeClientDoneFunction) => void; +export type SerializeClientDoneFunction = (err: Error | null, id: string) => void; -type DeserializeClientFunction = (id: string, done: DeserializeClientDoneFunction) => void; -type DeserializeClientDoneFunction = (err: Error | null, client?: any | boolean) => void; +export type DeserializeClientFunction = (id: string, done: DeserializeClientDoneFunction) => void; +export type DeserializeClientDoneFunction = (err: Error | null, client?: any | boolean) => void; -type IssueGrantCodeFunction = (client: any, redirectUri: string, user: any, res: any, issued: (err: Error | null, code?: string) => void) => void; +export type IssueGrantCodeFunction = (client: any, redirectUri: string, user: any, res: any, issued: (err: Error | null, code?: string) => void) => void; -type IssueGrantTokenFunction = (client: any, user: any, ares: any, issued: (err: Error | null, code?: string, params?: any) => void) => void; +export type IssueGrantTokenFunction = (client: any, user: any, ares: any, issued: (err: Error | null, code?: string, params?: any) => void) => void; +export type IssueExchangeCodeFunction = (client: any, code: string, redirectURI: string, issued: ExchangeDoneFunction) => void; -type IssueExchangeCodeFunction = (client: any, code: string, redirectURI: string, issued: ExchangeDoneFunction) => void; - -type ExchangeDoneFunction = (err: Error | null, accessToken?: string | boolean, refreshToken?: string, params?: any) => void; - +export type ExchangeDoneFunction = (err: Error | null, accessToken?: string | boolean, refreshToken?: string, params?: any) => void; export class OAuth2Server { grant(type: string, fn: MiddlewareFunction): OAuth2Server; diff --git a/types/oauth2orize/oauth2orize-tests.ts b/types/oauth2orize/oauth2orize-tests.ts index 49d7c94794..84d9fe95e9 100644 --- a/types/oauth2orize/oauth2orize-tests.ts +++ b/types/oauth2orize/oauth2orize-tests.ts @@ -17,19 +17,20 @@ server.grant(oauth2orize.grant.code((client, redirectURI, user, ares, done) => { // }); })); - // Register Exchanges -class AuthorizationCode { - static findOne(code: string, callback: (err: Error, code: { - clientId: string, userId: string, redirectURI: string, scope: string - }) => void): void {} -} +function findOne(code: string, callback: (err: Error, code: { + clientId: string, userId: string, redirectURI: string, scope: string +}) => void): void {} server.exchange(oauth2orize.exchange.code((client, code, redirectURI, done) => { - AuthorizationCode.findOne(code, (err, code) => { - if (err) { return done(err); } - if (client.id !== code.clientId) { return done(null, false); } - if (redirectURI !== code.redirectURI) { return done(null, false); } + findOne(code, (err, code) => { + if (err) { + done(err); + } else if (client.id !== code.clientId) { + done(null, false); + } else if (redirectURI !== code.redirectURI) { + done(null, false); + } // var token = utils.uid(256); // var at = new AccessToken(token, code.userId, code.clientId, code.scope); @@ -43,7 +44,7 @@ server.exchange(oauth2orize.exchange.code((client, code, redirectURI, done) => { // Implement Authorization Endpoint class Clients { static findOne(id: string, callback: (err: Error, client?: Clients) => void): void { - callback(new Error(), {} as Clients); + callback(new Error(), {} as Clients); // tslint:disable-line no-object-literal-type-assertion } redirectURI: string; } @@ -52,33 +53,41 @@ class Clients { // login.ensureLoggedIn(), server.authorize((clientID, redirectURI, done) => { Clients.findOne(clientID, (err, client) => { - if (err) { return done(err); } - if (!client) { return done(null, false); } - if (client.redirectURI != redirectURI) { return done(null, false); } - return done(null, client, client.redirectURI); + if (err) { + done(err); + } else if (!client) { + done(null, false); + } else if (client.redirectURI !== redirectURI) { + done(null, false); + } else { + done(null, client, client.redirectURI); + } }); - }), + }); (req: http.IncomingMessage, res: http.ServerResponse) => { // res.render('dialog', { transactionID: req.oauth2.transactionID, // user: req.user, client: req.oauth2.client }); - } + }; // ); // Session Serialization server.serializeClient((client, done) => { - return done(null, client.id); + done(null, client.id); }); server.deserializeClient((id, done) => { Clients.findOne(id, (err, client) => { - if (err) { return done(err); } - return done(null, client); + if (err) { + done(err); + } else { + done(null, client); + } }); }); // Implement Token Endpoint // app.post('/token', // passport.authenticate(['basic', 'oauth2-client-password'], { session: false }), - server.token(), - server.errorHandler() + server.token(); + server.errorHandler(); // ); diff --git a/types/oauth2orize/tslint.json b/types/oauth2orize/tslint.json index a41bf5d19a..f12cd9111f 100644 --- a/types/oauth2orize/tslint.json +++ b/types/oauth2orize/tslint.json @@ -1,79 +1,8 @@ { "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, + // TODOs "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/odata/index.d.ts b/types/odata/index.d.ts index 3f436667f9..349d48763b 100644 --- a/types/odata/index.d.ts +++ b/types/odata/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for odata v0.3.3 +// Type definitions for odata v0.3.4 // Project: https://github.com/janhommes/odata -// Definitions by: Jan Hommes +// Definitions by: Jan Hommes , Jean-Christophe Chalte // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare module 'odata' { import Q = require("q"); @@ -19,6 +20,9 @@ declare module 'odata' { username ?: string password ?: string isAsync ?: boolean + isCors ?: boolean + isHashRoute ?: boolean + appending ?: string } interface OHandler { diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index efb79ed942..3d62c4262c 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -14503,6 +14503,13 @@ declare module olx { maxLines?: number; strokeStyle?: ol.style.Stroke; targetSize?: number; + showLabels?: boolean; + lonLabelFormatter?: ((lon: number) => string); + latLabelFormatter?: ((lat: number) => string); + lonLabelPosition?: number; + latLabelPosition?: number; + lonLabelStyle?: ol.style.Text; + latLabelStyle?: ol.style.Text; } diff --git a/types/optics-agent/index.d.ts b/types/optics-agent/index.d.ts index 496437994f..2c8ae46283 100644 --- a/types/optics-agent/index.d.ts +++ b/types/optics-agent/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apollostack/optics-agent-js#readme // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { GraphQLSchema } from "graphql"; import { Request, Response } from "express"; diff --git a/types/oracledb/index.d.ts b/types/oracledb/index.d.ts index 17ade85591..39907702dc 100644 --- a/types/oracledb/index.d.ts +++ b/types/oracledb/index.d.ts @@ -481,7 +481,6 @@ declare namespace oracledb { terminate(): IPromise; } - /* tslint:disable no-unused-variable */ const DEFAULT: number; /** Metadata return type */ const DB_TYPE_VARCHAR: number; @@ -539,7 +538,6 @@ declare namespace oracledb { */ function newLob(iLob: ILob): Lob; - /* tslint:disable no-var-keyword */ /** Default transaction behaviour of auto commit for each statement. */ var autoCommit: boolean; /** diff --git a/types/orchestrator/index.d.ts b/types/orchestrator/index.d.ts index fcb1a16120..780c3815c5 100644 --- a/types/orchestrator/index.d.ts +++ b/types/orchestrator/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/orchestrator/orchestrator // Definitions by: Qubo , TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/orchestrator/orchestrator-tests.ts b/types/orchestrator/orchestrator-tests.ts index 13e9bb19e0..964369098b 100644 --- a/types/orchestrator/orchestrator-tests.ts +++ b/types/orchestrator/orchestrator-tests.ts @@ -4,7 +4,7 @@ import stream = require("stream"); import Q = require('q'); import Orchestrator = require('orchestrator'); -var orchestrator = new Orchestrator(); +const orchestrator = new Orchestrator(); // API: @@ -21,13 +21,13 @@ orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() { // Do stuff }); orchestrator.add('thing2', function(callback){ - var err: any = null; + const err: any = null; // do stuff callback(err); }); orchestrator.add('thing3', function(){ - var deferred = Q.defer(); + const deferred = Q.defer(); // do async stuff setTimeout(function() { @@ -38,7 +38,7 @@ orchestrator.add('thing3', function(){ }); orchestrator.add('thing4', function(){ - var stm = new stream.Stream(); + const stm = new stream.Stream(); // do stream stuff return stm; }); @@ -61,7 +61,7 @@ orchestrator.task('task3', ['task1', 'task2'], function() { // orchestrator.hasTask(name); // -var hasThing1: boolean = orchestrator.hasTask('thing1'); +const hasThing1: boolean = orchestrator.hasTask('thing1'); // // orchestrator.start(tasks...[, cb]); @@ -70,7 +70,7 @@ var hasThing1: boolean = orchestrator.hasTask('thing1'); orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function(err: any) { // all done }).start(['thing1', 'thing2'], ['thing3', 'thing4'], "thing5", function(err) { - var res: any = err; + const res: any = err; }); // @@ -90,14 +90,14 @@ orchestrator.reset(); // orchestrator.on('task_start', function(e) { - var message: string = e.message; - var task: string = e.task; - var err: any = e.err; + const message: string = e.message; + const task: string = e.task; + const err: any = e.err; }); orchestrator.on('task_stop', function(e) { - var message: string = e.message; - var task: string = e.task; - var duration: number = e.duration; + const message: string = e.message; + const task: string = e.task; + const duration: number = e.duration; }); // @@ -105,8 +105,8 @@ orchestrator.on('task_stop', function(e) { // orchestrator.onAll(function(e) { - var message: string = e.message; - var task: string = e.task; - var err: any = e.err; - var src: string = e.src; + const message: string = e.message; + const task: string = e.task; + const err: any = e.err; + const src: string = e.src; }); diff --git a/types/orchestrator/tsconfig.json b/types/orchestrator/tsconfig.json index 734b3aae82..3cfb6b0cdb 100644 --- a/types/orchestrator/tsconfig.json +++ b/types/orchestrator/tsconfig.json @@ -5,20 +5,15 @@ "es6", "dom" ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 5a0dfd9056..19f615efd0 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/orientechnologies/orientjs // Definitions by: [Saeed Tabrizi] // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + // Last Update : 20-7-2017 // Compatible with Orientdb >= 2.2.15 and orientjs >= 2.2.x features . // Developed with love in www.nowcando.com diff --git a/types/p-any/index.d.ts b/types/p-any/index.d.ts index 8b4165b54c..8b4df3504c 100644 --- a/types/p-any/index.d.ts +++ b/types/p-any/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sindresorhus/p-any#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import AggregateErrorModule = require('aggregate-error'); diff --git a/types/p-lazy/p-lazy-tests.ts b/types/p-lazy/p-lazy-tests.ts index d240ae826e..16ab9e466b 100644 --- a/types/p-lazy/p-lazy-tests.ts +++ b/types/p-lazy/p-lazy-tests.ts @@ -1,7 +1,7 @@ import PLazy = require('p-lazy'); const lazyPromise = new PLazy((resolve, reject) => { - if (typeof resolve === 'object') { + if (!true) { resolve('foo'); } else { reject(new Error()); diff --git a/types/p-props/index.d.ts b/types/p-props/index.d.ts index 38ee03b990..3fa293ef69 100644 --- a/types/p-props/index.d.ts +++ b/types/p-props/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sindresorhus/p-props#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 export = pProps; diff --git a/types/p-retry/index.d.ts b/types/p-retry/index.d.ts index 30a3b23542..784f637549 100644 --- a/types/p-retry/index.d.ts +++ b/types/p-retry/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sindresorhus/p-retry#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { OperationOptions } from 'retry'; diff --git a/types/p-series/index.d.ts b/types/p-series/index.d.ts index 4c185fa807..ecc7b19cd8 100644 --- a/types/p-series/index.d.ts +++ b/types/p-series/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sindresorhus/p-series#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export = pSeries; diff --git a/types/p-some/index.d.ts b/types/p-some/index.d.ts index 6855018c7e..e22fd8d7ea 100644 --- a/types/p-some/index.d.ts +++ b/types/p-some/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sindresorhus/p-some#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import AggregateErrorModule = require('aggregate-error'); diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 82194e65a2..3ad8e6c15d 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -13,11 +13,11 @@ declare namespace Parse { - var applicationId: string; - var javaScriptKey: string | undefined; - var masterKey: string | undefined; - var serverURL: string; - var VERSION: string; + let applicationId: string; + let javaScriptKey: string | undefined; + let masterKey: string | undefined; + let serverURL: string; + let VERSION: string; interface SuccessOption { success?: Function; @@ -97,11 +97,17 @@ declare namespace Parse { reject(error: any): void; resolve(result: any): void; then(resolvedCallback: (...values: T[]) => IPromise, - rejectedCallback?: (reason: any) => IPromise): IPromise; + rejectedCallback?: (reason: any) => IPromise): IPromise; then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => IPromise): IPromise; + rejectedCallback?: (reason: any) => IPromise): IPromise; then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => U): IPromise; + rejectedCallback?: (reason: any) => U): IPromise; + } + + interface Pointer { + __type: string; + className: string; + objectId: string; } interface IBaseObject { @@ -357,6 +363,7 @@ declare namespace Parse { has(attr: string): boolean; hasChanged(attr: string): boolean; increment(attr: string, amount?: number): any; + isNew(): boolean; isValid(): boolean; op(attr: string): any; previous(attr: string): any; @@ -367,6 +374,7 @@ declare namespace Parse { save(key: string, value: any, options?: Object.SaveOptions): Promise; set(key: string, value: any, options?: Object.SetOptions): boolean; setACL(acl: ACL, options?: SuccessFailureOptions): boolean; + toPointer(): Pointer; unset(attr: string, options?: any): any; validate(attrs: any, options?: SuccessFailureOptions): boolean; } @@ -925,7 +933,7 @@ declare namespace Parse { * * import Buffer = require("buffer").Buffer; */ - var HTTPOptions: new () => HTTPOptions; + let HTTPOptions: new () => HTTPOptions; interface HTTPOptions { /** * The body of the request. diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 76440e46d3..1a2d5dcdee 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -2,13 +2,13 @@ function test_events() { - var object = new Parse.Events(); + const object = new Parse.Events(); object.on("alert", (eventName: string) => alert("Triggered " + eventName)); object.trigger("alert", "an event"); - var onChange = () => console.log('whatever'); - var context: any; + const onChange = () => console.log('whatever'); + let context: any; object.off("change", onChange); object.off("change"); @@ -29,29 +29,37 @@ class Game extends Parse.Object { constructor(options?: any) { - super("GameScore", options); + super("Game", options); } } function test_object() { - var game = new Game(); + const game = new Game(); + + if (!game.isNew()) { + console.error("Game should be new"); + } + + if (game.toPointer().className !== "Game") { + console.log("Class name should be 'Game") + } game.fetch({ success(g: Game) { } }); // Create a new instance of that class. - var gameScore = new GameScore(); + const gameScore = new GameScore(); gameScore.set("score", 1337); gameScore.set("playerName", "Sean Plott"); gameScore.set("cheatMode", false); - var score = gameScore.get("score"); - var playerName = gameScore.get("playerName"); - var cheatMode = gameScore.get("cheatMode"); + const score = gameScore.get("score"); + const playerName = gameScore.get("playerName"); + const cheatMode = gameScore.get("cheatMode"); gameScore.increment("score"); gameScore.addUnique("skills", "flying"); @@ -59,14 +67,14 @@ function test_object() { game.set("gameScore", gameScore); - var gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); + const gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); } function test_query() { - var gameScore = new GameScore(); + const gameScore = new GameScore(); - var query = new Parse.Query(GameScore); + const query = new Parse.Query(GameScore); query.equalTo("playerName", "Dan Stemkoski"); query.notEqualTo("playerName", "Michael Yabuti"); query.greaterThan("playerAge", 18); @@ -120,7 +128,7 @@ function test_query() { query.include("score"); query.include(["score.team"]); - var testQuery = Parse.Query.or(query, query); + const testQuery = Parse.Query.or(query, query); } class TestCollection extends Parse.Collection { @@ -141,9 +149,9 @@ function return_a_query(): Parse.Query { function test_collections() { - var collection = new TestCollection(); + let collection = new TestCollection(); - var query = new Parse.Query(Game); + const query = new Parse.Query(Game); query.equalTo("temperature", "hot"); query.greaterThan("degreesF", 100); @@ -167,10 +175,10 @@ function test_collections() { } ); - var model = collection.at(0); + const model = collection.at(0); // Or you can get it by Parse objectId. - var modelAgain = collection.get(model.id); + const modelAgain = collection.get(model.id); // Remove "Duke" from the collection. collection.remove(model); @@ -184,15 +192,15 @@ function test_collections() { function test_file() { - var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; - var file = new Parse.File("myfile.txt", { base64: base64 }); + const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; + let file = new Parse.File("myfile.txt", { base64: base64 }); - var bytes = [0xBE, 0xEF, 0xCA, 0xFE]; - var file = new Parse.File("myfile.txt", bytes); + const bytes = [0xBE, 0xEF, 0xCA, 0xFE]; + file = new Parse.File("myfile.txt", bytes); - var file = new Parse.File("myfile.zzz", {}, "image/png"); + file = new Parse.File("myfile.zzz", {}, "image/png"); - var src = file.url(); + const src = file.url(); file.save().then( () => { @@ -211,7 +219,7 @@ function test_file() { function test_analytics() { - var dimensions = { + const dimensions = { // Define ranges to bucket data points into meaningful segments priceRange: '1000-1500', // Did the user filter the query? @@ -222,7 +230,7 @@ function test_analytics() { // Send the dimensions to Parse along with the 'search' event Parse.Analytics.track('search', dimensions); - var codeString = '404'; + const codeString = '404'; Parse.Analytics.track('error', { code: codeString }) } @@ -232,7 +240,7 @@ function test_relation() { function test_user_acl_roles() { - var user = new Parse.User(); + const user = new Parse.User(); user.set("username", "my name"); user.set("password", "my pass"); user.set("email", "email@example.com"); @@ -240,7 +248,7 @@ function test_user_acl_roles() { // other fields can be set just like with Parse.Object user.set("phone", "415-392-0202"); - var currentUser = Parse.User.current(); + const currentUser = Parse.User.current(); if (currentUser) { // do stuff with the user } else { @@ -253,17 +261,17 @@ function test_user_acl_roles() { // The token could not be validated. }); - var game = new Game(); + const game = new Game(); game.set("score", new GameScore()); game.setACL(new Parse.ACL(Parse.User.current())); game.save().then((game: Game) => { }); game.save(null, { useMasterKey: true }); - var groupACL = new Parse.ACL(); + const groupACL = new Parse.ACL(); - var userList: Parse.User[] = [Parse.User.current()!]; + const userList: Parse.User[] = [Parse.User.current()!]; // userList is an array with the users we are sending this message to. - for (var i = 0; i < userList.length; i++) { + for (let i = 0; i < userList.length; i++) { groupACL.setReadAccess(userList[i], true); groupACL.setWriteAccess(userList[i], true); } @@ -279,7 +287,7 @@ function test_user_acl_roles() { }); // By specifying no write privileges for the ACL, we can ensure the role cannot be altered. - var role = new Parse.Role("Administrator", groupACL); + const role = new Parse.Role("Administrator", groupACL); role.getUsers().add(userList[0]); role.getRoles().add(role); role.save(); @@ -311,7 +319,7 @@ function test_facebook_util() { } }); - var user = Parse.User.current()!; + const user = Parse.User.current()!; if (!Parse.FacebookUtils.isLinked(user)) { Parse.FacebookUtils.link(user, null, { @@ -350,7 +358,7 @@ function test_cloud_functions() { }); Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest, - response: Parse.Cloud.BeforeDeleteResponse) => { + response: Parse.Cloud.BeforeDeleteResponse) => { // result }); @@ -366,27 +374,27 @@ class PlaceObject extends Parse.Object { } function test_geo_points() { - var point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 }); + const point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 }); - var userObject = Parse.User.current()!; + const userObject = Parse.User.current()!; // User's location - var userGeoPoint = userObject.get("location"); + const userGeoPoint = userObject.get("location"); // Create a query for places - var query = new Parse.Query(Parse.User); + const query = new Parse.Query(Parse.User); // Interested in locations near user. query.near("location", userGeoPoint); // Limit what could be a lot of points. query.limit(10); - var southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); - var northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962); + const southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); + const northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962); - var query2 = new Parse.Query(PlaceObject); + const query2 = new Parse.Query(PlaceObject); query2.withinGeoBox("location", southwestOfSF, northeastOfSF); - var query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => { }); + const query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => { }); } function test_push() { @@ -405,7 +413,7 @@ function test_push() { } }); - var query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); query.equalTo('injuryReports', true); Parse.Push.send({ @@ -425,8 +433,8 @@ function test_push() { function test_view() { - var model = Parse.User.current(); - var view = new Parse.View(); + const model = Parse.User.current(); + const view = new Parse.View(); } function test_promise() { diff --git a/types/passport-anonymous/index.d.ts b/types/passport-anonymous/index.d.ts index c997c92ff0..6e45ed3a23 100644 --- a/types/passport-anonymous/index.d.ts +++ b/types/passport-anonymous/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jaredhanson/passport-anonymous // Definitions by: Pavel Puchkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as passport from "passport"; diff --git a/types/passport-facebook-token/index.d.ts b/types/passport-facebook-token/index.d.ts index 3077beca0e..9013910ee1 100644 --- a/types/passport-facebook-token/index.d.ts +++ b/types/passport-facebook-token/index.d.ts @@ -1,38 +1,58 @@ -// Type definitions for passport-facebook-token 0.4.0 +// Type definitions for passport-facebook-token 0.4 // Project: https://github.com/drudge/passport-facebook-token -// Definitions by: Ray Martone +// Definitions by: Ray Martone , Michael Randolph // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - - - -import passport = require('passport'); -import express = require('express'); - -interface Profile extends passport.Profile { - gender: string; - profileUrl: string; -} - -interface StrategyOptions { - clientID: string; - clientSecret: string; - authorizationURL?: string; - tokenURL?: string; - scopeSeparator?: string; - passReqToCallback?: Function; - enableProof?: boolean; - profileFields?: any[]; -} +import * as passport from 'passport'; +import * as express from 'express'; declare class Strategy implements passport.Strategy { - constructor(options: StrategyOptions, - verify: (accessToken: string, - refreshToken: string, - profile: Profile, - done: (err: any, user?: any) => void) => void); + constructor(options: Strategy.StrategyOptionsWithRequest, verify: Strategy.VerifyFunctionWithRequest) + constructor(options: Strategy.StrategyOptions, verify: Strategy.VerifyFunction); + name: string; authenticate: (req: express.Request, options?: any) => void; } + +declare namespace Strategy { + interface ValueObject { + value: string; + } + + interface Profile extends passport.Profile { + provider: string; + id: string; + displayName: string; + name: { + familyName: string; + givenName: string; + middleName: string; + }; + gender: string; + emails: ValueObject[]; + photos: ValueObject[]; + _raw: string; + _json: any; + } + + interface StrategyOptions { + clientID: string; + clientSecret: string; + authorizationURL?: string; + tokenURL?: string; + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; + } + + interface StrategyOptionsWithRequest extends StrategyOptions { + passReqToCallback: true; + } + + type VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; + + type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +} + +export = Strategy; diff --git a/types/passport-facebook-token/passport-facebook-token-tests.ts b/types/passport-facebook-token/passport-facebook-token-tests.ts index e44100ca7d..cb2f078e88 100644 --- a/types/passport-facebook-token/passport-facebook-token-tests.ts +++ b/types/passport-facebook-token/passport-facebook-token-tests.ts @@ -1,28 +1,43 @@ +import * as express from 'express'; +import * as passport from 'passport'; +import * as FacebookStrategy from 'passport-facebook-token'; +// tslint:disable-next-line:no-duplicate-imports +import { StrategyOptions, StrategyOptionsWithRequest, VerifyFunction, VerifyFunctionWithRequest, Profile } from 'passport-facebook-token'; -import passport = require('passport'); -import facebook = require('passport-facebook-token'); - -var User = { +const User = { findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void { - callback(null, {username: 'ray'}); + callback(null, { username: 'ray' }); } -} - -var options: facebook.StrategyOptions = { - clientID: process.env.PASSPORT_FACEBOOK_CLIENT_ID, - clientSecret: process.env.PASSPORT_FACEBOOK_CLIENT_SECRET }; -function verify(accessToken: string, - refreshToken: string, - profile: facebook.Profile, - done: (err: any, user?: any) => void) { - User.findOrCreate(profile.id, profile.provider, function (err, user) { +const options: StrategyOptions = { + clientID: 'TEST_CLIENT_ID', + clientSecret: 'TEST_CLIENT_SECRET' +}; + +const optionsWithRequest: StrategyOptionsWithRequest = { + clientID: 'TEST_CLIENT_ID', + clientSecret: 'TEST_CLIENT_SECRET', + passReqToCallback: true +}; + +const verify: VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { + User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { - return done(err); + done(err); } done(null, user); }); -} +}; -passport.use(new facebook.Strategy(options, verify)); +const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { + User.findOrCreate(profile.id, profile.provider, (err, user) => { + if (err) { + done(err); + } + done(null, user); + }); +}; + +passport.use(new FacebookStrategy(options, verify)); +passport.use(new FacebookStrategy(optionsWithRequest, verifyWithRequest)); diff --git a/types/passport-facebook-token/tsconfig.json b/types/passport-facebook-token/tsconfig.json index a5f4d17112..e1d020177a 100644 --- a/types/passport-facebook-token/tsconfig.json +++ b/types/passport-facebook-token/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/passport-facebook-token/tslint.json b/types/passport-facebook-token/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/passport-facebook-token/tslint.json +++ b/types/passport-facebook-token/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/passport-jwt/index.d.ts b/types/passport-jwt/index.d.ts index f1c87c40ed..c300276fe2 100644 --- a/types/passport-jwt/index.d.ts +++ b/types/passport-jwt/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for passport-jwt 2.0 +// Type definitions for passport-jwt 3.0 // Project: https://github.com/themikenicholson/passport-jwt // Definitions by: TANAKA Koichi // Alex Young // David Ng +// Carlos Eduardo Scheffer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -15,7 +16,8 @@ export declare class Strategy extends PassportStrategy { } export interface StrategyOptions { - secretOrKey: string | Buffer; + secretOrKey?: string | Buffer; + secretOrKeyProvider?: any; jwtFromRequest: JwtFromRequestFunction; issuer?: string; audience?: string; diff --git a/types/passport-steam/index.d.ts b/types/passport-steam/index.d.ts index 5658623ab3..9e5470a070 100644 --- a/types/passport-steam/index.d.ts +++ b/types/passport-steam/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/liamcurry/passport-steam // Definitions by: Gonthier Renaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export = passport_steam; diff --git a/types/passport/index.d.ts b/types/passport/index.d.ts index f25f261360..574dd8b3de 100644 --- a/types/passport/index.d.ts +++ b/types/passport/index.d.ts @@ -1,103 +1,103 @@ -// Type definitions for Passport 0.3 +// Type definitions for Passport 0.4 // Project: http://passportjs.org -// Definitions by: Horiuchi_H , Eric Naeseth +// Definitions by: Horiuchi_H , Eric Naeseth , Igor Belagorudsky // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -declare namespace Express { - export interface Request { - authInfo?: any; - user?: any; +declare global { + namespace Express { + interface Request { + authInfo?: any; + user?: any; - // These declarations are merged into express's Request type - login(user: any, done: (err: any) => void): void; - login(user: any, options: any, done: (err: any) => void): void; - logIn(user: any, done: (err: any) => void): void; - logIn(user: any, options: any, done: (err: any) => void): void; + // These declarations are merged into express's Request type + login(user: any, done: (err: any) => void): void; + login(user: any, options: any, done: (err: any) => void): void; + logIn(user: any, done: (err: any) => void): void; + logIn(user: any, options: any, done: (err: any) => void): void; - logout(): void; - logOut(): void; + logout(): void; + logOut(): void; - isAuthenticated(): boolean; - isUnauthenticated(): boolean; + isAuthenticated(): boolean; + isUnauthenticated(): boolean; + } } } -declare module 'passport' { - import express = require('express'); +import express = require('express'); - namespace passport { - interface AuthenticateOptions { - authInfo?: boolean; - assignProperty?: string; - failureFlash?: string|boolean|any; - failureMessage?: boolean|string; - failureRedirect?: string; - failWithError?: boolean; - session?: boolean; - scope?: string|string[]; - successFlash?: string|boolean|any; - successMessage?: boolean|string; - successRedirect?: string; - successReturnToOrRedirect?: string; - pauseStream?: boolean; - userProperty?: string; - } - - interface Passport { - use(strategy: passport.Strategy): this; - use(name: string, strategy: passport.Strategy): this; - unuse(name: string): this; - framework(fw: passport.Framework): this; - initialize(options?: { userProperty: string; }): express.Handler; - session(options?: { pauseStream: boolean; }): express.Handler; - - authenticate(strategy: string|string[], callback?: Function): express.Handler; - authenticate(strategy: string|string[], options: AuthenticateOptions, callback?: Function): express.Handler; - authorize(strategy: string|string[], callback?: Function): express.Handler; - authorize(strategy: string|string[], options: any, callback?: Function): express.Handler; - serializeUser(fn: (user: TUser, done: (err: any, id?: TID) => void) => void): void; - deserializeUser(fn: (id: TID, done: (err: any, user?: TUser) => void) => void): void; - transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; - } - - interface PassportStatic extends Passport { - Passport: {new(): Passport}; - Authenticator: {new(): Passport}; - } - - interface Strategy { - name?: string; - authenticate(req: express.Request, options?: any): void; - } - - interface Profile { - provider: string; - id: string; - displayName: string; - username?: string; - name?: { - familyName: string; - givenName: string; - middleName?: string; - }; - emails?: Array<{ - value: string; - type?: string; - }>; - photos?: Array<{ - value: string; - }>; - } - - interface Framework { - initialize(passport: Passport, options?: any): Function; - authenticate(passport: Passport, name: string, options?: any, callback?: Function): Function; - authorize?(passport: Passport, name: string, options?: any, callback?: Function): Function; - } +declare namespace passport { + interface AuthenticateOptions { + authInfo?: boolean; + assignProperty?: string; + failureFlash?: string|boolean; + failureMessage?: boolean|string; + failureRedirect?: string; + failWithError?: boolean; + session?: boolean; + scope?: string|string[]; + successFlash?: string|boolean; + successMessage?: boolean|string; + successRedirect?: string; + successReturnToOrRedirect?: string; + pauseStream?: boolean; + userProperty?: string; + passReqToCallback?: boolean; } - const passport: passport.PassportStatic; - export = passport; + interface Passport { + use(strategy: Strategy): this; + use(name: string, strategy: Strategy): this; + unuse(name: string): this; + framework(fw: Framework): this; + initialize(options?: { userProperty: string; }): express.Handler; + session(options?: { pauseStream: boolean; }): express.Handler; + + authenticate(strategy: string|string[], callback?: (...args: any[]) => any): express.Handler; + authenticate(strategy: string|string[], options: AuthenticateOptions, callback?: (...args: any[]) => any): express.Handler; + authorize(strategy: string|string[], callback?: (...args: any[]) => any): express.Handler; + authorize(strategy: string|string[], options: any, callback?: (...args: any[]) => any): express.Handler; + serializeUser(fn: (user: TUser, done: (err: any, id?: TID) => void) => void): void; + deserializeUser(fn: (id: TID, done: (err: any, user?: TUser) => void) => void): void; + transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; + } + + interface PassportStatic extends Passport { + Passport: {new(): Passport}; + Authenticator: {new(): Passport}; + } + + interface Strategy { + name?: string; + authenticate(req: express.Request, options?: any): void; + } + + interface Profile { + provider: string; + id: string; + displayName: string; + username?: string; + name?: { + familyName: string; + givenName: string; + middleName?: string; + }; + emails?: Array<{ + value: string; + type?: string; + }>; + photos?: Array<{ + value: string; + }>; + } + + interface Framework { + initialize(passport: Passport, options?: any): (...args: any[]) => any; + authenticate(passport: Passport, name: string, options?: any, callback?: (...args: any[]) => any): (...args: any[]) => any; + authorize?(passport: Passport, name: string, options?: any, callback?: (...args: any[]) => any): (...args: any[]) => any; + } } +declare const passport: passport.PassportStatic; +export = passport; diff --git a/types/passport/passport-tests.ts b/types/passport/passport-tests.ts index c461d45562..5732a14b16 100644 --- a/types/passport/passport-tests.ts +++ b/types/passport/passport-tests.ts @@ -3,24 +3,24 @@ import * as express from 'express'; import 'express-session'; class TestStrategy implements passport.Strategy { - public name: string = 'test'; + name = 'test'; constructor() { } authenticate(req: express.Request) { } } -const newFramework:passport.Framework = { - initialize: function () { - return function () { }; +const newFramework: passport.Framework = { + initialize() { + return () => { }; }, - authenticate: function (passport, name, options) { - return function () { - return 'authenticate(): ' + name + ' ' + options; + authenticate(passport, name, options) { + return () => { + return `authenticate(): ${name} ${options}`; }; }, - authorize: function (passport, name, options) { - return function () { - return 'authorize(): ' + name + ' ' + options; - } + authorize(passport, name, options) { + return () => { + return `authorize(): ${name} ${options}`; + }; } }; passport.use(new TestStrategy()); @@ -49,7 +49,7 @@ passport.deserializeUser((id, done) => { fetchUser(id) .then((user) => done(null, user)) - .catch((err) => done(err)); + .catch(done); }); passport.use(new TestStrategy()) @@ -57,8 +57,7 @@ passport.use(new TestStrategy()) .use(new TestStrategy()) .framework(newFramework); - -var app = express(); +const app = express(); app.configure(() => { app.use(passport.initialize()); app.use(passport.session()); @@ -66,40 +65,39 @@ app.configure(() => { app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), - function (req, res) { + (req, res) => { res.redirect('/'); }); -app.post('/login', function (req, res, next) { - passport.authenticate('local', function (err: any, user: { username: string; }, info: { message: string; }) { - if (err) { return next(err) } +app.post('/login', (req, res, next) => { + passport.authenticate('local', (err: any, user: { username: string; }, info: { message: string; }) => { + if (err) { return next(err); } if (!user) { if (req.session) { req.session['error'] = info.message; } - return res.redirect('/login') + return res.redirect('/login'); } - req.logIn(user, function (err) { + req.logIn(user, (err) => { if (err) { return next(err); } return res.redirect('/users/' + user.username); }); })(req, res, next); }); -app.get('/logout', function (req, res) { +app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.post('/auth/token', passport.authenticate(['basic', 'oauth2-client-password'], { session: false })); - function authSetting(): void { - var authOption = { + const authOption = { successRedirect: '/', failureRedirect: '/login', }; - var successCallback = (req: express.Request, res: express.Response) => { + const successCallback = (req: express.Request, res: express.Response) => { res.redirect('/'); }; @@ -120,7 +118,6 @@ function authSetting(): void { })); app.get('/auth/google/callback', passport.authenticate('google', authOption), successCallback); - } function ensureAuthenticated(req: express.Request, res: express.Response, next: (err?: any) => void) { @@ -130,8 +127,8 @@ function ensureAuthenticated(req: express.Request, res: express.Response, next: } } -const passportInstance: passport.Passport = new passport.Passport() -passportInstance.use(new TestStrategy()) +const passportInstance: passport.Passport = new passport.Passport(); +passportInstance.use(new TestStrategy()); -const authenticator: passport.Passport = new passport.Authenticator() -authenticator.use(new TestStrategy()) \ No newline at end of file +const authenticator: passport.Passport = new passport.Authenticator(); +authenticator.use(new TestStrategy()); diff --git a/types/passport/tslint.json b/types/passport/tslint.json index a41bf5d19a..e1828da3e2 100644 --- a/types/passport/tslint.json +++ b/types/passport/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-void-expression": false } } diff --git a/types/pathwatcher/README.md b/types/pathwatcher/README.md deleted file mode 100644 index be0a445f29..0000000000 --- a/types/pathwatcher/README.md +++ /dev/null @@ -1,44 +0,0 @@ -## Path Watcher Node Type Definitions - -TypeScript type definitions for [Path Watcher Node], which is published as "[pathwatcher](https://www.npmjs.com/package/pathwatcher)" on NPM. - -### Usage Notes - -#### Exports - -The two classes exported from this module are: [File](https://github.com/atom/node-pathwatcher/blob/master/src/file.coffee) and [Directory](https://github.com/atom/node-pathwatcher/blob/master/src/directory.coffee). - -```ts -import { File, Directory } from "text-buffer"; -``` - -Additionally, the following functions are exported as well: -```ts -watch(): PathWatcher.PathWatcher; -closeAllWatchers(): void; -getWatchedPaths(): string[]; -``` - -#### The PathWatcher Namespace - -All types used by Path Watcher can be referenced from the PathWatcher namespace. - -```ts -function example(file: PathWatcher.File) {} -``` - -### 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 Path Watcher. As an example, if we wanted to reveal the private ```setPath``` method within the File class, then we would create a file with the following contents: - -```ts -// <>.d.ts - -declare namespace PathWatcher { - interface File { - setPath(path: string): 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 File class without TypeScript reporting errors. diff --git a/types/pathwatcher/index.d.ts b/types/pathwatcher/index.d.ts index 6fd17d6692..0ff5427913 100644 --- a/types/pathwatcher/index.d.ts +++ b/types/pathwatcher/index.d.ts @@ -5,236 +5,237 @@ // TypeScript Version: 2.2 /// -/// +import { Disposable } from "event-kit"; import { ReadStream, WriteStream } from "fs"; -declare global { - namespace PathWatcher { - /** The event objects that are passed into the callbacks which the user provides to - * specific API calls. - */ - namespace Events { - interface PathWatchErrorThrown { - /** 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; - } - - interface WatchedFilePathChangedEvent { - event: string; - newFilePath: string; - } - } - - /** Represents an individual file that can be watched, read from, and written to. */ - interface File { - // Properties - realPath: string|null; - path: string; - symlink: boolean; - - // Construction - /** 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): EventKit.Disposable; - - /** Invoke the given callback when the file's path changes. */ - onDidRename(callback: () => void): EventKit.Disposable; - - /** Invoke the given callback when the file is deleted. */ - onDidDelete(callback: () => void): EventKit.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: (errorObject: Events.PathWatchErrorThrown) => - void): EventKit.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; - } - - /** The static side to the File class. */ - interface FileStatic { - /** Configures a new File instance, no files are accessed. */ - new (filePath: string, symlink?: boolean): File; - } - - /** Represents a directory on disk that can be watched for changes. */ - interface Directory { - // Properties - realPath: string|null; - path: string; - symlink: boolean; - - // Construction - /** 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): EventKit.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; - } - - /** The static side to the Directory class. */ - interface DirectoryStatic { - /** Configures a new Directory instance, no files are accessed. */ - new (directoryPath: string, symlink?: boolean): Directory; - } - - interface PathWatcher { - onDidChange(callback: (change: Events.WatchedFilePathChangedEvent) => void): - EventKit.Disposable; - - close(): void; - } - } -} - -export let File: PathWatcher.FileStatic; -export let Directory: PathWatcher.DirectoryStatic; - -export function watch(): PathWatcher.PathWatcher; +export function watch(): PathWatcher; export function closeAllWatchers(): void; export function getWatchedPaths(): string[]; + +/** Represents an individual file that can be watched, read from, and written to. */ +export class File { + // Properties + realPath: string|null; + path: string; + symlink: boolean; + + // 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: (errorObject: 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 a directory on disk that can be watched for changes. */ +export class Directory { + // Properties + realPath: string|null; + path: string; + symlink: boolean; + + // 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; +} + +// Events ===================================================================== +// The event objects that are passed into the callbacks which the user provides +// to specific API calls. + +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 WatchedFilePathChangedEvent { + event: string; + newFilePath: string; +} + +// Structures ================================================================= +// The structures that are passed to the user by Atom following specific API calls. + +export interface PathWatcher { + onDidChange(callback: (change: WatchedFilePathChangedEvent) => void): Disposable; + + close(): void; +} diff --git a/types/pathwatcher/pathwatcher-tests.ts b/types/pathwatcher/pathwatcher-tests.ts index 20f3d797a3..55cba4ac33 100644 --- a/types/pathwatcher/pathwatcher-tests.ts +++ b/types/pathwatcher/pathwatcher-tests.ts @@ -1,11 +1,12 @@ +import { Disposable } from "event-kit"; import { File, Directory } from "pathwatcher"; let bool: boolean; let str: string; -let sub: EventKit.Disposable; +let sub: Disposable; -let file: PathWatcher.File; -let dir: PathWatcher.Directory; +let file: File; +let dir: Directory; // File ======================================================================= // Construction diff --git a/types/pathwatcher/tsconfig.json b/types/pathwatcher/tsconfig.json index c413f34011..41bb35a03c 100644 --- a/types/pathwatcher/tsconfig.json +++ b/types/pathwatcher/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "pathwatcher-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/pathwatcher/tslint.json b/types/pathwatcher/tslint.json index 7238e43729..e0508241c7 100644 --- a/types/pathwatcher/tslint.json +++ b/types/pathwatcher/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/phantomcss/index.d.ts b/types/phantomcss/index.d.ts index 688c706199..230936562b 100644 --- a/types/phantomcss/index.d.ts +++ b/types/phantomcss/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Huddle/PhantomCSS // Definitions by: Amaury Bauzac // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// import { Casper } from 'casperjs'; diff --git a/types/physijs/test/body.ts b/types/physijs/test/body.ts index dfb0224f65..d046880099 100644 --- a/types/physijs/test/body.ts +++ b/types/physijs/test/body.ts @@ -11,30 +11,30 @@ initScene = function() { projector = new THREE.Projector; renderer = new THREE.WebGLRenderer({ antialias: true }); - renderer.setSize( window.innerWidth, window.innerHeight ); + renderer.setSize(window.innerWidth, window.innerHeight); renderer.shadowMapEnabled = true; - // // renderer.shadowMapSoft = true; - document.getElementById( 'viewport' ).appendChild( renderer.domElement ); + // // renderer.shadowMapSoft = true; + document.getElementById('viewport').appendChild(renderer.domElement); render_stats = new Stats(); render_stats.dom.style.position = 'absolute'; render_stats.dom.style.top = '1px'; render_stats.dom.style.zIndex = '100'; - document.getElementById( 'viewport' ).appendChild( render_stats.dom ); + document.getElementById('viewport').appendChild(render_stats.dom); physics_stats = new Stats(); physics_stats.dom.style.position = 'absolute'; physics_stats.dom.style.top = '50px'; physics_stats.dom.style.zIndex = '100'; - document.getElementById( 'viewport' ).appendChild( physics_stats.dom ); + document.getElementById('viewport').appendChild(physics_stats.dom); scene = new Physijs.Scene(); - scene.setGravity(new THREE.Vector3( 0, -30, 0 )); + scene.setGravity(new THREE.Vector3(0, -30, 0)); scene.addEventListener( 'update', function() { applyForce(); - scene.simulate( undefined, 1 ); + scene.simulate(undefined, 1); physics_stats.update(); } ); @@ -45,14 +45,14 @@ initScene = function() { 1, 1000 ); - camera.position.set( 60, 50, 60 ); - camera.lookAt( scene.position ); - scene.add( camera ); + camera.position.set(60, 50, 60); + camera.lookAt(scene.position); + scene.add(camera); // Light - light = new THREE.DirectionalLight( 0xFFFFFF ); - light.position.set( 20, 40, -15 ); - light.target.position.copy( scene.position ); + light = new THREE.DirectionalLight(0xFFFFFF); + light.position.set(20, 40, -15); + light.target.position.copy(scene.position); light.castShadow = true; light.shadowCameraLeft = -60; light.shadowCameraTop = -60; @@ -63,11 +63,11 @@ initScene = function() { light.shadowBias = -.0001 light.shadowMapWidth = light.shadowMapHeight = 2048; //// light.shadowDarkness = .7; - scene.add( light ); + scene.add(light); // Materials ground_material = Physijs.createMaterial( - new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture( 'images/rocks.jpg' ) }), + new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('images/rocks.jpg') }), .8, // high friction .4 // low restitution ); @@ -75,7 +75,7 @@ initScene = function() { // ground_material.map.repeat.set( 3, 3 ); box_material = Physijs.createMaterial( - new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture( 'images/plywood.jpg' ) }), + new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('images/plywood.jpg') }), .4, // low friction .6 // high restitution ); @@ -89,11 +89,11 @@ initScene = function() { 0 // mass ); ground.receiveShadow = true; - scene.add( ground ); + scene.add(ground); - for ( var i = 0; i < 10; i++ ) { + for (var i = 0; i < 10; i++) { box = new Physijs.BoxMesh( - new THREE.BoxGeometry( 4, 4, 4 ), + new THREE.BoxGeometry(4, 4, 4), box_material ); box.position.set( @@ -112,46 +112,46 @@ initScene = function() { Math.random() * 1 + .5 ); box.castShadow = true; - scene.add( box ); - boxes.push( box ); + scene.add(box); + boxes.push(box); } - renderer.domElement.addEventListener( 'mousemove', setMousePosition ); + renderer.domElement.addEventListener('mousemove', setMousePosition); - requestAnimationFrame( render ); + requestAnimationFrame(render); scene.simulate(); }; render = function() { - requestAnimationFrame( render ); - renderer.render( scene, camera ); + requestAnimationFrame(render); + renderer.render(scene, camera); render_stats.update(); }; -setMousePosition = function( evt ) { +setMousePosition = function(evt) { // Find where mouse cursor intersects the ground plane var vector = new THREE.Vector3( - ( evt.clientX / renderer.dom.clientWidth ) * 2 - 1, - -( ( evt.clientY / renderer.dom.clientHeight ) * 2 - 1 ), + (evt.clientX / renderer.dom.clientWidth) * 2 - 1, + -((evt.clientY / renderer.dom.clientHeight) * 2 - 1), .5 ); - projector.unprojectVector( vector, camera ); - vector.sub( camera.position ).normalize(); + projector.unprojectVector(vector, camera); + vector.sub(camera.position).normalize(); var coefficient = (box.position.y - camera.position.y) / vector.y - mouse_position = camera.position.clone().add( vector.multiplyScalar( coefficient ) ); + mouse_position = camera.position.clone().add(vector.multiplyScalar(coefficient)); }; applyForce = function() { if (!mouse_position) return; var strength = 35, distance, effect, offset, box; - for ( var i = 0; i < boxes.length; i++ ) { + for (var i = 0; i < boxes.length; i++) { box = boxes[i]; - distance = mouse_position.distanceTo( box.position ), - effect = mouse_position.clone().sub( box.position ).normalize().multiplyScalar( strength / distance ).negate(), - offset = mouse_position.clone().sub( box.position ); - box.applyImpulse( effect, offset ); + distance = mouse_position.distanceTo(box.position); + effect = mouse_position.clone().sub(box.position).normalize().multiplyScalar(strength / distance).negate(); + offset = mouse_position.clone().sub(box.position); + box.applyImpulse(effect, offset); } }; diff --git a/types/pikaday-time/index.d.ts b/types/pikaday-time/index.d.ts index bc8b76a2ef..33a312801d 100644 --- a/types/pikaday-time/index.d.ts +++ b/types/pikaday-time/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/owenmead/Pikaday // Definitions by: Sayan Pal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as moment from 'moment'; diff --git a/types/pino-multi-stream/index.d.ts b/types/pino-multi-stream/index.d.ts index 4aa8dcfb7d..ad73577fe3 100644 --- a/types/pino-multi-stream/index.d.ts +++ b/types/pino-multi-stream/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pinojs/pino-multi-stream#readme // Definitions by: Jake Ginnivan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { LoggerOptions as PinoLoggerOptions, Logger as PinoLogger, diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 863daf8085..a34dbf2ab8 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -123,6 +123,7 @@ export interface Layout { dragmode: "lasso" | "pan" | "select" | "zoom"; shapes: Array>; legend: Partial; + font: Partial; } export interface Legend { @@ -150,6 +151,7 @@ export interface Axis { type: AxisType; tickformat: string; hoverformat: string; + exponentformat: "none" | "e" | "E" | "power" | "SI" | "B"; rangeslider: Partial; rangeselector: Partial; range: [Datum, Datum]; diff --git a/types/polyline/index.d.ts b/types/polyline/index.d.ts index bead8d9e5e..7a8b7eeb19 100644 --- a/types/polyline/index.d.ts +++ b/types/polyline/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mapbox/polyline // Definitions by: Arseniy Maximov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 6ea1fcbbf9..cb0a813385 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for prettier 1.7 +// Type definitions for prettier 1.8 // Project: https://github.com/prettier/prettier // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import { File } from 'babel-types'; @@ -18,7 +18,8 @@ export type BuiltInParserName = | 'less' | 'scss' | 'json' - | 'graphql'; + | 'graphql' + | 'markdown'; export type CustomParser = (text: string, parsers: Record, options: Options) => AST; @@ -76,6 +77,20 @@ export interface Options { * This is very useful when gradually transitioning large, unformatted codebases to prettier. */ requirePragma?: boolean; + /** + * Prettier can insert a special @format marker at the top of files specifying that + * the file has been formatted with prettier. This works well when used in tandem with + * the --require-pragma option. If there is already a docblock at the top of + * the file then this option will add a newline to it with the @format marker. + */ + insertPragma?: boolean; + /** + * By default, Prettier will wrap markdown text at the specified print width. + * In some cases you may want to rely on editor/viewer soft wrapping instead, + * so this option allows you to opt out. When prose wrapping is disabled, + * each paragraph will be printed on its own line. + */ + proseWrap?: boolean; } export interface CursorOptions extends Options { diff --git a/types/proj4leaflet/index.d.ts b/types/proj4leaflet/index.d.ts index 1d88365237..81a16100e4 100644 --- a/types/proj4leaflet/index.d.ts +++ b/types/proj4leaflet/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kartena/Proj4Leaflet#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as geojson from 'geojson'; import * as L from 'leaflet'; diff --git a/types/promise-pg/index.d.ts b/types/promise-pg/index.d.ts index 0cc7e232ca..d9461d77ae 100644 --- a/types/promise-pg/index.d.ts +++ b/types/promise-pg/index.d.ts @@ -2,6 +2,7 @@ // Project: https://bitbucket.org/lplabs/promise-pg // Definitions by: Chris Charabaruk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/promise-pool/index.d.ts b/types/promise-pool/index.d.ts index 51af449480..947500b0f5 100644 --- a/types/promise-pool/index.d.ts +++ b/types/promise-pool/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/vilic/promise-pool // Definitions by: VILIC VANE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/promise-retry/index.d.ts b/types/promise-retry/index.d.ts new file mode 100644 index 0000000000..e31fe3a657 --- /dev/null +++ b/types/promise-retry/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for promise-retry 1.1 +// Project: https://github.com/IndigoUnited/node-promise-retry +// Definitions by: Jamie Birch +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { WrapOptions } from "retry"; +/** + * A function that is retryable, by having implicitly-bound params for both an error handler and an attempt number. + * + * @param retry The retry callback upon any rejection. Essentially throws the error on in the form of a { retried: err } + * wrapper, and tags it with a 'code' field of value "EPROMISERETRY" so that it is recognised as needing retrying. Call + * this from the catch() block when you want to retry a rejected attempt. + * @param attempt The number of the attempt. + * @returns A Promise for anything (eg. a HTTP response). + */ +type RetryableFn = ((retry: (error: any) => never, attempt: number) => Promise); +/** + * Wrap all functions of the object with retry. The params can be entered in either order, just like in the original library. + * + * @param retryableFn The function to retry. + * @param options The options for how long/often to retry the function for. + * @returns The Promise resolved by the input retryableFn, or rejected (if not retried) from its catch block. + */ +declare function promiseRetry(retryableFn: RetryableFn, options?: WrapOptions): Promise; +declare function promiseRetry(options: WrapOptions, retryableFn: RetryableFn): Promise; +export = promiseRetry; diff --git a/types/promise-retry/promise-retry-tests.ts b/types/promise-retry/promise-retry-tests.ts new file mode 100644 index 0000000000..80abc7046d --- /dev/null +++ b/types/promise-retry/promise-retry-tests.ts @@ -0,0 +1,93 @@ +import promiseRetry = require('promise-retry'); + +// From sleep +declare function sleep(milliseconds: number): Promise; + +// Adapted from Chai +interface Assertion { + equal: Equal; + not: Assertion; + to: Assertion; +} +type Equal = (value: any, message?: string) => Assertion; +type Operator = string; // "==" | "===" | ">" | ">=" | "<" | "<=" | "!=" | "!=="; +interface ExpectStatic { + (target: any, message?: string): Assertion; + fail(actual?: any, expected?: any, message?: string, operator?: Operator): void; +} +declare const expect: ExpectStatic; + +// Adapted from Mocha +interface ContextDefinition { + (desc: string, f: () => void): void; + timeout(ms: number): void; +} +declare const describe: ContextDefinition; +interface Runnable { + timeout(n: number): this; +} +interface TestDefinition { + (desc: string, f: (done?: (error?: Error) => void) => void): Runnable; + timeout(ms: number): void; +} +declare const it: TestDefinition; + +// Adapted from lib.d.ts +interface Console { + assert(test?: boolean, message?: string, ...optionalParams: any[]): void; + error(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; +} +declare let Console: { + prototype: Console; + new(): Console; +}; +declare let console: Console; + +describe("Promise-retry tests", () => { + it('should allow params to be input either way round', () => { + let count = 0; + + promiseRetry( + (retryCb, attemptNumber) => { + count += 1; + + return Promise.resolve() + .then(() => { + console.log("Count in then()", count); + if (count > 1) return Promise.resolve('final'); + else return Promise.reject(new Error('arbitrary excuse to retry')); + }) + .catch((err: any) => { + console.log("Count in catch()", count); + if (count > 1) return Promise.resolve('final'); + else return retryCb(err); + }); + }, + {forever: true, factor: 1, minTimeout: 0, maxTimeout: 30, randomize: false} + ) + .then((value: any) => console.log("Finished with value ", value)) + .catch((err: any) => console.error(err.message || err)); + + promiseRetry( + {forever: true, factor: 1, minTimeout: 0, maxTimeout: 30, randomize: false}, + (retryCb, attemptNumber) => { + count += 1; + + return Promise.resolve() + .then(() => { + console.log("Count in then()", count); + if (count > 1) return Promise.resolve('final'); + else return Promise.reject(new Error('arbitrary excuse to retry')); + }) + .catch((err: any) => { + console.log("Count in catch()", count); + if (count > 1) return Promise.resolve('final'); + else return retryCb(err); + }); + } + ) + .then((value: any) => console.log("Finished with value ", value)) + .catch((err: any) => console.error(err.message || err)); + }); +}); diff --git a/types/promise-retry/tsconfig.json b/types/promise-retry/tsconfig.json new file mode 100644 index 0000000000..cd598fc1f4 --- /dev/null +++ b/types/promise-retry/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", + "promise-retry-tests.ts" + ] +} diff --git a/types/promise-retry/tslint.json b/types/promise-retry/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promise-retry/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/protractor-browser-logs/index.d.ts b/types/protractor-browser-logs/index.d.ts index 276c22fad8..8968e24cb1 100644 --- a/types/protractor-browser-logs/index.d.ts +++ b/types/protractor-browser-logs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/protractor-browser-logs, https://github.com/wix/protractor-browser-logs // Definitions by: Saqib Rokadia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as webdriver from 'selenium-webdriver'; import Entry = webdriver.logging.Entry; diff --git a/types/protractor-http-mock/index.d.ts b/types/protractor-http-mock/index.d.ts index 110883a8d3..7dfdd9057e 100644 --- a/types/protractor-http-mock/index.d.ts +++ b/types/protractor-http-mock/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/atecarlos/protractor-http-mock // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as webdriver from 'selenium-webdriver'; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 12af2a6eeb..151f69d70f 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -191,7 +191,7 @@ export interface ElementHandle extends JSHandle { screenshot(options?: ScreenshotOptions): Promise; tap(): Promise; toString(): string; - type(selector: string, text: string, options?: { delay: number }): Promise; + type(text: string, options?: { delay: number }): Promise; uploadFile(...filePaths: string[]): Promise; } diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index 403c3ac7ac..9d76178a62 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -208,7 +208,7 @@ puppeteer.launch().then(async browser => { } }); console.log(button.toString()); - div.type("input", "Hello World", { delay: 10 }); + input.type("Hello World", { delay: 10 }); const buttonText = await (await button.getProperty('textContent')).jsonValue(); diff --git a/types/q-io/index.d.ts b/types/q-io/index.d.ts index 783f70ddc4..3b9e0462a1 100644 --- a/types/q-io/index.d.ts +++ b/types/q-io/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kriskowal/q-io // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/q-retry/index.d.ts b/types/q-retry/index.d.ts index 2d06f97f2e..d9b05477f8 100644 --- a/types/q-retry/index.d.ts +++ b/types/q-retry/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/vilic/q-retry // Definitions by: VILIC VANE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Q from 'q'; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index f0c95c7a8c..5875b4ef50 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1,8 +1,7 @@ -// Type definitions for ramda 0.24 +// Type definitions for ramda 0.25 // Project: https://github.com/donnut/typescript-ramda // Definitions by: Erwin Poeze // Matt DeKrey -// Liam Goodacre // Matt Dziuban // Stephen King // Alejandro Fernandez Haro @@ -11,6 +10,7 @@ // Simon Højberg // Charles-Philippe Clermont // Samson Keung +// Angelo Ocana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -226,9 +226,8 @@ declare namespace R { /** * Returns a new list containing the contents of the given list, followed by the given element. */ - append(el: U): (list: T[]) => Array<(T & U)>; - append(el: U, list: T[]): Array<(T & U)>; - append(el: T, list: string): Array; + append(el: T, list: T[]): T[]; + append(el: T): (list: T[]) => T[]; /** * Applies function fn to the argument list args. This is useful for creating a fixed-arity function from @@ -553,6 +552,14 @@ declare namespace R { */ empty(x: T): T; + /** + * Checks if a list ends with the provided values + */ + endsWith(a: string, list: string): boolean; + endsWith(a: string): (list: string) => boolean; + endsWith(a: T | T[], list: T[]): boolean; + endsWith(a: T | T[]): (list: T[]) => boolean; + /** * Takes a function and two values in its domain and returns true if the values map to the same value in the * codomain; false otherwise. @@ -1000,7 +1007,7 @@ declare namespace R { * returns the result. Subsequent calls to the memoized fn with the same argument set will not result in an * additional call to fn; instead, the cached result for that set of arguments will be returned. */ - memoize(fn: (...a: any[]) => any): (...a: any[]) => any; + memoize(fn: (...a: any[]) => T): (...a: any[]) => T; /** * Create a new object with the own properties of a @@ -1161,6 +1168,7 @@ declare namespace R { * returned in subsequent invocations. */ once(fn: (...a: any[]) => any): (...a: any[]) => any; + once(fn: (...a: any[]) => T): (...a: any[]) => T; /** * A function that returns the first truthy of two arguments otherwise the last argument. Note that this is @@ -1189,18 +1197,18 @@ declare namespace R { pair(fst: F, snd: S): [F, S]; /** - * Accepts as its arguments a function and any number of values and returns a function that, - * when invoked, calls the original function with all of the values prepended to the - * original function's arguments list. In some libraries this function is named `applyLeft`. + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided initially followed by the arguments provided to `g`. */ - partial(fn: (...a: any[]) => any, ...args: any[]): (...a: any[]) => any; + partial(fn: (...a: any[]) => T, args: any[]): (...a: any[]) => T; /** - * Accepts as its arguments a function and any number of values and returns a function that, - * when invoked, calls the original function with all of the values appended to the original - * function's arguments list. + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided to `g` followed by the arguments provided initially. */ - partialRight(fn: (...a: any[]) => any, ...args: any[]): (...a: any[]) => any; + partialRight(fn: (...a: any[]) => T, args: any[]): (...a: any[]) => T; /** * Takes a predicate and a list and returns the pair of lists of elements diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 2ce8bae2ca..ddaf6d95b1 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -262,22 +262,22 @@ R.times(i, 5); })(); (() => { - function multiply(a: number, b: number) { + function multiply(a: number, b: number): number { return a * b; } - const double = R.partial(multiply, 2); + const double = R.partial(multiply, [2]); double(2); // => 4 function greet(salutation: string, title: string, firstName: string, lastName: string) { return `${salutation}, ${title} ${firstName} ${lastName}!`; } - const sayHello = R.partial(greet, "Hello"); - const sayHelloToMs = R.partial(sayHello, "Ms."); + const sayHello = R.partial(greet, ["Hello"]); + const sayHelloToMs = R.partial(sayHello, ["Ms."]); sayHelloToMs("Jane", "Jones"); // => 'Hello, Ms. Jane Jones!' - const greetMsJaneJones = R.partialRight(greet, "Ms.", "Jane", "Jones"); + const greetMsJaneJones = R.partialRight(greet, ["Ms.", "Jane", "Jones"]); greetMsJaneJones("Hello"); // => 'Hello, Ms. Jane Jones!' })(); @@ -301,12 +301,20 @@ R.times(i, 5); // Note that argument order matters memoTrackedAdd(2, 1); // => 3 numberOfCalls; // => 3 + + function stringLength(str: string): number { + return str.length; + } + const memoStringLength = R.memoize(stringLength); + const isLong = memoStringLength('short') > 10; // false })(); (() => { const addOneOnce = R.once((x: number) => x + 1); addOneOnce(10); // => 11 addOneOnce(addOneOnce(50)); // => 11 + + const str = R.once(() => 'test')(); })(); (() => { @@ -443,10 +451,6 @@ R.times(i, 5); R.append("tests", ["write", "more"]); // => ['write', 'more', 'tests'] R.append("tests")(["write", "more"]); // => ['write', 'more', 'tests'] R.append("tests", []); // => ['tests'] - R.append(["tests"], ["write", "more"]); // => ['write', 'more', ['tests']] - R.append(["tests"], ["write", "more"]); // => ['write', 'more', ['tests']] - R.append(["tests"])(["write", "more"]); // => ['write', 'more', ['tests']] - R.append(["tests"])(["write", "more"]); // => ['write', 'more', ['tests']] }; () => { @@ -2241,6 +2245,15 @@ class Rectangle { R.isEmpty({a: 1}); // => false }; +() => { + R.endsWith("c", "abc"); // => true + R.endsWith("c")("abc"); // => true + R.endsWith(3, [1, 2, 3]); // => true + R.endsWith(3)([1, 2, 3]); // => true + R.endsWith([3], [1, 2, 3]); // => true + R.endsWith([3])([1, 2, 3]); // => true +}; + () => { R.not(true); // => false R.not(false); // => true diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts new file mode 100644 index 0000000000..d402d24ad2 --- /dev/null +++ b/types/react-alert/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for react-alert 2.4 +// Project: https://github.com/schiehll/react-alert +// Definitions by: Steve Syrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +export interface AlertContainerProps { + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + offset: number; + + /** + * The position of the alert. Can be [bottom left, bottom right, top left, top right]. + * + * Default: 'bottom left' + */ + position: string; + + /** + * The color theme of the alert. Can be [dark, light]. + * + * Default: 'dark' + */ + theme: string; + + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure + * (applies to all alerts). + * + * Default: 5000 + */ + time: number; + + /** + * The transition animation. Can be [scale, fade]. + * + * Default: 'scale' + */ + transition: string; +} + +export interface AlertShowOptions { + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure. + */ + time?: number; + + /** + * The icon to show in the alert. + * + * Default: the icon which matches the type of alert to be shown. + */ + icon?: React.ReactNode; + + /** + * A callback function that will be called when the alert is closed. + */ + onClose?: () => void; + + /** + * The type of alert to show. This will only be used when calling show(). + * Can be [info, success, error]. + * + * Default: 'info' + */ + type?: string; +} + +export default class AlertContainer extends React.Component { + /** + * Show a success alert. + * @returns The id of the created alert. + */ + success(message: string, options?: AlertShowOptions): string; + + /** + * Show an error alert. + * @returns The id of the created alert. + */ + error(message: string, options?: AlertShowOptions): string; + + /** + * Show an info alert. + * @returns The id of the created alert. + */ + info(message: string, options?: AlertShowOptions): string; + + /** + * Show an alert. + * @returns The id of the created alert. + */ + show(message: string, options?: AlertShowOptions): string; + + /** + * Remove all alerts from the page. + */ + removeAll(): void; + + /** + * Removes the alert with the specified id from the page. + */ + remove(id: string): void; +} diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx new file mode 100644 index 0000000000..84686ea73d --- /dev/null +++ b/types/react-alert/react-alert-tests.tsx @@ -0,0 +1,48 @@ +import * as React from "react"; +import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; + +export class ReactAlertTest extends React.Component { + private _alert: AlertContainer; + render() { + const props: AlertContainerProps = { + offset: 14, + position: "bottom left", + theme: "dark", + time: 5000, + transition: "scale" + }; + + return ( +
      + this._alert = a as AlertContainer} {...props} /> +
      + ); + } + + private _testMethods(): void { + const options: AlertShowOptions = { + time: 5000, + type: "info", + onClose: this._onAlertClosed, + icon: + }; + + let alertId: string; + alertId = this._alert.show("show without options"); + alertId = this._alert.show("show with options", options); + + alertId = this._alert.error("error without options"); + alertId = this._alert.error("error with options", options); + + alertId = this._alert.info("info without options"); + alertId = this._alert.info("info with options", options); + + alertId = this._alert.success("success without options"); + alertId = this._alert.success("success with options", options); + + this._alert.remove(alertId); + this._alert.removeAll(); + } + + private _onAlertClosed(): void { } +} diff --git a/types/react-alert/tsconfig.json b/types/react-alert/tsconfig.json new file mode 100644 index 0000000000..9332254f22 --- /dev/null +++ b/types/react-alert/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "react-alert-tests.tsx" + ] +} diff --git a/types/react-alert/tslint.json b/types/react-alert/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alert/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-autosuggest/index.d.ts b/types/react-autosuggest/index.d.ts index 9205f63d4c..b1f080efe5 100644 --- a/types/react-autosuggest/index.d.ts +++ b/types/react-autosuggest/index.d.ts @@ -9,6 +9,7 @@ // TypeScript Version: 2.3 import * as React from 'react'; + declare class Autosuggest extends React.Component {} export = Autosuggest; @@ -57,22 +58,11 @@ declare namespace Autosuggest { method: 'click' | 'enter'; } - interface Theme { - container?: string; - containerOpen?: string; - input?: string; - inputOpen?: string; - inputFocused?: string; - suggestionsContainer?: string; - suggestionsContainerOpen?: string; - suggestionsList?: string; - suggestion?: string; - suggestionFirst?: string; - suggestionHighlighted?: string; - sectionContainer?: string; - sectionContainerFirst?: string; - sectionTitle?: string; - } + type ThemeKey = 'container' | 'containerOpen' | 'input' | 'inputOpen' | 'inputFocused' | 'suggestionsContainer' | + 'suggestionsContainerOpen' | 'suggestionsList' | 'suggestion' | 'suggestionFirst' | 'suggestionHighlighted' | + 'sectionContainer' | 'sectionContainerFirst' | 'sectionTitle'; + + type Theme = Record | Partial>; interface AutosuggestProps extends React.Props { suggestions: any[]; diff --git a/types/react-autosuggest/react-autosuggest-tests.tsx b/types/react-autosuggest/react-autosuggest-tests.tsx index c67a5c72ad..23841519e4 100644 --- a/types/react-autosuggest/react-autosuggest-tests.tsx +++ b/types/react-autosuggest/react-autosuggest-tests.tsx @@ -85,7 +85,8 @@ export class ReactAutosuggestBasicTest extends React.Component { const theme = { input: 'themed-input-class', container: 'themed-container-class', - suggestionFocused: 'active' + suggestionFocused: 'active', + sectionTitle: { color: 'blue' } }; return , Aleksander Lode , Josué Us +// Definitions by: Frank Laub , +// Aleksander Lode , +// Josué Us +// Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - // documentation taken from http://allenfang.github.io/react-bootstrap-table/docs.html -import { ComponentClass, Props, ReactElement } from 'react'; -import { EventEmitter } from 'events'; +import { Component, CSSProperties, Props, ReactElement, SyntheticEvent } from 'react'; + +/** + * Table scroll position. + */ +export type ScrollPosition = 'Top' | 'Bottom'; + +/** + * Row selection mode. Single selection = 'radio', multiple selection = 'checkbox'. + */ +export type SelectRowMode = 'none' | 'radio' | 'checkbox'; + +/** + * Sort Order values. 'asc' = ascending, 'desc' = descending. + */ +export type SortOrder = 'asc' | 'desc'; + +/** + * Type of selection for cell editing. + */ +export type CellEditClickMode = 'none' | 'click' | 'dbclick'; + +/** + * Tell react-bootstrap-table how to trigger expanding by clicking on 'row' or 'column' level. + * If the value is 'column', by default all the columns are expandable. If you want to specify some columns as + * unexpandable, check expandable. + * Default is 'row'. + */ +export type ExpandBy = 'row' | 'column'; + +/** + * Used to specify whether a dropdown button should use 'dropup' mode or 'dropdown' mode. + * Default is usually 'dropdown'. + */ +export type DropDirection = 'dropdown' | 'dropup'; + +/** + * List of valid filter types. + * Note: ArrayFilter can only be used as part of the FilterData passed to the BootstrapTable.handleFilterData + * function. It is NOT valid for use when specifying a filter to the TableHeaderColumn filter properties. + */ +export type FilterType = + | 'TextFilter' + | 'RegexFilter' + | 'SelectFilter' + | 'NumberFilter' + | 'DateFilter' + | 'CustomFilter' + | 'ArrayFilter'; + +/** + * Filter conditions that can be used with TextFilter/SelectFilter/RegexFilter filters. + */ +export type FilterCondition = 'eq' | 'like'; + +/** + * Filter comparators used for NumberFilter/DateFilter filters + */ +export type FilterComparator = '=' | '<' | '<=' | '>' | '>=' | '!='; + +/** + * Element type to use for editing a particular column's cells. + */ +export type EditCellType = 'textarea' | 'select' | 'checkbox' | 'datetime'; + +/** + * Position to show the Pagination Panel. Options are above the table ('top'), below the table ('bottom'), or both + * above and below the table ('both'). + */ +export type PaginationPostion = 'top' | 'bottom' | 'both'; + +/** + * Result type for validation when editing. + */ +export type EditValidatorType = 'success' | 'error'; + +/** + * Used to specify the text alignment for a column. + */ +export type DataAlignType = 'left' | 'center' | 'right' | 'start' | 'end'; + +/** + * Boostrap version number. + */ +export type BootstrapVersion = '3' | '4'; + +/** + * CSV Field types supported. + */ +export type CSVFieldType = 'string' | 'number'; + +/** + * Custom attributes for a column/cell/etc. + * Example: { 'data-attr': 'test' } + */ +export interface CustomAttrs { + [attrKey: string]: string | number | boolean; +} + +/** + * Size per page list definition + */ +export type SizePerPageList = number[] | Array<{ text: string, value: number }>; /** * Interface spec for sepcifying functionality to handle remotely * * Consult [documentation](https://allenfang.github.io/react-bootstrap-table/docs.html#remote) * for more info - * */ export interface RemoteObjSpec { - /** If set, cell edits will be handled remotely */ + /** + * If set, cell edits will be handled remotely + */ cellEdit?: boolean; - /** If set insertions will be handled remotely */ + /** + * If set insertions will be handled remotely + */ insertRow?: boolean; - /** If set deletion will be handled remotely */ + /** + * If set deletion will be handled remotely + */ dropRow?: boolean; - /** If set filters will be handled remotely */ + /** + * If set filters will be handled remotely + */ filter?: boolean; - /** If set search will be handled remotely */ + /** + * If set search will be handled remotely + */ search?: boolean; - /** If set, exporting CSV will be handled remotely */ + /** + * If set, exporting CSV will be handled remotely + */ exportCSV?: boolean; - /** If set sorting will be handled remotely */ + /** + * If set sorting will be handled remotely + */ sort?: boolean; - /** If set pagination will be handled remotely */ + /** + * If set pagination will be handled remotely + */ pagination?: boolean; } export interface BootstrapTableProps extends Props { /** - * Set version='4' to use bootstrap@4, else bootstrap@3 is used. + * Bootstrap version to use, values include '3' or '4'. Defaults to '3'. */ - version?: string; + version?: BootstrapVersion; /** * Use data to specify the data that you want to display on table. */ - data: any[]; + data: object[]; /** - * If set, data is remote (use also fetchInfo) + * Normally, react-bootstrap-table handles all the data sorting/filtering/pagination/etc itself internally. + * If this is true, you need to handle all of those manually outside the table. By default it is false. + * This is used mostly with an external/central data store, for example Redux or a database that returns + * already filtered/sorted/paged data. + * + * If a function given, which means you can choose which functionality should be handled with remote or not.Currently, + * we have following functionality you can control: sort, pagination, cellEdit, insertRow, dropRow, filter, search, + * exportCSV. */ - remote?: ((remobeObj: RemoteObjSpec) => RemoteObjSpec) | boolean; // Updated to support ^3.0.0 + remote?: boolean | ((remobeObj: RemoteObjSpec) => RemoteObjSpec); /** * Use keyField to tell table which column is unique. This is same as isKey in - * Tips: You need choose one configuration to set key field: keyField or isKey in + * Tips: react-bootstrap-table support data manipulation(CRUD) so that we need to fetch correct row by a unique column. + * You need choose one of configuration to set the key field: isKey or keyField in . */ keyField?: string; /** - * Use height to set the height of table, default is 100%. + * Use height to set the height of table, default is 100%. The string needs to have a unit, e.g. 'px', '%'. */ height?: string; /** - * Set the max column width (pixels) + * Set the maximum height of table. You need give a string with an unit(px) value like height. */ maxHeight?: string; /** @@ -88,19 +213,19 @@ export interface BootstrapTableProps extends Props { * If a string given, means the value will be presented as the row class. * If a function given, will pass rowData and rowIndex as params and should return string for presenting class. for examples: * @example - * function trClassFormat(rowData,rowIndex){ - * return rowIndex%2==0?"tr-odd":"tr-even"; //return a class name. - * } + * function trClassFormat(rowData,rowIndex) { + * return rowIndex % 2 == 0 ? "tr-odd" : "tr-even"; // return a class name. + * } */ - trClassName?: string | ((rowData: any, rowIndex: number) => string); + trClassName?: string | ((rowData: ReadonlyArray, rowIndex: number) => string); /** * Enable row insertion by setting insertRow to true, default is false. - * If you enable row insertion, there's a button on the upper left side of table. + * If you enable row insertion, there's a button on the upper left side of table. */ insertRow?: boolean; /** * Enable row deletion by setting deleteRow to true, default is false. - * If you enable row deletion, there's a button on the upper left side of table. + * If you enable row deletion, there's a button on the upper left side of table. */ deleteRow?: boolean; /** @@ -118,8 +243,8 @@ export interface BootstrapTableProps extends Props { */ searchPlaceholder?: string; /** - * Enable strict search, default is false. - * More info here: https://github.com/AllenFang/react-bootstrap-table/issues/1199 + * Strict search. Set this flag to apply search terms so that only rows that contain ALL terms are included in the + * search results. */ strictSearch?: boolean; /** @@ -130,15 +255,101 @@ export interface BootstrapTableProps extends Props { multiColumnSearch?: boolean; /** * Enable export csv function, default is false. - * If you enable, there's a button on the upper left side of table. + * If you enable, there's a button on the upper left side of table. */ exportCSV?: boolean; /** * Set CSV filename (e.g. items.csv). Default is spreadsheet.csv */ - csvFileName?: () => string | string; + csvFileName?: string | (() => string); /** - * Enable row selection on table. selectRow accept an object which have the following properties + * If true, it will hide the pagination if there is only one page, default is false. + */ + ignoreSinglePage?: boolean; + /** + * Specify a fix position for the vertical bar if it exist. Available is a number or Top and Bottom + */ + scrollTop?: number | ScrollPosition; + /** + * Add css styles to the react-bs-table-container class. + * For example: containerStyle={ { background: '#00ff00' } } + */ + containerStyle?: CSSProperties; + /** + * Add css styles to the react-bs-table class. + */ + tableStyle?: CSSProperties; + /** + * Add css styles to the react-bs-container-header class. + */ + headerStyle?: CSSProperties; + /** + * Add css styles to the react-bs-container-body class. + */ + bodyStyle?: CSSProperties; + /** + * Add your own class names on the react-bs-table-container class + */ + containerClass?: string; + /** + * Add your own class names on the react-bs-table class + */ + tableContainerClass?: string; + /** + * Add your own class names on the react-bs-container-header class + */ + headerContainerClass?: string; + /** + * Add your own class names on the react-bs-container-body class + */ + bodyContainerClass?: string; + /** + * react-bootstrap-table separate two table element as header and body. + * The tableHeaderClass is for the table element in the header + */ + tableHeaderClass?: string; + /** + * react-bootstrap-table separate two table element as header and body. + * The tableBodyClass is for the table element in the body + */ + tableBodyClass?: string; + /** + * Tell react-bootstrap-table which rows are able to expand. This prop accepts + * a callback function and is suppose to be return an Array of row keys. + * expandableRow is always used with expandComponent, both of props are enable + * the expand row functionality on table. + */ + expandableRow?(row: any): boolean; + /** + * Tell react-bootstrap-table what's content should be rendered in the expanding + * content. This props accept a callback function and is suppose to be return JSX + * or String. + * expandComponent is always used with expandableRow, both of props are enable + * the expand row functionality on table. + */ + expandComponent?(row: any): string | ReactElement; + /** + * Assign some alternative options for expand row feature, expandColumnOptions + * only have four available property currently. + */ + expandColumnOptions?: ExpandColumnOptions; + /** + * Enable the multi sort on table and the number value is means max number of sorting column. + */ + multiColumnSort?: number; + /** + * This prop will enable/disable the keyboard navigation cell by cell on table. This is new + * feature from 3.0.0. Default is false. You can have a basic and simple keyboard navigation + * feature on table by enabling keyBoardNav on BootstrapTable. For the usage of keyboard + * navigation is you can click any cell to focus in or use ⬅ ⬆ ⬇ ➡ to natigate the cell. + * + * But if you want more advance features for keyboard navigation or to integrate with cell + * editing, expand row or selection row, you may get interested to see how they work well + * together: In the advance cases, you need to configure keyBoardNav as an object. + */ + keyBoardNav?: boolean | KeyboardNavigation; + /** + * Enable row selection on table. SelectRow accept an object. */ selectRow?: SelectRow; /** @@ -149,51 +360,119 @@ export interface BootstrapTableProps extends Props { * For some options setting on this component, you can set the options attribute and give an object which contain following properties */ options?: Options; + /** + * Used to specify the total number of rows (matching current filter/sort/size per page) in a remote data source. + * Documented in examples, but missing from the main docs. Essential for remote data pagination calculations. + */ fetchInfo?: FetchInfo; - printable?: boolean; - tableStyle?: any; - containerStyle?: any; - headerStyle?: any; - bodyStyle?: any; - ignoreSinglePage?: boolean; - containerClass?: string; - tableContainerClass?: string; - headerContainerClass?: string; - bodyContainerClass?: string; - expandableRow?: (row: any) => boolean; - expandComponent?: (row: any) => any; + /** + * Automatically collapses open rows when doing a sort/filter/search action if those options have been specified. + * Is an object with three possible fields: sort, filter, search. Each field is a flag to specify whether that + * action type should cause expanded rows to close. All three fields default to false. + */ + autoCollapse?: { + sort?: boolean; + filter?: boolean; + search?: boolean; + }; + /** + * Set a style to be used for the table rows. + */ + trStyle?: CSSProperties; + /** + * Disable the automatic tabIndex for navigating between cells. This can be useful if you have a page with multiple + * tables on the page, to stop the tab moving to another table. Default is false. + */ + withoutTabIndex?: boolean; + /** + * Disable writing the header row when exporting to a CSV file. + */ + excludeCSVHeader?: boolean; + /** + * Add a footer to the table. + */ + footer?: boolean; + /** + * Data for the table footer. Format is an array of footer rows, each containing an array of column footer data. + */ + footerData?: FooterData[][]; + /** + * Table footer custom class + */ + tableFooterClass?: string; } -export type SelectRowMode = 'none' | 'radio' | 'checkbox'; - -export interface SelectRow { +/** + * Footer Data for a column. + */ +export interface FooterData { /** - * For specifing the selection is single(radio) or multiple(checkbox). + * Title to display for the column footer + */ + label: string; + /** + * Index for the column that this footer belongs to + */ + columnIndex: number; + /** + * Text alignment for the data in this footer. + */ + align?: DataAlignType; + /** + * Formatting function for the data in this footer. Used to be able to do things like sum the contents of this + * column in the table so that the footer can be used for totals, etc. + * + * The output value from the formatter function will be used instead of the label if the formatter function is + * defined. + */ + formatter?(tableData: any[]): string | number | ReactElement; +} + +export interface SelectRow { + /** + * Specify whether the selection column uses single(radio) or multiple(checkbox) selection modes. Required. */ mode: SelectRowMode; /** - * Click the row will trigger selection on that row if enable clickToSelect, default is false. + * If true, clicking the row will trigger selection on that row, default is false. */ clickToSelect?: boolean; /** - * If true, click the row will trigger selection on that row and also trigger cell editing if you enabled cell edit. Default is false. + * If true, clicking the row will trigger selection on that row and also trigger cell editing if you enabled cell edit. Default is false. */ clickToSelectAndEditCell?: boolean; /** - * You can assign the background color of row which be selected. + * If true, clicking the row will trigger expanding the row. Default is false. */ - bgColor?: string; + clickToExpand?: boolean; /** - * You can assign the class name of row which be selected. + * You can assign the background color of row which be selected. + * If your requirement is much complex, you can assign a function to bgColor that + * returns a css color string. */ - className?: string; + bgColor?: string | ((row: TRow, isSelect: boolean) => string); + /** + * You can change the width of the selection column by columnWidth (include units). + */ + columnWidth?: string; + /** + * You can assign the class name of selected rows. This can either be a string, or a function that takes two + * arguments: row and isSelect. + * `row`: The current row data. + * `isSelect`: Flag indicating whether this particular row is selected. + */ + className?: string | ((row: TRow, isSelect: boolean) => string); /** * Give an array data to perform which rows you want to be selected when table loading. - * The content of array should be the rowkey which you want to be selected. + * The content of array should be the rowkeys for the rows that you want to be selected. */ - selected?: string[] | number[]; + selected?: Array; /** - * if true, the radio/checkbox column will be hide. + * Provide a list of unselectable row keys. + */ + unselectable?: Array; + /** + * If true, the radio/checkbox column will be hidden. * You can enable this attribute if you enable clickToSelect and you don't want to show the selection column. */ hideSelectColumn?: boolean; @@ -203,282 +482,635 @@ export interface SelectRow { showOnlySelected?: boolean; /** * Accept a custom callback function, if a row be selected or unselected, this function will be called. - * This callback function taking three arguments row, isSelected and event: - * `row`: is the row data which you wanted to select or unselect. - * `isSelected`: it's a boolean value means "whether or not that row will be selected?". - * `event`: The event target object. - * If return value of this (function) is false, the select or deselect action will not be applied. + * This callback function takes four arguments: row, isSelected, event, and rowIndex: + * `row`: is the row data which you wanted to select or unselect. + * `isSelected`: it's a boolean value means "whether or not that row will be selected?". + * `event`: The event target object. + * `rowIndex`: the index number for the row. + * If the return value of this (function) is false, the select or deselect action will not be applied. */ - onSelect?: (row: any, isSelected: boolean, event: any) => boolean; + onSelect?(row: TRow, isSelected: boolean, event: any, rowIndex: number): boolean | void; /** - * Accept a custom callback function, if click select all checkbox, this function will be called. - * This callback function taking two arguments isSelected and currentSelectedAndDisplayData: - * `isSelected`: it's a boolean value means "whether or not that row will be selected?". - * `currentSelectedAndDisplayData`: If pagination enabled, this result is the data which in a page. In contrast, this is all data in table. - * If return value of this function is false, the select all or deselect all action will not be applied. + * Accept a custom callback function, if click select all checkbox, this function will be called. This callback + * function taking two arguments: isSelected, rows. + * isSelectedis a boolean value which means "whether or not that row will be selected?". + * rows is the rows which be selected or unselected. + * + * Tips: + * If the return value of this function is false, the select all or deselect all action will not be applied. + * If return value of this function is an array of rowkeys, this array will be applied as selection row when + * select all triggers. It's useful when you have a validation to filter some rows on selecting all. */ - onSelectAll?: (isSelected: boolean, currentSelectedAndDisplayData: any) => boolean; - + onSelectAll?(isSelected: boolean, rows: TRow[]): boolean | Array; /** - * Provide a list of unselectable row keys. + * Function that returns a component to customize the display of the selection checkbox or radio button with. */ - unselectable?: number[]; + customComponent?(props: CustomSelectProps): string | ReactElement; + /** + * Only unselect visible rows. + */ + onlyUnselectVisible?: boolean; } -export type CellEditClickMode = 'none' | 'click' | 'dbclick'; - -export interface CellEdit { +/** + * react-bootstrap-table supports cell editing. When you enable this feature, react-bootstrap-table will make + * the target cell editable by either clicking or dbclicking (depending on the properties you set). + */ +export interface CellEdit { /** - * To spectify which condition will trigger cell editing.(click or dbclick) + * Spectify which condition will trigger cell editing.(click or dbclick). Required. */ mode: CellEditClickMode; /** - * Enable blurToSave will trigger a saving event on cell when mouse blur on the input field. Default is false. + * Enabling blurToSave will trigger a saving event on the cell when the input field becomes deselected. Default is false. * In the default condition, you need to press ENTER to save the cell. */ blurToSave?: boolean; /** - * Accept a custom callback function, before cell saving, this function will be called. - * This callback function taking three arguments:row, cellName and cellValue - * It's necessary to return a bool value which whether apply this cell editing. + * Enabling blurToEscape will result in a cell edit being cancelled when the user clicks outside the table during + * editing. + * Default is false. */ - beforeSaveCell?: (row: any, cellName: string, cellValue: any) => boolean; + blurToEscape?: boolean; + /** + * nonEditableRows tell react-bootstrap-table which rows should not be edited on all of the columns. Briefly, its a row level limitation + * Please assign a callback function, and this function is supposed to be return an array of row keys. + */ + nonEditableRows?(): Array; + /** + * Accept a custom callback function, before cell saving, this function will be called. + * This callback function takes four arguments: row, cellName, cellValue and done. + * `row`: the row data to be saved. + * `cellName`: the column dataField cell name that has been modified. + * `cellValue`: the new cell value. + * `done`: a callback function to use if this is an async operation, to indicate if the save data is valid. + * If your validation is async, for example: you want to pop a confirm dialog for user to confim in this case, + * react-bootstrap-table pass a callback function to you. You are supposed to call this callback function with a + * bool value to perfom if it is valid or not in addition, you should return 1 from the main function to tell + * react-bootstrap-table that this is a async operation. + */ + beforeSaveCell?(row: TRow, cellName: K, cellValue: TRow[K], done: (isValid: boolean) => void): boolean | 1; /** * Accept a custom callback function, after cell saving, this function will be called. - * This callback function taking three arguments:row, cellName and cellValue + * This callback function takes three arguments: row, cellName and cellValue */ - afterSaveCell?: (row: any, cellName: string, cellValue: any) => void; + afterSaveCell?(row: TRow, cellName: K, cellValue: TRow[K]): void; } -export type SortOrder = 'asc' | 'desc'; - -export interface Options { +/** + * Main Options for the Bootstrap Table. + */ +export interface Options { /** - * Manage sort field by yourself + * Provide the name of the column that should be sorted by. + * If multi-column sort is active, this is an array of columns. */ - sortName?: string; + sortName?: keyof TRow | Array; /** - * Manage sort order by yourself + * Specify whether the sort should be ascending or descending. + * If multi-column sort is active, this is an array of sortOrder items. */ - sortOrder?: SortOrder; + sortOrder?: SortOrder | SortOrder[]; /** - * Assign a default sort field. + * Specify the default sort column. + * Note: when using cleanSort(), this default sort column will be restored. */ - defaultSortName?: string; + defaultSortName?: keyof TRow; /** - * Assign a default sort ordering. + * Assign a default sort order. + * Note: when using cleanSort(), this default sort order will be restored. */ defaultSortOrder?: SortOrder; /** - * False to disable sort indicator on header column, default is true. + * Set to false to disable sort indicators on header columns, default is true. */ sortIndicator?: boolean; /** - * Change the displaying text on table if data is empty. + * Assign a callback function which will be called after triggering sorting. + * This function takes two argument: `sortName` and `sortOrder`. + * `sortName`: The sort column name, or array of column names if multi-column sort is active. + * `sortOrder`: The sort ordering, or array of ordering if multi-column sort is active. + */ + onSortChange?: + | ((sortName: keyof TRow, sortOrder: SortOrder) => void) + | ((sortName: ReadonlyArray, sortOrder: ReadonlyArray) => void); + /** + * Change the text displayed on the table if data is empty. */ noDataText?: string | ReactElement; + /** + * If true, this hides the noDataText on the table when the tableis empty. Default is false. + */ + withoutNoDataText?: boolean; /** * A delay for trigger search after a keyup (millisecond) */ searchDelayTime?: number; /** - * A custom text on export csv button - */ - exportCSVText?: string; - /** - * Default is false, if true means you want to ignore any editable configuration when row insert. - */ - ignoreEditable?: boolean; - /** - * Only work on enable search. If true, there will be a button beside search input field for clear search field text. + * Only work on enable search. If true, there will be a button beside the search input field + * that will empty the field when clicked. */ clearSearch?: boolean; /** - * Assign a callback function which will be called after table update. + * Set the default search condition. */ - afterTableComplete?: Function; + defaultSearch?: string; + /** + * Assign a callback function which will be called when search text changes. This function takes + * three argument: + * `searchText`: the text from the search field. + * `colInfos`: Array of column settings (e.g. filterFormatted, etc). + * `multiColumnSearch`: True if multiple column search is enabled. + * In most cases, you only need to use searchText. This function usually used for remote searching. + */ + onSearchChange?(searchText: string, colInfos: ReadonlyArray>, multiColumnSearch: boolean): void; + /** + * Assign a callback function which will be called after triggering searching. + * This function takes two argument: search and result. + * `search`: The search text from the user. + * `result`: The results after searching (array of rows that matched the search). + */ + afterSearch?(search: string, result: ReadonlyArray): void; + /** + * Default is false, if true means you want to ignore any editable columns when creating the insert form. + */ + ignoreEditable?: boolean; + /** + * Assign a callback function that will be called after table updates. + */ + afterTableComplete?(): void; /** * Assign a callback function which will be called after row delete. - * This function taking one argument: rowKeys, which means the row key you dropped. + * This function takes two arguments: + * `rowKeys`: which means the row keys for the deleted rows + * `rows`: the array of row data that was deleted. */ - afterDeleteRow?: (rowKeys: string[]) => void; + afterDeleteRow?(rowKeys: ReadonlyArray, rows: ReadonlyArray): void; /** - * Assign a callback function which will be called after row insert. - * This function taking one argument: row, which means the whole row data you added. + * Assign a callback function which will be called after inserting a row. + * This function takes one argument: row, which means the whole row data you added. */ - afterInsertRow?: (row: any) => void; + afterInsertRow?(row: TRow): void; /** - * Customize the text of previouse page button + * Assign a callback function which will be called after triggering column filtering. + * This function takes two arguments: filterConds and result. + * `filterConds`: It's an array object which contain all column filter conditions. + * `result`: The results after filtering. + * + * This function only work when you enable columnFilter on or define + * a filter on . */ - prePage?: string; + afterColumnFilter?(filterConds: ReadonlyArray, result: ReadonlyArray): void; /** - * Customize the text of next page button + * Assign a callback function which will be called when a row is added. This function + * takes three arguments: + * `row`: which represents the new row data + * `colInfos`: Array of Column Descriptions for the table. + * `errorCallback`: Function to call to provide an async error message if the Add fails. + * The function should either return a string immediately, or return false and then return a string through the + * error callback function later. */ - nextPage?: string; + onAddRow?(row: TRow, colInfo: ReadonlyArray>, errorCallback: (message: string) => void): string | boolean; /** - * Customize the text of first page button + * Assign a callback function which will be called when a filter condition changes. + * This function takes one argument: filterObj which is an object which take dataField + * as object key and the value is the filter condition. */ - firstPage?: string; + onFilterChange?(filterObject: FilterData): void; /** - * Customize the text of last page button + * Assign a callback function which will be called when the export csv button is clicked. + * In this function, you need to return an array of rows to be exported. */ - lastPage?: string; + onExportToCSV?(): TRow[]; + /** + * Assign a callback function which will be called when a row been deleted. + * This function takes two arguments: + * `rowKeys`: keys for the rows to be deleted. + * `rows`: row data for the rows to be deleted. + */ + onDeleteRow?(rowKeys: ReadonlyArray, rows: ReadonlyArray): void; + /** + * Assign a callback function which will be called after a row click. + * This function takes three arguments: + * `row`: which is the row data that was clicked on. + * `columnIndex`: index of the column that was clicked on. + * `rowIndex`: index of the row that was clicked on. + */ + onRowClick?(row: TRow, columnIndex: number, rowIndex: number): void; + /** + * Assign a callback function which will be called after a row double click. + * This function takes one argument: row which is the row data that was double clicked on. + */ + onRowDoubleClick?(row: TRow): void; + /** + * Assign a callback function which will be called when mouse enters the table. + */ + onMouseEnter?(): void; + /** + * Assign a callback function which will be called when mouse leaves the table. + */ + onMouseLeave?(): void; + /** + * Assign a callback function which will be called when the mouse enters a row in table. + * This function takes two arguments: + * `row`: the row data the mouse entered + * `e`: the mouse event data + */ + onRowMouseOver?(row: TRow, e: React.MouseEvent): void; + /** + * Assign a callback function which will be called when mouse leaves a row in table. + * This function takes two arguments: + * `row`: the row data the mouse entered + * `e`: the mouse event data + */ + onRowMouseOut?(row: TRow, e: React.MouseEvent): void; + /** + * Assign a callback function which will be called when deleting a row. + * It gives you a chance to customize your confirmation for row deletion. + * This function takes two argument: next and rowKeys: + * `next`: If you confirm the delete, call next() to continue the process. + * `rowKeys` Is the row keys to be deleted, you can call the `next` function to apply this deletion. + */ + handleConfirmDeleteRow?(next: () => void, rowKeys: ReadonlyArray): void; + /** + * Customize the text of previouse page button. + * If using the default pagination panel, this should be a string to use for the button label. + * If creating a custom pagination panel, this is passed to the panel and can be of any type desired. + */ + prePage?: any; + /** + * Customize the text of next page button. + * If using the default pagination panel, this should be a string to use for the button label. + * If creating a custom pagination panel, this is passed to the panel and can be of any type desired. + */ + nextPage?: any; + /** + * Customize the text of first page button. + * If using the default pagination panel, this should be a string to use for the button label. + * If creating a custom pagination panel, this is passed to the panel and can be of any type desired. + */ + firstPage?: any; + /** + * Customize the text of last page button. + * If using the default pagination panel, this should be a string to use for the button label. + * If creating a custom pagination panel, this is passed to the panel and can be of any type desired. + */ + lastPage?: any; /** * Accept a number, which means the page you want to show as default. */ page?: number; /** * You can change the dropdown list for size per page if you enable pagination. + * Default is [10, 25, 30, 50]. */ - sizePerPageList?: number[]; + sizePerPageList?: SizePerPageList; /** - * Means the size per page you want to locate as default. + * Current chosen size per page. */ sizePerPage?: number; /** - * To define the pagination bar length, default is 5. + * Number of page buttons to show on the pagination bar, default is 5. + * i.e. previous 2 pages + current page + next two pages = 5. */ paginationSize?: number; /** - * To define where to start counting the pages. + * Hide the dropdown list for size per page, default is false. + */ + hideSizePerPage?: boolean; + /** + * Display a short text showing the total number of rows and current lines displayed, + * default is false. If you want to customize this short text, you can give a function + * and this function take three arguments: + * `start`: Current start index + * `to`: Current end index + * `total`: The total data volume. + */ + paginationShowsTotal?: boolean | ((start: number, to: number, total: number) => string | ReactElement); + /** + * Allows you to modify where to start counting the pages, e.g. to set the first page number to 0. + * Default is 1. */ pageStartIndex?: number; /** * Assign a callback function which will be called after page changed. - * This function taking two argument: page and sizePerPage. - * `page`: Current page. - * `sizePerPage`: The data size which in one page. + * This function takes two argument: page and sizePerPage. + * `page`: New page number + * `sizePerPage`: The number of rows to display in one page. */ - onPageChange?: (page: number, sizePerPage: number) => void; + onPageChange?(page: number, sizePerPage: number): void; /** - * Assign a callback function which will be called after size per page dropdown changed. - * This function taking one argument: sizePerPage. - * `sizePerPage`: The data size which in one page. + * Assign a callback function which will be called after the size per page (number of rows per page) + * has been changed. + * This function takes one argument: sizePerPage. + * `sizePerPage`: The new number of rows to display in one page. */ - onSizePerPageList?: (sizePerPage: number) => void; + onSizePerPageList?(sizePerPage: number): void; /** - * Assign a callback function which will be called after trigger sorting. - * This function taking two argument: `sortName` and `sortOrde`r. - * `sortName`: The sort column name - * `sortOrder`: The sort ordering. + * Default is false. If true, the pagination list will be hidden when there is only one page. */ - onSortChange?: (sortName: string, sortOrder: SortOrder) => void; + hidePageListOnlyOnePage?: boolean; /** - * Assign a callback function which will be called after trigger searching. - * This function taking two argument: search and result. - * `search`: The search text which user input. - * `result`: The results after searching. - */ - afterSearch?: (search: string, result: any) => void; - /** - * Assign a callback function which will be called after trigger column filtering. - * This function taking two argument: filterConds and result. - * `filterConds`: It's an array object which contain all column filter conditions. - * `result`: The results after filtering. - */ - afterColumnFilter?: (filterConds: any[], result: any) => void; - /** - * Assign a callback function which will be called after a row click. - * This function taking one argument: row which is the row data which you click on. - */ - onRowClick?: (row: any) => void; - /** - * Assign a callback function which will be called after a row double click. - * This function taking one argument: row which is the row data which you double click on. - */ - onRowDoubleClick?: (row: any) => void; - /** - * Background color on expanded rows. + * Background color on expanded rows (css color value). */ expandRowBgColor?: string; /** - * Assign a callback function which will be called when mouse enter into the table. + * Tell react-bootstrap-table how to trigger expanding by clicking on 'row' or 'column' level. + * If the value is 'column', by default all the columns are expandable. If you want to specify some columns as + * unexpandable, check expandable. + * Default is 'row'. */ - onMouseEnter?: Function; + expandBy?: ExpandBy; /** - * Assign a callback function which will be called when mouse leave from the table. + * Customize the text on the insert button. */ - onMouseLeave?: Function; - /** - * Assign a callback function which will be called when mouse over a row in table. - * This function taking one argument: row which is the row data which mouse over. - */ - onRowMouseOver?: Function; - /** - * Assign a callback function which will be called when mouse leave from a row in table. - * This function taking one argument: row which is the row data which mouse out. - */ - onRowMouseOut?: Function; - - /** - * Assign a callback function which will be called when row dropping. - * It give you a chance to customize your confirmation for row deletion. - * This function taking two argument: next and rowKeys: - * `next`: If you confirm to drop row, call next() to continue the process - * `rowKeys` is the row keys which been deleted, you can call next function to apply this deletion. - */ - handleConfirmDeleteRow?: (next: Function, rowKeys: any[]) => void; - paginationShowsTotal?: boolean | ((start: number, to: number, total: number) => ReactElement); - onSearchChange?: Function; - onAddRow?: Function; - onExportToCSV?: Function; - insertText?: string; + /** + * Customize the text on the delete button. + */ deleteText?: string; + /** + * Customize the text on the save button in the insert modal. + */ saveText?: string; + /** + * Customize the text on the close button in the insert modal. + */ closeText?: string; - // Customization properties /** - * Callback function to be called when a cell is modified - * - * https://allenfang.github.io/react-bootstrap-table/example.html#remote - * + * Customize the text on the export csv button */ - onCellEdit?: (row: any, field: string, value: any) => any; + exportCSVText?: string; /** - * Callback function to be called when filter changing - * - * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-filtering.js#L67 - * + * You can do something before the toastr pop or even disable the toastr!! + * Returning false or void will not trigger the toastr. + * If you want the toastr popup, you should return true always. + * Inputs match the EditValidatorObject.notification field types. */ - onFilterChange?: (filterObj: any) => any; + beforeShowError?(type: EditValidatorType, msg: string, title: string): boolean | void; /** - * Callback function which will be called when a row will be deleted - * - * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-delete-row.js#L27 - * + * Default is true. If false, during printing the toolbar is hidden. */ - onDeleteRow?: (rows: any) => any; + printToolBar?: boolean; /** - * A callback which will be called after page changed - * - * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-paging.js#L30 - * + * ToolBar is the area on the top of table, it contain the search panel, buttons for data manipulation. + * After v3.0.0, you can custom all the components in the ToolBar also itself too. + * Give a toolBar in options props and toolBar only accept a function and a JSX returned value is necessary. */ - onpageChange?: (page: any, sizePerPage: number) => any; + toolBar?(props: ToolBarProps): ReactElement; + /** + * Button group which contain the insert, drop, show only select and export CSV buttons, these button all + * grouped as btn-group class in bootstrap. This is a chance that you can custom this button group. + * Give a btnGroup in options props and btnGroup only accept a function and a JSX returned value is necessary. + * This lets you customize just the left-hand-side of the toolbar if desired. + */ + btnGroup?(props: ButtonGroupProps): ReactElement; + /** + * It's available to customize the insert button by configuring insertBtn in options props, insertBtn only + * accept a function and a JSX returned value is necessary. This function will take one argument: onClick. + * + * The default `InsertButton` component is also exported as a component, so that you can use it as the base + * for your custom component. + */ + insertBtn?(onClick: (e: React.MouseEvent) => void): ReactElement; + /** + * It's available to customize delete button by configuring deleteBtn in options props, deleteBtn onl) => void): ReactElement; + /** + * It's available to customize the export csv button by configuring exportCSVBtn in options props, exportCSVBtn only + * accept a function and a JSX returned value is necessary. This function will take one argument: onClick. + * + * The default `ExportCSVButton` component is also exported as a component, so that you can use it as the base + * for your custom component. + */ + exportCSVBtn?(onClick: (e: React.MouseEvent) => void): ReactElement; + /** + * It's available to custom select only toggle button by configuring showSelectedOnlyBtn in options props. + * showSelectedOnlyBtn only accept a function and a JSX returned value is necessary. + * This function will take two argument: onClick and showSelected. + * + * The default `ShowSelectedOnlyButton` component is also exported as a component, so that you can use it as + * the base for your custom component. + */ + showSelectedOnlyBtn?(onClick: (e: React.MouseEvent) => void, showSelected: boolean): ReactElement; + /** + * You can custom the whole search panel(right side) by searchPanel in options props. searchPanel only accept + * a function and a JSX returned value is necessary. This function will take one argument: props, that contains: + * `searchField`: the default search field component + * `clearBtn`: the default clear button component + * `defaultValue`: the default text for the search field + * `placeholder`: the default placeholder text for the search field + * `clearBtnClick`: the callback function to use when the clear search button is clicked + * `search`: the callback function for triggering the search, which takes the search text as an input. + */ + searchPanel?(props: SearchPanelProps): ReactElement; + /** + * You can custom the search input field only by searchField in options props. searchField only accept a + * function and a JSX returned value is necessary. + * + * The default `SearchField` component is also exported as a component, so that you can use it as the base for + * your custom component. + */ + searchField?(props: SearchFieldProps): ReactElement & SearchFieldInterface>; + /** + * You can custom the clear button for search field by giving clearSearchBtn in options props. + * clearSearchBtn only accept a function and a JSX returned value is necessary. + * + * The default `ClearSearchButton` component is also exported as a component, so that you can use it as the + * base for your own custom component. + */ + clearSearchBtn?(onClick: (e: React.MouseEvent) => void): ReactElement; + /** + * You can customize everything in the insert modal via options.insertModal and we give you the event + * callback, props and some informations: onModalClose, onSave, columns, validateState, ignoreEditable + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/custom-insert-modal.js + */ + insertModal?( + onModalClose: () => void, + onSave: (row: TRow) => void, + columns: ReadonlyArray>, + validateState: { [dataField: string]: string }, + ignoreEditable: boolean + ): ReactElement; + /** + * You can customize the body of the insert modal via options.insertModalBody and we give you the following + * arguments: columns, validateState {[fieldname]: errorMsg}, ignoreEditable + * + * Note: There is no exported Insert Modal Body component - if you are customising this, you need to create your + * own body component. That component needs to implement a `getFieldValue` method that returns the new row data. It + * will be called by react-bootstrap-table when the save button is clicked in the insert modal window. + */ + insertModalBody?( + columns: ReadonlyArray>, + validateState: { [dataField: string]: string }, + ignoreEditable: boolean + ): React.ReactElement & ModalBodyInterface>; + /** + * It's available to custom the header of insert modal by configuring options.insertModalHeader. It only accepts + * a function and a JSX returned value is necessary. This function will take two arguments: closeModal and save. + * `closeModal`: callback function to trigger closing the modal window. + * `save`: callback function to trigger saving the new row data. + * + * The default `InsertModalHeader` component is also exported as a component, so that you can use it as the base + * for your own custom component. + */ + insertModalHeader?(closeModal: () => void, save: () => void): ReactElement; + /** + * It's available to custom the footer of insert modal by configuring options.insertModalFooter. It only accepts + * a function and a JSX returned value is necessary. This function will take two arguments: closeModal and save. + * `closeModal`: callback function to trigger closing the modal window. + * `save`: callback function to trigger saving the new row data. + * + * The default `InsertModalFooter` component is also exported as a component, so that you can use it as the base + * for your own custom component. + */ + insertModalFooter?(closeModal: () => void, save: () => void): ReactElement; + /** + * Function to customize all of components for pagination, including the sizePerPage dropdown and the + * pagination list. + */ + paginationPanel?(props: PaginationPanelProps): ReactElement; + /** + * Function to customize the sizePerPage dropdown. + */ + sizePerPageDropDown?(props: SizePerPageFunctionProps): ReactElement; + /** + * Location for the pagination panel to be displayed. Options are 'top' (above the table), 'bottom' + * (below the table) and 'both' (above and below the table). + */ + paginationPosition?: PaginationPostion; + /** + * Callback when the value in a cell has been modified. It accepts a function that takes three arguments: + * `row`: row that is being edited. + * `fieldName`: column dataField for the cell being edited. + * `value`: new value for the cell. + * The function allows you to make further modifications to the cell value prior to it being saved. You need to + * return the final cell value to use. + */ + onCellEdit?(row: TRow, fieldName: K, value: TRow[K]): TRow[K]; + /** + * Custom message to show when the InsertModal save fails validation. + * Default message is 'Form validate errors, please checking!' + */ + insertFailIndicator?: string; + /** + * Function to verify that a key being generated in the Insert Modal is a valid key. + * If the key fails validation, return a string error message. + * If the key is ok, return void. + */ + isValidKey?(key: number | string): string | void; + /** + * Ability to disable the BOM in the exported CSV file. + * BOM = prepend BOM for UTF-8 XML and text/* types(including HTML) when saving the file. + */ + noAutoBOM?: boolean; + /** + * Custom class to use for the expanded content section of an expanded row. This can either be a string, or a + * function that returns a string and takes three arguments: row, rowIndex, isExpanding. + * `row`: the row expanding/collapsing. + * `rowIndex`: index number of the row. + * `isExpanding`: boolean flag specifying whether the field is expanding or collapsing. + */ + expandBodyClass?: string | ((row: TRow, rowIndex: number, isExpanding: boolean) => string); + /** + * Custom class to use for the row itself for an expanded row when it has been expanded. This can either be a + * string, or a function that returns a string and takes two arguments: row and rowIndex. + * `row`: the expanded row. + * `rowIndex`: index number of the row. + */ + expandParentClass?: string | ((row: TRow, rowIndex: number) => string); + /** + * Customize the field separator in a CSV export file. Default is ','. + */ + exportCSVSeparator?: string; + /** + * Set a function to be called when expanding or collapsing a row. This function takes two arguments: rowKey + * and isExpand. + * `rowKey`: dataField key for the row that is expanding or collapsing. + * `isExpand`: True if the row is expanding, false if it is collapsing. + */ + onExpand?(rowKey: number | string, isExpand: boolean): void; + /** + * Specify that only one row should be able to be expanded at the same time. + */ + onlyOneExpanding?: boolean; + /** + * Customize the tooltip text shown when hovering over the prePage button. + */ + prePageTitle?: string; + /** + * Customize the tooltip text shown when hovering over the nextPage button. + */ + nextPageTitle?: string; + /** + * Customize the tooltip text shown when hovering over the firstPage button. + */ + firstPageTitle?: string; + /** + * Customize the tooltip text shown when hovering over the lastPage button. + */ + lastPageTitle?: string; + /** + * Provide an array of expanded rows for the table. + */ + expanding?: Array; + /** + * Flag to indicate that the table should keep the SizePerPage dropdown open if the table rerenders without any + * user interaction. + */ + keepSizePerPageState?: boolean; + /** + * Flag to indicate that the table should always show next/previous buttons even when there is not next/previous + * page. + */ + alwaysShowAllBtns?: boolean; + /** + * Flag to indicate whether there should be buttons for First and Last page. + */ + withFirstAndLast?: boolean; } -interface FetchInfo { - dataTotalSize?: number; +/** + * Properties for data where only a portion of the data is loaded into the table at one time (i.e. remote data). + */ +export interface FetchInfo { + /** + * Total number of rows that match the current table filter/search properties. + */ + dataTotalSize: number; } -export interface BootstrapTable extends ComponentClass { +/** + * BootstrapTable class definition. + */ +export class BootstrapTable extends Component { /** - * Call this function to insert an new row to table. + * Call this function to insert a new row to table. */ handleAddRow(row: any): void; /** - * Call this function to insert an new row as first row on table. + * Call this function to insert a new row as the first row in the table. */ handleAddRowAtBegin(row: any): void; /** - * Call this function to drop rows in table. + * Call this function to drop/delete rows from the table. */ - handleDropRow(rowKeys: any[]): void; + handleDropRow(rowKeys: Array): void; /** * Call this function to do column filtering on table. + * @example: + * // Filtering passing an array of values + * this.refs.table.handleFilterData({ + * name: { type: 'ArrayFilter', value: ['Item name 3', 'Item name 4'] }, + * price: { type: 'ArrayFilter', value: [2100, 2104] } + * }); */ - handleFilterData(filter: any): void; + handleFilterData(filter: FilterData): void; /** * Call this function with search text for fully searching. */ @@ -486,104 +1118,181 @@ export interface BootstrapTable extends ComponentClass { /** * Call this function to sort table. */ - handleSort(order: SortOrder, field: string): void; + handleSort(order: SortOrder, dataField: string): void; /** * Call this function to get the page by a rowkey */ - getPageByRowKey(rowKey: string): any; + getPageByRowKey(rowKey: number | string): number; /** * Call this function to export table as csv. */ handleExportCSV(): void; /** - * Clean all the selection state on table. + * Reset the sort options to the defaults. Documented in examples but missing from main options list. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/clean-sorted-table.js + */ + cleanSort(): void; + /** + * Deselect all rows in the table. */ cleanSelected(): void; + /** + * Call reset to clean all the status on the table currently (sort, editing, filtering, search). + */ + reset(): void; } -interface BootstrapTable extends ComponentClass { } -declare const BootstrapTable: BootstrapTable; -export type DataAlignType = 'left' | 'center' | 'right' | 'start' | 'end'; export interface TableHeaderColumnProps extends Props { /** - * The field of data you want to show on column. + * The field of data you want to show on column. This is used throughout react-bootstrap-table as the column field + * name. */ dataField?: string; /** - * Use isKey to tell table which column is unique. This is same as keyField in - * Tips: You need choose one configuration to set key field: isKey or keyField in + * Use isKey to tell table which column is unique. This is same as the keyField in + * Tips: You need choose one configuration to set key field: isKey or the keyField in */ isKey?: boolean; /** - * Set the column width. ex: 150, it's means 150px + * Set the column width, including the units. e.g. '10%' or '150px' */ width?: string; /** - * Set align in column, value is left, center, right, start and end. + * Set the text alignment in the column, possible values are 'left', 'center', 'right', 'start' and 'end'. */ dataAlign?: DataAlignType; - /** * Alignment of text in the column header. + * Tip: If you don't set the headerAlign, it will default to the setting for dataAlign. */ headerAlign?: DataAlignType; /** - * True to enable table sorting. Default is disabled. + * True to enable table sorting on this column. Default is disabled. */ dataSort?: boolean; - /** - * Default search string. - */ - defaultSearch?: string; /** * Allow user to render a custom sort caret. You should give a function and should return a JSX. - * This function taking one arguments: order which present the sort order currently. + * This function takes two arguments: order and fieldName. + * `direction`: the current sort order. + * `fieldName`: the dataField name of the field currently being sorted. */ - caretRender?: Function; - /** - * Give an Object like following to able to customize your own editing component. - * This Object should contain these two property: - * getElement(REQUIRED): Accept a callback function and take two arguments: onUpdate and props. - * customEditorParameters: Another extra data for custom cell edit component. - */ - customEditor?: { getElement: (onUpdate: any, props: any) => ReactElement, customEditorParameters?: object }; + caretRender?(direction: SortOrder | null, fieldName: string): string | ReactElement; /** * To customize the column. This callback function should return a String or a React Component. - * In addition, this function taking two argument: cell and row. + * In addition, this function taking four argument: cell, row, formatExtraData, rowIdx. + * The formatExtraData will be the value which you assign it on */ - dataFormat?: (cell: any, row: any, formatExtraData?: any) => string | ReactElement; + dataFormat?(cell: any, row: any, formatExtraData: any, rowIndex: number): string | ReactElement; /** - * To to enable search or filter data on formatting. Default is false + * It's useful with dataFormat, you can give any data you want to be passed to the formatter. + */ + formatExtraData?: any; + /** + * Allow you to add your custom attributes on TD element. + * Example: tdAttr={ { 'data-attr': 'test' } } + */ + tdAttr?: CustomAttrs; + /** + * Allow you to add your custom style object on TD element. Accepts either a CSS Properties object, or + * a function that takes 4 arguments and returns a CSS Properties object. These arguments are: + * `cell`: The current cell value + * `row`: The current row data + * `rowIndex`: Index number for the current row data in the input data array. + * `columnIndex`: Index number for the current column that the cell is in. + */ + tdStyle?: CSSProperties | ((cell: any, row: any, rowIndex: number, columnIndex: number) => CSSProperties); + /** + * Allow you to add your custom style object on TH element. + */ + thStyle?: CSSProperties; + /** + * When true, the column will filter using the value returned by the column's formatter. + * When false (default), the column will filter using the pre-formatted value. */ filterFormatted?: boolean; /** - * True to hide column. + * Return the value you want to be filtered on that column. + * It's useful if your column data is an object. + * @example: (cell, row) => cell.fieldOne; + * @see: https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/search-format-table.js + */ + filterValue?(cell: any, row: any): any; + /** + * Customize the cell content when exporting to a CSV file. This function takes two argument: cell, row. + */ + csvFormat?(cell: any, row: any): string; + /** + * Customize the column header text for the column when exporting to a CSV file. + */ + csvHeader?: string; + /** + * It's usually used with csvFormat, and it's same as formatExtraData. + * You can give any additional data you want to be passed to the csvFormat function. + */ + csvFormatExtraData?: any; + /** + * Set to true to hide the column. Default is false. Often used to hide rowKey columns that are required to + * identify a row but that do not need to be visible. */ hidden?: boolean; /** - * True to hide from insert dialog + * Used to specify whether a column will be exported to csv. + * + * If true, the column will be included in the export. This is usually used with hidden columns, as those are not + * exported by default. + * + * If false, the column will be excluded from the csv export. + */ + export?: boolean; + /** + * Usually used with Options.expandBy. + * You can assign which columns will trigger a row expansion or not. + * If false, clicking on a row inside this column will not cause the row to expand. + */ + expandable?: boolean; + /** + * Set this to true to hide this column on insert modal. Default is false. + * + * This is often used together with autoValue for auto-generated columns like row keys. */ hiddenOnInsert?: boolean; /** - * True to hide the dropdown for sizePerPage. + * It only work for enabling insertRow and be assign on rowKey column. If true, the value of rowkey will be + * generated automatically after a row insertion. If a function given, you can customize the value by yourself and + * remember to return the value for the cell from the function. */ - hideSizePerPage?: boolean; + autovalue?: boolean | (() => any); /** * False to disable search functionality on column, default is true. */ searchable?: boolean; /** - * Give a customize function for data sorting. - * This function taking four arguments: a, b, order, sortField, extraData + * Show the title on each column in the data section of the table. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column/column-title-table.js */ - sortFunc?: (a: any, b: any, order: SortOrder, sortField: any, extraData: any) => number; + columnTitle?: boolean | string | ((cell: any, row: any, rowIndex: number, colIndex: number) => string); /** - * It's a extra data for custom sort function, if defined, this data will be pass as fifth argument in sortFunc. + * Show the title on each column in the header section of the table, default is true. + */ + headerTitle?: boolean; + /** + * If the children of TableHeaderColumn is a JSX or Object, we prefer to add this prop to describe this column with + * a pure text(String). It will be used on the placeholder or tips in the filter, search field or insert field etc. + */ + headerText?: string; + /** + * Give a custom callback function for data sorting. + * This function takes five arguments: a, b, order, sortField, extraData + * The extraData value is the data from the sortFuncExtraData. + */ + sortFunc?(a: object, b: object, order: SortOrder, sortField: keyof object, extraData: any): number; + /** + * Extra data for the custom sort function. If defined, this data will be passed as fifth argument in sortFunc. */ sortFuncExtraData?: any; /** * Add custom css class on table header column, this attribute only accept String or Function. - * If Function, it taking four arguments: cell, row, rowIndex, columnIndex. + * If Function, it takes four arguments: cell, row, rowIndex, columnIndex. * In addition, this function should return a String which is the class name you want to add on. */ className?: string | ((cell: any, row: any, rowIndex: number, columnIndex: number) => string); @@ -592,156 +1301,1334 @@ export interface TableHeaderColumnProps extends Props { * If Function, it taking four arguments: cell, row, rowIndex, columnIndex. * In addition, this function should return a String which is the class name you want to add on. */ - columnClassName?: String | ((cell: any, row: any, rowIndex: number, columnIndex: number) => string); + columnClassName?: string | ((cell: any, row: any, rowIndex: number, columnIndex: number) => string); /** - * Add True to set column editable, false is non-editable. If give Object, - * you can do more customization when editing cell. This object have following properties: - * @example - * { - * type: //edit type, avaiable value is textarea, select, checkbox - * validator: //give function for validation and taking only one "cell value" as argument. This function should return Bool. - * options:{ - * values: //values means data in select or checkbox.If checkbox, use ':'(colon) to separate value, ex: Y:N - * } - * } + * Add custom css class on editing cell, if assign a callback function, you are supposed to return a String for class name */ - editable?: boolean | Editable; + editColumnClassName?: string | ((cell: any, row: any) => string); /** - * It only work when you enable insertRow and be assign on rowKey column. - * If true, the row key will be generated automatically after a row insertion. + * Add custom css class for invalid editing cell, if assign a callback function, you are supposed to return a String for class name */ - autoValue?: boolean; + invalidEditColumnClassName?: string | ((cell: any, row: any) => string); + /** + * boolean: Add True to set column editable, false is non-editable. + * function: You have ability to control the editable level on cell instead of column level. For this + * callback function, you are supposed to be return a bool value to decide this cell editable or not + * This callback accepts four arguments: cell, row, rowIndex, columnIndex. + * object: @see Editable interface. + */ + editable?: boolean | Editable | ((cell: any, row: any, rowIndex: number, columnIndex: number) => boolean | string | EditValidatorObject); + /** + * Give an Object like following to able to customize your own editing component. + * This Object should contain these two property: + * getElement(REQUIRED): Accept a callback function and take two arguments: onUpdate and props. + * customEditorParameters: Additional data for custom cell edit component. + */ + customEditor?: CustomEditor; /** * To Enable a column filter within header column. - * This feature support a lots of filter type and condition. Please check example - * Following is the format for filter + * This feature support a lots of filter types and conditions. */ filter?: Filter; - - onSort?: Function; - /** - * Header for column in generated CSV file - */ - csvHeader?: string; - csvFormat?: Function; - columnTitle?: boolean; - sort?: SortOrder; - formatExtraData?: any; - - /** - * Row in the header on which this header column present. + * This is always used together with rowSpan and colSpan, to create multi-row/multi-column headers. + * Row is the header row on which this header column present. */ row?: number; - /** * Indicates how many rows this column takes. * Default: 1 */ rowSpan?: number; - /** * Indicates how many columns this column takes. * Default: 1 */ colSpan?: number; - /** - * Return the value you want to be filtered on that column. - * It's useful if your column data is an object. + * Specify the field type to use when exporting this column to CSV. Available types are 'number' and 'string'. + * Defaults to 'string'. */ - filterValue?: Function; - + csvFieldType?: CSVFieldType; /** - * Allow you to add your custom attributes on TD element. + * Set the column class name for the actively filtered column. Can be either a string, or a function that takes two + * parameters: order and dataField. + * `order`: current sort order for the column. + * `dataField`: current column's dataField. + * This allows you to specify a different className depending on whether the current dataField is being sorted 'asc' + * or 'desc'. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/sort-style-table.js#L36-L37 */ - tdAttr?: object; - + sortHeaderColumnClassName?: string | ((order: SortOrder, dataField: string) => string); /** - * Allow you to add your custom style object on TD element. + * Specify custom tdAttrs to use for a cell that is being edited within this column. */ - tdStyle?: object; - + editTdAttr?: CustomAttrs; /** - * Allow you to add your custom style object on TH element. + * Custom insert editor element. This is a function to generate a custom edit element to display in the InsertModal + * form. The function takes five arguments: column, attr, editorClass, ignoreEditable, defaultValue. + * `column`: column information given to the insert modal. + * `attr`: EditableAttrs from the TableHeader.editable object options. + * `editorClass`: className to apply to the editor component. + * `ignoreEditable`: boolean flag indicating whether editable fields should be ignored in the insert modal + * `defaultValue`: the default value to use for this cell. + * The function should return either a JSX element for the field, or false to default back to the standard edit + * element. */ - thStyle?: object; + customInsertEditor?: { + getElement( + column: InsertModalColumnDescription, + attr: EditableAttrs, + editorClass: string, + ignoreEditable: boolean, + defaultValue: any + ): ReactElement | boolean; + }; + /** + * Support specifying that the column should start sorting with the 'asc' option. + */ + defaultASC?: boolean; } -export interface Editable { - type?: string; // edit type, avaiable value is textarea, select, checkbox - /** - * Function for validation and taking only one "cell value" as argument. This function should return Bool. - */ - validator?: (cell: any) => boolean; - /** - * @example - * { - * values: //values means data in select or checkbox. If checkbox, use ':'(colon) to separate value, ex: Y:N - * } - */ - options?: any; +/** + * Editable Attributes. Poorly documented, but used when creating custom editor components. + */ +export interface EditableAttrs { /** - * Configuration for the textarea editable type + * Placeholder text to use for the cell editor field. + */ + placeholder?: string; + /** + * Function to pass a reference to the input editor field. + */ + ref?(ref: any): any; + /** + * Callback for onKeyDown. + */ + onKeyDown?(): void; + /** + * Callback for on cell blur. + */ + onBlur?(): void; +} + +/** + * Editable Select option values + */ +export type EditSelectOptionValue = + | Array<{ text: string; value: string; }> + | string[] + | number[]; + +/** + * Editable Checkbox option values. This should be a string with the true/false value separated by a colon. + * e.g. "Yes:No" + */ +export type EditCheckboxOptionValue = string; + +/** + * Object to use to customize the properties for an editable column. + */ +export interface Editable { + /** + * Edit field type, avaiable value is 'textarea', 'select', 'checkbox' and 'datetime' + */ + type?: EditCellType; + /** + * Class name to use for the editor component. + */ + className?: string; + /** + * Number of columns to display for a text area component. */ cols?: number; + /** + * Number of rows to display for a text area component. + */ rows?: number; + /** + * Used to specify a field that can be modified in the insert modal when adding a new row, but cannot be edited + * inside the table after the row has been inserted. + */ + readOnly?: boolean; + /** + * CSS Style to use for the editor component. + */ + style?: CSSProperties; + /** + * Validation function for the column. It takes the new "cell value" as argument. This function should return + * a boolean true/false for isValid, or an EditValidatorObject (so that an error message can be provided). + */ + validator?(cell: TRow[K], row: TRow): boolean | string | EditValidatorObject; + /** + * Data in a select or checkbox. If a checkbox, use a string with a ':'(colon) to separate the two values, ex: Y:N + * The callback function can be used to customize the select options based on other field values within the row. + * If the array is an array of objects, the fields 'text' can be used for the display text and 'value' to specify + * the option's value. + */ + options?: { + values: + | EditSelectOptionValue + | EditCheckboxOptionValue + | ((row: TRow) => EditCheckboxOptionValue | EditSelectOptionValue); + }; + /** + * Default value to show in the edit field in the Insert Modal for this column. + */ + defaultValue?: TRow[K]; + /** + * @deprecated Use placeholder inside the attrs field instead. + * Text to display as placeholder text in the editor component. + */ + placeholder?: string; + /** + * Additional attributes for the editor component. + */ + attrs?: EditableAttrs; } + export type SetFilterCallback = (targetValue: any) => boolean; export interface ApplyFilterParameter { callback: SetFilterCallback; } -export type FilterType = 'TextFilter' | 'RegexFilter' | 'SelectFilter' | 'NumberFilter' | 'DateFilter' | 'CustomFilter'; -export interface Filter { +/** + * Text filter type. + */ +export interface TextFilter { /** - * "TextFilter"||"SelectFilter"||"NumberFilter"||"DateFilter"||"RegexFilter"||"YOUR_CUSTOM_FILTER" + * Filter type must be 'TextFilter'. */ - type?: FilterType; + type: 'TextFilter'; /** - * Default value on filter. If type is NumberFilter or DateFilter, this value will like { number||date: xxx, comparator: '>' } - */ - defaultValue?: any; - /** - * Assign a millisecond for delay when trigger filtering, default is 500. + * Delay time in milliseconds after the last key press prior to applying the filter. Defaults to 500ms. */ delay?: number; /** - * Only work on TextFilter. Assign the placeholder text on text and regex filter + * Placeholder text to show in the filter. */ - placeholder?: string | RegExp; + placeholder?: string; /** - * Only work on NumberFilter. Accept an array which conatin the filter condition, like: ['<','>','='] + * Condition. Can be 'eq' (exactly equal) or 'like' (contains the given string). Defaults to 'like'. */ - numberComparators?: string[]; - - /** - * Options for the filter. - */ - options?: any; - - /** - * Comparison condition for the NumberFilter - */ - condition?: string; - - /** - * Get element which represent filter. - */ - getElement?: (filterHandler: (parameters?: ApplyFilterParameter) => void, filterParameters: any) => JSX.Element; - - /** - * Parameters for custom filter - */ - customFilterParameters?: any; + condition?: FilterCondition; + /** + * Default value for the text filter. Defaults to '' + */ + defaultValue?: string; + /** + * CSS Style to use for the select filter. + */ + style?: CSSProperties; } -export interface TableHeaderColumn extends ComponentClass { } -declare const TableHeaderColumn: TableHeaderColumn; - -declare class TableDataSet extends EventEmitter { - constructor(data: any); - setData(data: any): void; - clear(): void; - getData(): any; +export interface SelectFilterOptionsType { + [value: string]: string | number | boolean; + [value: number]: string | number | boolean; } + +/** + * Select filter type + */ +export interface SelectFilter { + /** + * Filter type must be 'SelectFilter' + */ + type: 'SelectFilter'; + /** + * Placeholder text to show in the filter. + */ + selectText?: string; + /** + * Options for the filter select. + */ + options: SelectFilterOptionsType; + /** + * Condition. Can be 'eq' (exactly equal) or 'like' (contains the given string). Defaults to 'like'. + */ + condition?: FilterCondition; + /** + * Default value for the select filter. + */ + defaultValue?: string | number | boolean; + /** + * CSS Style to use for the select filter. + */ + style?: CSSProperties; + /** + * Disable the empty option in the dropdown filter. + */ + withoutEmptyOption?: boolean; +} + +/** + * Regex filter type + */ +export interface RegexFilter { + /** + * Filter type must be 'RegexFilter' + */ + type: 'RegexFilter'; + /** + * Delay time in milliseconds after the last key press prior to applying the filter. Defaults to 500ms. + */ + delay?: number; + /** + * Placeholder text to show in the filter. + */ + placeholder?: string; + /** + * Default value + */ + defaultValue?: string; + /** + * CSS Style to use for the select filter. + */ + style?: CSSProperties; +} + +/** + * Number filter type + */ +export interface NumberFilter { + /** + * Filter type must be 'NumberFilter' + */ + type: 'NumberFilter'; + /** + * Delay time in milliseconds after the last key press prior to applying the filter. Defaults to 500ms. + */ + delay?: number; + /** + * Placeholder text to show in the filter. + */ + placeholder?: string; + /** + * Number filter comparators + */ + numberComparators?: FilterComparator[]; + /** + * Default value for the filter. + */ + defaultValue?: { + /** + * Number value. + */ + number: number; + /** + * Comparator value. + */ + comparator: FilterComparator; + }; + /** + * If this is a select number field, disable the empty option in the dropdown. + */ + withoutEmptyOption?: boolean; + /** + * Specify that the comparator field MUST have a comparator selected. + */ + withoutEmptyComparatorOption?: boolean; + /** + * Specify that the value field MUST have a number value specified. + */ + withoutEmptyNumberOption?: boolean; + /** + * List of number options that can be selected, if the number field is a select dropdown instead of a text edit. + */ + options?: number[]; + /** + * CSS Style to use for the select filter. + */ + style?: { + number: CSSProperties; + comparator: CSSProperties; + }; +} + +/** + * Date filter type + */ +export interface DateFilter { + /** + * Filter type must be 'DateFilter' + */ + type: 'DateFilter'; + /** + * Delay time in milliseconds after the last key press prior to applying the filter. Defaults to 500ms. + */ + delay?: number; + /** + * Date filter comparators + */ + dateComparators?: FilterComparator[]; + /** + * Default value for the filter. + */ + defaultValue?: { + /** + * Date value. String values will be automatically converted to dates. + */ + date: Date | string; + /** + * Comparator value. + */ + comparator: FilterComparator; + }; + /** + * CSS Style to use for the select filter. + */ + style?: { + date: CSSProperties; + comparator: CSSProperties; + }; +} + +/** + * Custom filter type. + */ +export interface CustomFilter { + /** + * Type must be 'CustomFilter' + */ + type: 'CustomFilter'; + /** + * Function to generate the filter component + */ + getElement( + filterHandler: (parameters?: ApplyFilterParameter) => void, + customFilterParameters: object + ): ReactElement; + /** + * Custom filter parameters to be passed to the generator function + */ + customFilterParameters: object; +} + +/** + * Collection of filter types. + */ +export type Filter = TextFilter | SelectFilter | RegexFilter | NumberFilter | DateFilter | CustomFilter; + +/** + * The "value" type for a number filter + */ +export interface NumberFilterValue { + number: number; + comparator: FilterComparator; +} + +/** + * The "value" type for a date filter. + */ +export interface DateFilterValue { + date: Date | string; + comparator: FilterComparator; +} + +/** + * Text Filter's data object. + */ +export interface TextFilterData { + type: 'TextFilter'; + value: string; +} + +/** + * Select Filter's data object. + */ +export interface SelectFilterData { + type: 'SelectFilter'; + value: string; +} + +/** + * Regex Filter's data object. + */ +export interface RegexFilterData { + type: 'RegexFilter'; + value: string; +} + +/** + * Number Filter's data object. + */ +export interface NumberFilterData { + type: 'NumberFilter'; + value: NumberFilterValue; +} + +/** + * Date Filter's data object. + */ +export interface DateFilterData { + type: 'DateFilter'; + value: DateFilterValue; +} + +/** + * Data object returned for an array filter. + */ +export interface ArrayFilterData { + type: 'ArrayFilter'; + value: string[] | number[]; +} + +/** + * Valid types for the "value" field inside a filter's data object. + */ +export type FilterValueData = string | number | string[] | number[] | DateFilterValue | NumberFilterValue; + +/** + * Combined types of filter data objects. + */ +export type FilterValue = + | TextFilterData + | SelectFilterData + | RegexFilterData + | NumberFilterData + | DateFilterData + | ArrayFilterData; + +/** + * Filter object that can be passed to BootstrapTableFilter.handleFilterData function. + */ +export interface FilterData { + [dataField: string]: FilterValue; +} + +/** + * TableHeaderColumn class definition. + */ +export class TableHeaderColumn extends Component { + /** + * Function to reset the filter on this column to the default values. + */ + cleanFiltered(): void; + /** + * Apply a filter value. + */ + applyFilter(value: FilterValueData): void; +} + +/** + * Customize the options for Keyboard Navigation. + */ +export interface KeyboardNavigation { + /** + * Return a style object which will be applied on the navigating cell. + */ + customStyle?: CSSProperties; + /** + * Set to false to disable click to navigate, usually user wants to click to select row instead of navigation. + */ + clickToNav?: boolean; + /** + * Return a style object which will be applied on the both of navigating and editing cell. + */ + customStyleOnEditCell?: CSSProperties; + /** + * When set to true, pressing ENTER will begin to edit the cell if cellEdit is also enabled. + */ + enterToEdit?: boolean; + /** + * When set to true, pressing ENTER will expand or collapse the current row. + */ + enterToExpand?: boolean; +} + +/** + * Input properties for the expandColumnComponent function when customising the expand indicator. + */ +export interface ExpandColumnComponentProps { + /** + * True if the current row is able to be expanded. + */ + isExpandableRow: boolean; + /** + * True if the current row is currently expanded. + */ + isExpanded: boolean; +} + +/** + * Customize the options for expand row feature. + */ +export interface ExpandColumnOptions { + /** + * Will enable an indicator column at first column if true. Default is false. + */ + expandColumnVisible?: boolean; + /** + * a callback function to customize the appearance of the indicator column. + */ + expandColumnComponent?(props: ExpandColumnComponentProps): string | ReactElement; + /** + * set the width of indicator column. + */ + columnWidth?: number | string; + /** + * If both an indicator column and a selection column are displaying, this specifies whether the indicator column + * should be shown first. Default is true, false will move the expand indicator column after selection column. + */ + expandColumnBeforeSelectColumn?: boolean; +} + +/** + * Properties provided in the callback to create a custom component for the selection column radio/checkboxes + */ +export interface CustomSelectProps { + /** + * What type of selection should be used? Values are 'radio' (single) or 'checkbox' (multiple). + */ + type: SelectRowMode; + /** + * True if the current row being drawn is selected. + */ + checked: boolean; + /** + * True if the current row being drawn is not permitted to be selected. + */ + disabled: boolean; + /** + * Callback that should be used when someone selects the current row. + * `event`: the current event target + * `rowIndex`: the index of the current row being toggled. + */ + onChange(event: any, rowIndex: string | number): void; + /** + * Index for the row currently being rendered. + * If the rowIndex is 'Header', it means this rendering is for header selection column. + */ + rowIndex: number | string; + /** + * The indeterminate flag is used to indicate that there are some rows selected, but it is neither all rows nor + * no rows. As far as the select all checkbox is concerned, it is neither true nor false. + */ + indeterminate: boolean; +} + +/** + * Details of the column settings, provided to the Options.onSearchChange callback function. + * The values for these settings come from the properties for a column. + * + * Note: the list of options is poorly documented. This list comes from double-checking the + * react-bootstrap-table source code to check what properties actually get passed to the + * onSearchChange callback function. + */ +export interface ColumnDescription { + /** + * Name of the column. + * Comes from TableHeader.dataField property. + */ + name: keyof TRow; + /** + * Column text alignment setting + * Comes from TableHeader.dataAlign property. + */ + align: DataAlignType; + /** + * Column sorting setting. If true, the column can be used to sort the data. + * Comes from TableHeader.dataSort property. + */ + sort: boolean; + /** + * Column data format function. + * Comes from TableHeader.dataFormat property. + */ + format(cell: any, row: TRow, formatExtraData: any, rowIndex: number): string | ReactElement; + /** + * The formatExtraData setting for the column. + * Comes from TableHeader.formatExtraData property. + */ + formatExtraData: any; + /** + * Whether data should be filtered based on the formatted value, or the raw data value. + * Comes from TableHeader.filterFormatted property. + */ + filterFormatted: boolean; + /** + * Filter function for the column. + * Comes from TableHeader.filterValue property. + */ + filterValue(cell: any, row: TRow): any; + /** + * Setting for whether the data in this column can be edited. + * Comes from TableHeader.editable property. + */ + editable: boolean | Editable | ((cell: any, row: TRow, rowIndex: number, columnIndex: number) => boolean | string | EditValidatorObject); + /** + * Custom editor settings to use when editing the data in this column. + * Comes from TableHeader.customEditor property. + */ + customEditor: CustomEditor; + /** + * Flag to indicate whether this column should be visible or not. + * Comes from TableHeader.hidden property. + */ + hidden: boolean; + /** + * Flag to indicate whether this column should be hidden on the insert modal. + * Comes from TableHeader.hiddenOnInsert property. + */ + hiddenOnInsert: boolean; + /** + * Flag to indicate whether the data in this column should be included in a search. + * Comes from TableHeader.searchable property. + */ + searchable: boolean; + /** + * Custom className setting for this column. + * Comes from TableHeader.columnClassName property. + */ + className: string | ((cell: any, row: TRow, rowIndex: number, columnIndex: number) => string); + /** + * Custom className setting for this column when a cell in the column is being edited. + * Comes from TableHeader.editColumnClassName property. + */ + editClassName: string | ((cell: any, row: TRow) => string); + /** + * Custom className setting for this column when a cell in the column contains invalid data. + * Comes from TableHeader.invalidEditColumnClassName property. + */ + invalidEditColumnClassName: string | ((cell: any, row: TRow) => string); + /** + * Custom title to display for this column. + * Comes from TableHeader.columnTitle property. + */ + columnTitle: boolean; + /** + * Width setting for this column. + * Comes from TableHeader.width property. + */ + width: string; + /** + * Custom header value/component/children to use for this column. + * Comes from TableHeader.headerText || TableHeader.children properties. + */ + text: string | number | boolean | ReactElement; + /** + * Custom sort function to use for this column. + * Comes from TableHeader.sortFunc property. + */ + sortFunc(a: TRow, b: TRow, order: SortOrder, sortField: keyof TRow, extraData: any): number; + /** + * Extra data to be provided to the search function for this column. + * Comes from TableHeader.sortFuncExtraData property. + */ + sortFuncExtraData: any; + /** + * Flag to indicate whether this column should be included in a CSV export. + * Comes from TableHeader.export property. + */ + export: boolean; + /** + * Flag to indicate whether this column is expandable. + * Comes from TableHeader.expandable property. + */ + expandable: boolean; + /** + * Custom attributes (e.g. {'data-attr': 'test'}) to be applied to cells in this column. + * Comes from TableHeader.tdAttr property. + */ + attrs: CustomAttrs; + /** + * Custom attributes (e.g. {'data-attr': 'test'}) to use for cells that are being edited in this column. + * Comes from TableHeader.editTdAttr property. + */ + editAttrs: CustomAttrs; + /** + * CSS style properties to use for cells in this column. + * Comes from TableHeader.tdStyle property. + */ + style: CSSProperties; +} + +/** + * Props provided to the Options.toolBar callback function for creating a custom toolbar. + */ +export interface ToolBarProps { + /** + * Rendered components to use in the toolbar. + */ + components: ButtonGroupProps & { + /** + * Search panel component. + */ + searchPanel: ReactElement; + /** + * Button group components. + */ + btnGroup: ReactElement; // button groups JSX + /** + * The individual search field. + */ + searchField: ReactElement; // search field JSX + /** + * The button to clear the search field. + */ + clearBtn: ReactElement; // clear search field JSX + }; + /** + * Event callbacks to use with a custom toolbar. + */ + event: { + /** + * Callback to activate the insert row modal window. + */ + openInsertModal(): void; + /** + * Callback to close the insert row modal window. + */ + closeInsertModal(): void; + /** + * Callback to delete selected row(s) from the table. + */ + dropRow(): void; + /** + * Callback to toggle between showing all rows and showing only selected rows. + */ + showOnlyToogle(): void; + /** + * Callback to export the table to a CSV file. + */ + exportCSV(): void; + /** + * Callback to apply a search. + */ + search(): void; + }; +} + +/** + * Left-hand side Button elements (used when customizing the toolbar). + */ +export interface ButtonGroupProps { + /** + * Export to CSV button. + */ + exportCSVBtn: ReactElement; + /** + * Insert button (to add a row). + */ + insertBtn: ReactElement; + /** + * Delete button. + */ + deleteBtn: ReactElement; + /** + * Toggle button to switch between showing all rows and showing selected rows only. + */ + showSelectedOnlyBtn: ReactElement; +} + +/** + * Properties that are given to the Options.searchPanel callback function. + */ +export interface SearchPanelProps { + /** + * Default search field component. + */ + searchField: ReactElement; + /** + * Default clear search field button component. + */ + clearBtn: ReactElement; + /** + * The default search text. + */ + defaultValue: string; + /** + * The placeholder text for the search field. + */ + placeholder: string; + /** + * A callback to trigger the clear search field event. + */ + clearBtnClick(): void; + /** + * A callback to trigger a search, takes the search text as an input. + */ + search(searchText: string): void; +} + +/** + * Properties passed as props to the Options.paginationPanel function when generating a custom pagination panel. + */ +export interface PaginationPanelProps { + /** + * Current page number + */ + currPage: number; + /** + * Current number of rows to show per page + */ + sizePerPage: number; + /** + * Choices for size per page dropdown component + */ + sizePerPageList: SizePerPageList; + /** + * Index number for the first page of data. + * Comes from Options.pageStartIndex. + */ + pageStartIndex: number; + /** + * Callback function to use to change page. + */ + changePage(pageNum: number): void; + /** + * Callback function to trigger the toggle on sizePerPage dropdown button + */ + toggleDropDown(): void; + /** + * Callback function to use to set a new size per page. + */ + changeSizePerPage(sizePerPage: number): void; + /** + * The basic components for the pagination panel, provided here so that you have the option to use some of them + * if you don't want to customize all of them. + */ + components: { + /** + * Text/element to display when displaying the total number of rows. + */ + totalText: string | ReactElement; + /** + * Default sizePerPageDropdown component. + */ + sizePerPageDropDown: SizePerPageDropDown; + /** + * The default list of page change buttons. + */ + pageList: HTMLUListElement; + }; +} + +/** + * Properties given to the Options.sizePerPageDropDown function used to generate a custom sizePerPage component to + * render in the pagination panel. + */ +export interface SizePerPageFunctionProps { + /** + * Flag to indicate that the sizePerPage dropdown should currently be 'open'. + */ + open: boolean; + /** + * Flag indicating that the sizePerPage dropdown should be hidden. + */ + hideSizePerPage: boolean; + /** + * Current size per page as a string value. + */ + currSizePerPage: string; + /** + * Array of the size per page options to display in the dropdown. + */ + sizePerPageList: SizePerPageList; + /** + * On-click toggle function callback to open/close the size per page dropdown list. + */ + toggleDropDown(): void; + /** + * Callback function to use to change the current size per page. + */ + changeSizePerPage(newSizePerPage: number): void; +} + +/** + * Custom Editor Props passed to the getElement function in the TableHeader.customEditor object. + */ +export interface CustomEditorProps extends EditableAttrs { + /** + * The row data for the cell being edited. + */ + row: TRow; + /** + * Default value for the editor cell. + */ + defaultValue: TRow[K]; + /** + * Contents of the customEditorParameters object. + */ + [parameterName: string]: any; +} + +/** + * Object to provide a custom editor component to use for a table column. + * @see: https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/cell-edit/custom-cell-edit-table.js + */ +export interface CustomEditor { + /** + * Required. Function to use to create the custom cell editor. Takes two parameters: + * `onUpdate`: callback function to call to update the value inside the cell. + * `props`: + */ + getElement(onUpdate: (updatedCell: TRow[K]) => void, props: CustomEditorProps): ReactElement; + /** + * Additional parameters to pass to the getElement function inside the props argument. + */ + customEditorParameters?: object; +} + +/** + * Validation object that can be returned from cell editing validation. + */ +export interface EditValidatorObject { + /** + * Boolean flag indicating whether the cell value is valid. + */ + isValid: boolean; + /** + * Notification object providing details on the validation result. + */ + notification: { + /** + * One of 'success' or 'error' + */ + type: EditValidatorType; + /** + * A text message explaining the validation result. + */ + msg: string; + /** + * A text title explaining the validation result. + */ + title: string; + }; +} + +/** + * Properties that can be passed to the InsertButton, DeleteButton, ExportCSVButton and ClearSearchButton + * components. + */ +export interface ButtonProps { + /** + * Label for the button + */ + btnText?: string; + /** + * Bootstrap css style class for the button, e.g. 'btn-warning' + */ + btnContextual?: string; + /** + * Custom class for the button + */ + className?: string; + /** + * Glyphicon glyph string for the button, e.g. 'glyphicon-edit' + */ + btnGlyphicon?: string; + /** + * Function to be called to activate the normal onClick functionality for this button. + */ + onClick?(e: React.MouseEvent): void; +} + +/** + * Properties that can be passed to the ShowSelectedOnlyButton component. + */ +export interface ShowSelectedButtonProps { + /** + * Label for when clicking the button will toggle the table back into "show all rows" mode. + */ + showAllText?: string; + /** + * Label for when clicking the button will toggle the table into "show only selected rows" mode. + */ + showOnlySelectText?: string; + /** + * Bootstrap css style class for the button, e.g. 'btn-warning' + */ + btnContextual?: string; + /** + * Custom class for the button + */ + className?: string; + /** + * Glyphicon glyph string for the button, e.g. 'glyphicon-edit' + */ + btnGlyphicon?: string; + /** + * Function to be called to activate the normal onClick functionality for this button. + */ + onClick?(e: React.MouseEvent): void; +} + +/** + * Properties that can be passed to the SearchField component. + */ +export interface SearchFieldProps { + /** + * Custom css class name + */ + className?: string; + /** + * Default value for the search field + */ + defaultValue?: string; + /** + * Placeholder text for the search field + */ + placeholder?: string; + /** + * callback funciton to call when a key is released + */ + onKeyUp?(e: React.KeyboardEvent): void; +} + +/** + * Interface that must be implemented for a custom search field component. + */ +export interface SearchFieldInterface { + /** + * getValue should return the current search text. + */ + getValue(): string; + /** + * setValue should update the current search text to the given value. + */ + setValue(search: string): void; +} + +/** + * Modal Column data passed to Options.insertModal and Options.insertModalBody. + */ +export interface InsertModalColumnDescription { + /** + * Flag to indicate that this is the key field for the column. It is only present if there is more than + * one column in the table. + * Comes from TableHeader.isKey field. + */ + isKey?: boolean; + /** + * Header text/element for the column. + * Comes from TableHeader.headerText or TableHeader.children. + */ + name: string | ReactElement; + /** + * Field name for the column data. + * Comes from TableHeader.dataField. + */ + field: keyof TRow; // children.props.dataField, + /** + * Flag to indicate whether this column is editable. + * Comes from TableHeader.editable. + */ + editable: boolean | Editable | ((cell: TRow[keyof TRow], row: TRow, rowIndex: number, columnIndex: number) => boolean | string | EditValidatorObject); + /** + * Custom element to use for the Insert field element. + * Comes from TableHeader.customInsertEditor. + */ + customInsertEditor( + column: InsertModalColumnDescription, + attr: EditableAttrs, + editorClass: string, + ignoreEditable: boolean, + defaultValue: TRow[keyof TRow] + ): ReactElement | boolean; + /** + * Flag to indicate whether this column should be hidden on the Insert Modal page. + * Comes from TableHeader.hiddenOnInsert. + */ + hiddenOnInsert: boolean; // children.props.hiddenOnInsert, + /** + * Flag to indicate whether the table should check that a key does not already exist. + * Comes from TableHeader.keyValidator. + */ + keyValidator: boolean; // children.props.keyValidator + /** + * Flag to indicate that the field should be auto-generated rather than edited. It is only present if there is more + * than one column in the table. + * Comes from TableHeader.autoValue. + */ + autoValue?: boolean; + /** + * Format function for the field. It is only present if there is more than one column in the table. Value is either + * 'false', meaning that there is no format function present, or a wrapper function that returns the formatted string + * content for the field using the TableHeader.dataFormat function to generate that string. + * + * Based on from TableHeader.dataFormat, but is applied as a wrapper function around that function. + */ + format?: boolean | ((cell: TRow[keyof TRow]) => string); +} + +/** + * Properties that can be passed to the InsertModalHeader component. + */ +export interface InsertModalHeaderProps { + /** + * Header class name. + */ + className?: string; + /** + * Title to display in the header. + */ + title?: string; + /** + * Callback function to call prior to closing the Insert Modal window. + */ + beforeClose?(e: SyntheticEvent): void; + /** + * Callback function to call to close the Insert Modal window. + */ + onModalClose?(closeModal: () => void): void; + /** + * Set to true to hide the close button. Default is false. + */ + hideClose?: boolean; + /** + * Bootstrap version. + */ + version?: BootstrapVersion; +} + +/** + * Properties that can be passed to the InsertModalFooter component. + */ +export interface InsertModalFooterProps { + /** + * Header class name. + */ + className?: string; + /** + * Text to display on the Save button + */ + saveBtnText?: string; + /** + * Text to display on the Close button + */ + closeBtnText?: string; + /** + * Bootstrap css class name for the close button, example: 'btn-warning' + */ + closeBtnContextual?: string; + /** + * Bootstrap css class name for the save button, example: 'btn-success' + */ + saveBtnContextual?: string; + /** + * Custom class name for the close button. + */ + closeBtnClass?: string; + /** + * Custom class name for the save button. + */ + saveBtnClass?: string; + /** + * Callback function to call prior to closing the Insert Modal window. + */ + beforeClose?(e: SyntheticEvent): void; + /** + * Callback function to call to close the Insert Modal window. + */ + onModalClose?(closeModal: () => void): void; + /** + * Callback function to be called prior to saving the new row. + */ + beforeSave?(e: SyntheticEvent): void; + /** + * Callback function to be called to save the new row. + */ + onSave?(save: () => void): void; +} + +/** + * Interface that must be implemented by a custom insert modal body component. + */ +export interface ModalBodyInterface { + /** + * The required getFieldValue method that must be implemented on a customized insert modal body that returns the + * new row data when the save button is clicked in the modal window. + */ + getFieldValue(): TRow; +} + +/** + * Properties that can be given to the SizePerPageDropDown component. + */ +export interface SizePerPageDropDownProps { + /** + * Custom class name to use for the component. + */ + className?: string; + /** + * Bootstrap css style class for the button, e.g. 'btn-warning' + */ + btnContextual?: string; + /** + * Whether the button menu should 'dropup' or 'dropdown'. + */ + variation?: DropDirection; + /** + * Callback function that should be triggered when the user clicks on the dropdown button. + */ + onClick?(toggleDropDown: () => void): void; + /** + * Current size per page + */ + currSizePerPage?: string; + /** + * Size Per Page options list + */ + options?: number[] | Array<{ text: string, value: number }>; + /** + * Flag to indicate that the dropdown is open + */ + open?: boolean; + /** + * Flag to indicate that the dropdown is currently hidden + */ + hidden?: boolean; +} + +/** + * Default InsertButton component. Can be used to create custom toolbars, etc. + */ +export class InsertButton extends Component {} + +/** + * Default DeleteButton component. Can be used to create custom toolbars, etc. + */ +export class DeleteButton extends Component {} + +/** + * Default ExportCSVButton component. Can be used to create custom toolbars, etc. + */ +export class ExportCSVButton extends Component {} + +/** + * Default ShowSelectedOnlyButton component for toggling between showing all rows or only + * selected rows. Can be used to create custom toolbars, etc. + */ +export class ShowSelectedOnlyButton extends Component {} + +/** + * Default SearchField component. Can be used to create custom toolbars, etc. + */ +export class SearchField extends Component implements SearchFieldInterface { + getValue(): string; + setValue(search: string): void; +} + +/** + * Default ClearSearchButton component. Can be used to create custom toolbars, etc. + */ +export class ClearSearchButton extends Component {} + +/** + * Default header component used for the Insert modal. Can be used to customize the + * insert row modal form. + */ +export class InsertModalHeader extends Component {} + +/** + * Default footer component used for the Insert modal. Can be used to customize the + * insert row modal form. + */ +export class InsertModalFooter extends Component {} + +/** + * Default size per page component used in the pagination row. Can be used to customize + * the size per page dropdown. + */ +export class SizePerPageDropDown extends Component {} diff --git a/types/react-bootstrap-table/react-bootstrap-table-tests.tsx b/types/react-bootstrap-table/react-bootstrap-table-tests.tsx index c8f25dfa56..edf2111b78 100644 --- a/types/react-bootstrap-table/react-bootstrap-table-tests.tsx +++ b/types/react-bootstrap-table/react-bootstrap-table-tests.tsx @@ -1,8 +1,49 @@ import * as React from 'react'; import { render } from 'react-dom'; -import { BootstrapTable, TableHeaderColumn, ApplyFilterParameter, Filter } from 'react-bootstrap-table'; +import { + ApplyFilterParameter, + BootstrapTable, + ButtonGroupProps, + CellEdit, + ColumnDescription, + CustomSelectProps, + DeleteButton, + EditableAttrs, + EditValidatorObject, + ExpandColumnComponentProps, + ExpandColumnOptions, + ExportCSVButton, + Filter, + FilterData, + FooterData, + InsertButton, + InsertModalColumnDescription, + InsertModalFooter, + InsertModalHeader, + ModalBodyInterface, + Options, + PaginationPanelProps, + SearchField, + SearchFieldInterface, + SearchFieldProps, + SearchPanelProps, + SelectRow, + ShowSelectedOnlyButton, + SizePerPageDropDown, + SortOrder, + TableHeaderColumn, + ToolBarProps +} from 'react-bootstrap-table'; -const products = [{ +interface Product { + id: number; + name: string; + price?: number; + quality?: number; + inStockStatus?: number; + sales?: number; +} +const products: Product[] = [{ id: 1, name: "Item name 1", price: 100 @@ -12,8 +53,40 @@ const products = [{ price: 100 }]; +type JobType = 'A' | 'B' | 'C' | 'D'; +interface Job { + id: number; + status: string; + name: string; + type: JobType; + active: 'Y' | 'N'; +} +const jobs = [ + { id: 1, status: '200', name: 'Item name 1', type: 'B', active: 'N' }, + { id: 2, status: '200', name: 'Item name 2', type: 'B', active: 'Y' } +]; +const jobTypes = ['A', 'B', 'C', 'D']; + +interface ExtendedJob { + id: number; + name: string; + type1: JobType; + type2: JobType; + active: 'Y' | 'N'; + datetime: Date; +} +const extendedJobs = [ + { id: 1, name: 'Item name 1', type1: 'A', type2: 'B', active: 'N', datetime: '2001-12-28T14:57:00' }, + { id: 2, name: 'Item name 2', type1: 'A', type2: 'B', active: 'Y', datetime: '2002-12-28T14:57:00' } +]; + +const inStockStatus = { + 1: 'yes', + 2: 'no' +}; + // It's a data format example. -function priceFormatter(cell: any, row: any) { +function priceFormatter(cell: number, row: Product) { return ' ' + cell; } @@ -32,7 +105,8 @@ const qualityType = { 2: 'unknown' }; -function enumFormatter(cell: any, row: any, enumObject: any) { +function enumFormatter(cell: any, row: any, enumObject: any, rowIndex: number) { + console.log(`The row index: ${rowIndex}`); return enumObject[cell]; } @@ -91,7 +165,7 @@ class RemoteProps extends React.Component { return remoteObj; }} options={{ - onCellEdit: (row: any, fieldName: string, value: any) => { console.info(row); } + onCellEdit: (row: any, fieldName: string, value: any) => { console.info(row); return value; } }} > Product ID @@ -145,27 +219,20 @@ const thStyleExample = Product Price ; -// Adopted from https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-header-span/column-header-span-complex.js -export default class ColumnHeaderSpanComplex extends React.Component { +/** + * Adopted from https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-header-span/column-header-span-complex.js + */ +class ColumnHeaderSpanComplex extends React.Component { render() { - const selectRow = { - mode: 'checkbox', - bgColor: 'rgb(238, 193, 213)' - }; - - const cellEdit = { - mode: 'click', - blurToSave: true - }; + const options: Options = { exportCSVSeparator: '##' }; return ( - + ID Product name price Coupon - In stock + In stock Customer name order @@ -173,3 +240,1297 @@ export default class ColumnHeaderSpanComplex extends React.Component { ); } } + +/** + * Pagination options + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/pagination/custom-pagination-table.js + */ +class PaginationTable extends React.Component { + sizePerPageListChange = (sizePerPage: number) => { + alert(`sizePerPage: ${sizePerPage}`); + } + + onPageChange = (page: number, sizePerPage: number) => { + alert(`page: ${page}, sizePerPage: ${sizePerPage}`); + } + + renderShowsTotal = (start: number, to: number, total: number) => { + return ( +

      + From {start} to {to}, totals is {total}  (its a customize text) +

      + ); + } + + render() { + const options: Options = { + onPageChange: this.onPageChange, + onSizePerPageList: this.sizePerPageListChange, + page: 2, // which page you want to show as default + sizePerPageList: [{ + text: '5', value: 5 + }, { + text: '10', value: 10 + }, { + text: 'All', value: products.length + }], // you can change the dropdown list for size per page + sizePerPage: 5, // which size per page you want to locate as default + pageStartIndex: 0, // where to start counting the pages + paginationSize: 3, // the pagination bar size. + prePage: 'Prev', // Previous page button text + nextPage: 'Next', // Next page button text + firstPage: 'First', // First page button text + lastPage: 'Last', // Last page button text + prePageTitle: 'Go to previous', // Previous page button title + nextPageTitle: 'Go to next', // Next page button title + firstPageTitle: 'Go to first', // First page button title + lastPageTitle: 'Go to Last', // Last page button title + paginationShowsTotal: this.renderShowsTotal, // Accept bool or function + paginationPosition: 'top', // default is bottom, top and both is all available + keepSizePerPageState: true, // default is false, enable will keep sizePerPage dropdown state(open/clode) when external rerender happened + hideSizePerPage: true, // You can hide the dropdown for sizePerPage + alwaysShowAllBtns: true, // Always show next and previous button + withFirstAndLast: false, // Hide the going to First and Last page button + hidePageListOnlyOnePage: true // Hide the page list if only one page. + }; + + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Adopted from https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/cell-edit/blur-to-escape-table.js + */ +class BlurToEscapeTable extends React.Component { + render() { + const cellEditProp: CellEdit = { + mode: 'click', + blurToEscape: true + }; + + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Cell classnames, row saving hooks. + * @see https://githum.com/AllenFang/react-bootstrap-table/blob/master/examples/js/cell-edit/cell-edit-classname.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/cell-edit/cell-edit-hook-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/insert-row-table.js + */ +class EditCellClassNameTable extends React.Component { + jobNameValidator = (value: string) => { + const response: EditValidatorObject = { isValid: true, notification: { type: 'success', msg: '', title: '' } }; + if (!value) { + response.isValid = false; + response.notification.type = 'error'; + response.notification.msg = 'Value must be inserted'; + response.notification.title = 'Requested Value'; + } else if (value.length < 10) { + response.isValid = false; + response.notification.type = 'error'; + response.notification.msg = 'Value must have 10+ characters'; + response.notification.title = 'Invalid Value'; + } + return response; + } + + jobStatusValidator = (value: string) => { + const nan = isNaN(parseInt(value, 10)); + if (nan) { + return 'Job Status must be a integer!'; + } + return true; + } + + invalidJobStatus = (cell: string, row: Job) => { + console.log(`${cell} at row id: ${row.id} fails on editing`); + return 'invalid-jobstatus-class'; + } + + editingJobStatus = (cell: string, row: Job) => { + console.log(`${cell} at row id: ${row.id} in current editing`); + return 'editing-jobstatus-class'; + } + + onBeforeSaveCellAsync = (row: Job, cellName: K, cellValue: Job[K], done: (ok: boolean) => void): boolean | 1 => { + setTimeout(() => { + done(false); // it's not ok to save :( + }, 3000); + return 1; // return 1 === async operation. + } + + onAfterSaveCell(row: Job, cellName: string, cellValue: any) { + alert(`Save cell ${cellName} with value ${cellValue}`); + let rowStr = ''; + for (const prop in row) { + rowStr += `${prop}: ${row[prop as keyof Job]}\n`; + } + alert('The whole row :\n' + rowStr); + } + + onAfterInsertRow = (row: any) => { + let newRowStr = ''; + + for (const prop in row) { + newRowStr += `${prop}: ${row[prop]} \n`; + } + alert('The new row is:\n ' + newRowStr); + } + + render() { + const cellEditProp: CellEdit = { + mode: 'dbclick', + blurToSave: true, + beforeSaveCell: this.onBeforeSaveCellAsync, + afterSaveCell: this.onAfterSaveCell + }; + const options: Options = { + afterInsertRow: this.onAfterInsertRow // A hook for after insert rows + }; + + return ( + + Job ID + Job Status + Job Name + Job Type + Active + + ); + } +} + +/** + * Multiple field sorting, filtering, searching and clearing + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/filter-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/multi-search-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/search-clear-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/strict-multi-search-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-search.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/custom-caret-sort-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/custom-sort-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/sort-style-table.js + */ +class MultiSortAndFiltering extends React.Component { + tableRef: BootstrapTable | null; + idRef: TableHeaderColumn | null; + state = { data: products }; + + onSortChange = (name: string, order: SortOrder) => { + console.log(`Next sort = ${name}:${order}`); + } + + cleanSort = () => { this.tableRef.cleanSort(); }; + + cleanSelected = () => { this.tableRef.cleanSelected(); }; + + onFilterChange = (filter: FilterData) => { + Object.keys(filter).forEach((column) => { + console.log(`Filtering ${column}: ${JSON.stringify(filter[column])}`); + }); + } + + cleanFilters = () => { this.idRef.cleanFiltered(); }; + + afterColumnFilter = (filterConds: ReadonlyArray, result: ReadonlyArray) => { + console.log('Filter Conditions: '); + filterConds.forEach((filterCond: FilterData) => { + Object.keys(filterCond).forEach((fieldName: string) => + console.log(`Filter column = ${fieldName}, Filter value = ${filterCond[fieldName]}`)); + }); + console.log('Result is:'); + for (const resultItem of result) { + console.log(`Product: ${resultItem.id}, ${resultItem.name}, ${resultItem.price}`); + } + } + + onSearchChange = (searchText: string, colInfos: ReadonlyArray>, multiColumnSearch: boolean) => { + this.setState({ data: products.filter((product) => product.name = searchText) }); + } + + afterSearch = (searchText: string, result: ReadonlyArray) => { + console.log(`Your search text is ${searchText}`); + console.log('Result is:'); + for (const resultItem of result) { + console.log(`Product: ${resultItem.id}, ${resultItem.name}, ${resultItem.price}`); + } + } + + getNameCaret = (direction: SortOrder | null, fieldName: string) => + (direction === 'asc') + ? ( up) + : (direction === 'desc') + ? ( down) + : ( up/down) + + revertSortFunc = (a: Product, b: Product, order: SortOrder) => + (order === 'desc') ? a.price - b.price : b.price - a.price + + customSortStyle = (order: SortOrder, dataField: string) => + (order === 'desc') ? 'sort-desc' : 'sort-asc' + + render() { + const options: Options = { + onSortChange: this.onSortChange, + onFilterChange: this.onFilterChange, + noDataText: 'This is custom text for empty data', + withoutNoDataText: false, + afterColumnFilter: this.afterColumnFilter, + onSearchChange: this.onSearchChange, + afterSearch: this.afterSearch, + clearSearch: true, + sortIndicator: true + }; + return ( +
      + + + Product ID + Product Name + =', '<=', '='] }}>Product Price + +
      + ); + } +} + +/** + * Sort with extra data. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/sort/custom-sort-with-extra-data-table.js + */ +class CustomSortWithExtraDataTable extends React.Component { + sortByName = (a: any, b: any, order: SortOrder, field: string, enumObject: any) => { + if (order === 'desc') { + if (enumObject[a[field]] > enumObject[b[field]]) { + return -1; + } else if (enumObject[a[field]] < enumObject[b[field]]) { + return 1; + } + return 0; + } + if (enumObject[a[field]] < enumObject[b[field]]) { + return -1; + } else if (enumObject[a[field]] > enumObject[b[field]]) { + return 1; + } + return 0; + } + + render() { + return ( + + Product ID + Product Name + + Product Quality + + ); + } +} + +/** + * Render custom pagination with provided SizePerPageDropDown component. + */ +class CustomPagination extends React.Component { + renderPagination = (props: PaginationPanelProps) => ( +
      + +
      + + + +
      +
      + ) + + render() { + const options: Options = { + paginationPanel: this.renderPagination + }; + + return ( + + + + + + ); + } +} + +/** + * Customize the entire insert modal. + * Adapted from https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/custom-insert-modal.js + */ +class CustomModal extends React.Component { + handleSaveBtnClick = (columns: ReadonlyArray>, onSave: (row: any) => void) => { + const newRow: {[field: string]: string} = {}; + columns.forEach((column, i) => { + newRow[column.field] = (this.refs[column.field] as HTMLInputElement).value; + }, this); + onSave(newRow); + } + + createCustomModal = ( + onModalClose: () => void, + onSave: (row: any) => void, + columns: ReadonlyArray>, + validateState: { [dataField: string]: string }, + ignoreEditable: boolean + ) => ( +
      +

      Custom Insert Modal

      +
      + { + columns.map((column, i) => { + const { + editable, + format, + field, + name, + hiddenOnInsert + } = column; + + if (hiddenOnInsert) { + return null; + } + const error = validateState[field] ? + ({validateState[field]}) : + null; + return ( +
      + + + {error} +
      + ); + }) + } +
      +
      + + +
      +
      + ) + + render() { + const options: Options = { + insertModal: this.createCustomModal + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Custom Insert Modal Fields, both as a custom component and as custom fields. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/custom-insert-modal-field.js + */ +class SalesRadioField extends React.Component<{editorClass: string, ignoreEditable: boolean}> { + yes: HTMLInputElement | null; + no: HTMLInputElement | null; + + getFieldValue = () => { + return this.yes.checked ? 'Yes' : 'No'; + } + + render() { + return ( +
      + + +
      + ); + } +} +class CustomInsertModalFieldTable extends React.Component { + customKeyField = ( + column: InsertModalColumnDescription, + attr: EditableAttrs, + editorClass: string, + ignoreEditable: boolean + ) => { + const seqId = products.length; + return ( + + ); + } + + customNameField = ( + column: InsertModalColumnDescription, + attr: EditableAttrs, + editorClass: string, + ignoreEditable: boolean, + defaultValue: any) => { + const fruits = ['banana', 'apple', 'orange', 'tomato', 'strawberries']; + return ( + + ); + } + + customSaleField = ( + column: InsertModalColumnDescription, + attr: EditableAttrs, + editorClass: string, + ignoreEditable: boolean, + defaultValue: any) => { + return ( + + ); + } + + render() { + return ( + + Product ID + Product Name + On Sales? + Product Price + + ); + } +} + +/** + * Custom modal header, body & footer. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/default-custom-insert-modal-header.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/custom-insert-modal-body.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-modal/default-custom-insert-modal-footer.js + */ +interface MyCustomBodyProps { + columns: ReadonlyArray>; + validateState: { [dataField: string]: string }; + ignoreEditable: boolean; +} +class MyCustomBody extends React.Component implements ModalBodyInterface { + getFieldValue() { + const newRow: Partial = {}; + this.props.columns.forEach((column, i) => { + newRow[column.field] = (this.refs[column.field] as HTMLInputElement).value; + }, this); + return newRow as Product; + } + + render() { + const { columns, validateState } = this.props; + return ( +
      +

      Custom body

      +
      + { + this.props.columns.map((column, i) => { + const { + editable, + format, + field, + name, + hiddenOnInsert + } = column; + + if (hiddenOnInsert) { + return null; + } + const error = validateState[field] ? + ({validateState[field]}) : + null; + return ( +
      + + + {error} +
      + ); + }) + } +
      +
      + ); + } +} +class DefaultCustomInsertModalHeaderFooterTable extends React.Component { + createCustomModalFooter = (closeModal: () => void, save: () => void) => { + return ( + {}} + beforeSave={(e) => {}} + onModalClose={closeModal} + onSave={save} /> + ); + } + + createCustomModalHeader = (closeModal: () => void, save: () => void) => { + return ( + { }} + onModalClose={closeModal} + hideClose={true} /> + ); + } + + createCustomModalBody = ( + columns: ReadonlyArray>, + validateState: { [dataField: string]: string }, + ignoreEditable: boolean + ) => ( + + ) + + render() { + const options: Options = { + insertModalFooter: this.createCustomModalFooter, + insertModalHeader: this.createCustomModalHeader, + insertModalBody: this.createCustomModalBody + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Custom Toolbar, including Search Panel & Buttons, and custom delete confirmation. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/toolbar/custom-button-group.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/toolbar/custom-toolbar-1.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/search/default-custom-search-field.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/search/custom-search-panel-1.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/search/fully-custom-search-field.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/insert-button/default-custom-insert-button.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/delete-button/default-custom-delete-button.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/custom/csv-button/default-custom-csv-button.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/manipulation/del-row-custom-confirm.js + */ +class MySearchField extends React.Component implements SearchFieldInterface { + field: SearchField | null; + + getValue() { + return this.field.getValue(); + } + + setValue(search: string) { + this.field.setValue(search); + } + + render() { + const { ...rest} = this.props; + return ( + { this.field = node; }} + /> + ); + } +} +class CustomButtonGroup extends React.Component { + createInsertButton = (onClick: (e: React.MouseEvent<{}>) => void) => ( + + ) + + createDeleteButton = (onClick: (e: React.MouseEvent<{}>) => void) => ( + + ) + + createExportCSVButton = (onClick: (e: React.MouseEvent<{}>) => void) => ( + + ) + + createShowSelectedOnlyButton = (onClick: (e: React.MouseEvent<{}>) => void, showSelected: boolean) => ( + + ) + + createCustomButtonGroup = (props: ButtonGroupProps) => ( +
      + {props.showSelectedOnlyBtn} + {props.exportCSVBtn} + {props.insertBtn} + {props.deleteBtn} + +
      + ) + + createCustomSearchField = (props: SearchFieldProps) => ( + + ) + + createCustomClearSearch = (onClick: (e: React.MouseEvent<{}>) => void) => ( + + ) + + createCustomSearchPanel = (props: SearchPanelProps) => ( +
      +
      + + {props.clearBtn} + +
      + {props.searchField} +
      + ) + + createCustomToolBar = (props: ToolBarProps) => { + return ( +
      + {props.components.btnGroup} +
      + {props.components.searchPanel} +
      +
      + ); + } + + customConfirm = (next: () => void, dropRowKeys: ReadonlyArray) => { + const dropRowKeysStr = dropRowKeys.join(','); + if (confirm(`(It's a custom confirm)Are you sure you want to delete ${dropRowKeysStr}?`)) { + next(); + } + } + + render() { + const selectRow: SelectRow = { + mode: 'checkbox', + showOnlySelected: true + }; + const options: Options = { + insertBtn: this.createInsertButton, + deleteBtn: this.createDeleteButton, + exportCSVBtn: this.createExportCSVButton, + showSelectedOnlyBtn: this.createShowSelectedOnlyButton, + btnGroup: this.createCustomButtonGroup, + clearSearch: true, + clearSearchBtn: this.createCustomClearSearch, + searchField: this.createCustomSearchField, + searchPanel: this.createCustomSearchPanel, + toolBar: this.createCustomToolBar, + searchDelayTime: 3000, + handleConfirmDeleteRow: this.customConfirm + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Expanding Rows & Selection + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/expand-row-by-column.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/expand-row-with-selection.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/custom-expand-indicator.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/custom-expand-class.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/auto-collapse.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/expandRow/manage-expanding.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/all-select.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/custom-multi-select-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/default-select-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/select-bgcolor-dynamic-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/select-filter-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/select-hook-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/selection/select-row-class-table.js + */ +class ExpandRowExample extends React.Component<{}, {expanding: number[]}> { + isExpandableRow = (row: any) => row.id === 2; + + expandComponent = (row: any) => ( +
      You expanded the row.
      + ) + + expandColumnComponent = ({ isExpandableRow, isExpanded }: ExpandColumnComponentProps) => { + const content = isExpandableRow + ? (isExpanded ? '(-)' : '(+)') + : ' '; + return ( +
      {content}
      + ); + } + + handleExpand = (rowKey: number, isExpand: boolean) => { + if (isExpand) { + this.setState({ expanding: [...this.state.expanding] }); + } else { + this.setState({ expanding: [...this.state.expanding.filter(id => id !== rowKey)] }); + } + } + + onSelectAll = (isSelected: boolean) => (isSelected) ? products.map(row => row.id) : []; + + onSelect = (row: Product, isSelected: boolean, e: React.MouseEvent, rowIndex: number) => { + const rowStr = `id: "${row.id}", name: ${row.name}, price: ${row.price}`; + console.log(e); + alert(`Selected: ${isSelected}, rowIndex: ${rowIndex}, row: ${rowStr}`); + } + + customMultiSelect = (props: CustomSelectProps) => ( +
      + props.onChange(e, props.rowIndex)} + ref={input => { + if (input) { + input.indeterminate = props.indeterminate; + } + }} /> + +
      + ) + + selectedRowClass = (row: Product, isSelect: boolean) => + (isSelect) + ? ((row.id >= 3) ? 'bigger-than-three-select-row' : 'less-than-three-select-row') + : '' + + render() { + const options: Options = { + expandRowBgColor: 'rgb(242, 255, 163)', + expandBy: 'column', + onlyOneExpanding: true, + expanding: this.state.expanding, + onExpand: this.handleExpand, + expandParentClass: 'custom-expand-parent', + expandBodyClass: (row, rowIndex, isExpanding) => { + return (!isExpanding) + ? 'current-is-hidden' + : (rowIndex > 1) + ? 'custom-expand-body-1' + : 'custom-expand-body-0'; + } + }; + const selectRow: SelectRow = { + mode: 'checkbox', + bgColor: (row: Product, isSelect: boolean) => + (isSelect) + ? ((row.id < 2) ? 'blue' : ((row.id < 4) ? 'red' : 'yellow')) + : null, + clickToSelect: true, // click to select, default is false + clickToExpand: true, // click to expand row, default is false + onSelect: this.onSelect, + onSelectAll: this.onSelectAll, + customComponent: this.customMultiSelect, + hideSelectColumn: false, + selected: [0, 2], + showOnlySelected: true, + onlyUnselectVisible: true, + className: this.selectedRowClass, + columnWidth: '60px', + unselectable: [1, 3] + }; + const expandColumnOptions: ExpandColumnOptions = { + expandColumnVisible: true, + expandColumnBeforeSelectColumn: false, + expandColumnComponent: this.expandColumnComponent, + columnWidth: 50 + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Table mouse enter/leave events + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/others/mouse-event-table.js + */ +class MouseEventTable extends React.Component { + render() { + const options: Options = { + onMouseLeave: () => { console.log('mouse left table'); }, + onMouseEnter: () => { console.log('mouse entered table'); }, + onRowMouseOut: (row: any, e: React.MouseEvent<{}>) => { + console.log(e); + console.log('mouse left row ' + row.id); + }, + onRowMouseOver: (row: any, e: React.MouseEvent<{}>) => { + console.log(e); + console.log('mouse entered row ' + row.id); + } + }; + + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Hidden on insert modal with async row error callback & read-only field + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/hide-on-insert-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/insert-error-handle-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/validator-table-read-only.js + */ +class HideOnInsertTable extends React.Component { + handleAddRowWithASyncError = (row: any, colInfo: ReadonlyArray>, errorCallback: (msg: string) => void) => { + setTimeout(() => { + errorCallback('Sorry, There\'s some error happend'); + }, 5000); + return false; + } + render() { + const options: Options = { + onAddRow: this.handleAddRowWithASyncError + }; + return ( + + Job ID + Job Name + Job Type + Active + + ); + } +} + +/** + * Edit field types + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/edit-type-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/insert-default-value-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/advance/insert-error-handle-table.js + */ +class EditTypeTable extends React.Component { + formatType = (cell: string) => `TYPE_${cell}`; + + jobTypes = (row: ExtendedJob) => (row.id > 2) ? ['A', 'B'] : ['B', 'C', 'D', 'E']; + + handleAddRowWithSyncError = () => { + return 'Sorry, There\'s some error happend'; + } + + render() { + const attrs = { + rows: 10, + onKeyDown: () => { console.log('keydown event trigger'); } + }; + const cellEditProp: CellEdit = { + mode: 'click', + blurToSave: true + }; + const options: Options = { + onAddRow: this.handleAddRowWithSyncError + }; + return ( + + Job ID + Job Name + Job Type1 + Job Type2 + Active + Date Time + + ); + } +} + +/** + * React component format for column. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-format/react-column-format-table.js + */ +class ActiveFormatter extends React.Component<{ active: boolean }> { + render() { + return ( + + ); + } +} + +export default class ReactColumnFormatTable extends React.Component { + activeFormatter = (cell: boolean, row: ExtendedJob) => (); + render() { + return ( + + + Job Name + Active + + ); + } +} + +/** + * Format Extra Data + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-format/extra-data-column-format-table.js + */ +class ExtraDataColumnFormatTable extends React.Component { + enumFormatter = (cell: number, row: Product, enumObject: {[id: number]: string}) => enumObject[cell]; + render() { + return ( + + Product ID + Product Name + Product Quality + Product Stock Status + + ); + } +} + +/** + * Column titles + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column/column-title-table.js + */ +class ColumnAlignTable extends React.Component { + customTitle = (cell: number, row: any, rowIndex: number, colIndex: number) => `${row.name} for ${cell}`; + + render() { + const options: Options = { + exportCSVText: 'my_export', + insertText: 'my_insert', + deleteText: 'my_delete', + saveText: 'my_save', + closeText: 'my_close' + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Table Footer + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/footer/footer-table.js + */ +class FooterTable extends React.Component { + render() { + const footerData: FooterData[][] = [ + [ + { label: 'Total', columnIndex: 0 }, + { + label: 'Total value', + columnIndex: 2, + align: 'right', + formatter: (tableData: Array<{price: number}>) => { + let label = 0; + for (let i = 0, tableDataLen = tableData.length; i < tableDataLen; i++) { + label += tableData[i].price; + } + return ( + {label} + ); + } + } + ] + ]; + + return ( +
      + + Product ID + Product Name + Product Price + +
      + ); + } +} + +/** + * Keyboard navigation + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/keyboard-nav/custom-style-nav-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/keyboard-nav/custom-style-nav-with-cell-edit-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/keyboard-nav/disable-click-to-nav-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/keyboard-nav/enter-to-edit-with-nav-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/keyboard-nav/nav-with-expand-table.js + */ +class CustomStyleNavTable extends React.Component { + customStyle = (cell: any, row: any) => { + return { + backgroundColor: 'red' + }; + } + + render() { + const cellEdit: CellEdit = { + mode: 'click', + blurToSave: true + }; + const keyBoardNav = { + customStyleOnEditCell: this.customStyle, + customStyle: this.customStyle, + clickToNav: false, + enterToEdit: true, + enterToExpand: false + }; + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Table body styles + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/inline-style-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/table-class-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/td-class-string-table.js + */ +class TrClassStringTable extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Table styles set by functions. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/td-class-function-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/tr-class-function-table.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/style/tr-style-table.js + */ +class TrClassFunctionTable extends React.Component { + headerColumnClassNameFormat = () => 'th-string-example'; + + columnClassNameFormat = (fieldValue: string | number, row: Product, rowIdx: number, colIdx: number) => + rowIdx % 2 === 0 ? 'td-column-function-even-example' : 'td-column-function-odd-example' + + trClassFormat = (rowData: ReadonlyArray, rIndex: number) => + rIndex % 3 === 0 ? 'tr-function-example' : '' + + trStyle = (row: Product, rowIndex: number) => ({ backgroundColor: '#FFFAFA' }); + + render() { + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +/** + * Filter types. + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/all-filters.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/date-filter-programmatically.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/number-filter-programmatically.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/regex-filter-programmatically.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/select-filter-programmatically.js + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/text-filter-programmatically.js + */ +class AllFilters extends React.Component { + name1: TableHeaderColumn | null; + name2: TableHeaderColumn | null; + quality: TableHeaderColumn | null; + price: TableHeaderColumn | null; + satisfaction: TableHeaderColumn | null; + inStockDate: TableHeaderColumn | null; + + handlerClickCleanFiltered = () => { + this.name1.cleanFiltered(); + this.name2.cleanFiltered(); + this.quality.cleanFiltered(); + this.price.cleanFiltered(); + this.satisfaction.cleanFiltered(); + this.inStockDate.cleanFiltered(); + } + + applyFiltersProgramatically = () => { + this.name1.applyFilter('Item 1'); + this.name2.applyFilter('[name]'); + this.quality.applyFilter(1); + this.price.applyFilter({ + number: 10.5, + comparator: '<=' + }); + this.satisfaction.applyFilter({ + number: 2, + comparator: '>' + }); + this.inStockDate.applyFilter({ + date: new Date(2015, 0, 1), + comparator: '=' + }); + } + + dateFormatter = (cell: Date, row: any) => { + if (typeof cell !== 'object') { + cell = new Date(cell); + } + + return `${('0' + cell.getDate()).slice(-2)}/${('0' + (cell.getMonth() + 1)).slice(-2)}/${cell.getFullYear()}`; + } + + render() { + const satisfaction = [0, 1, 2, 3, 4, 5]; + return ( + + + Product ID +
      clear filters +
      + { this.name1 = node; }} dataField='name' filter={{ type: 'TextFilter', placeholder: 'Please enter a value' }}>Product Name + { this.name2 = node; }} dataField='name' filter={{ type: 'RegexFilter', placeholder: 'Please enter a regex' }}>Product Name + < TableHeaderColumn ref={(node) => { this.quality = node; }} dataField='quality' filter={{ type: 'SelectFilter', options: qualityType }} + dataFormat={enumFormatter} formatExtraData={qualityType}>Product Quality
      + { this.price = node; }} dataField='price' filter={{ type: 'NumberFilter', delay: 1000 }}>Product Price + < TableHeaderColumn ref= {(node) => { this.satisfaction = node; }} dataField='satisfaction' filter={{ type: 'NumberFilter', options: satisfaction }}>Buyer Satisfaction
      + < TableHeaderColumn ref= {(node) => { this.inStockDate = node; }} dataField='inStockDate' filter={{ type: 'DateFilter' }} dataFormat={this.dateFormatter}>In Stock From
      +
      + ); + } +} + +/** + * Set Array filter programatically + * @see https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-filter/array-filter-programmatically.js + */ +class ProgrammaticallyArrayFilter extends React.Component { + table: BootstrapTable | null; + + /* Filtering passing an array of values */ + handleBtnClick = () => { + this.table.handleFilterData({ + name: { type: 'ArrayFilter', value: ['Item name 3', 'Item name 4'] }, + price: { type: 'ArrayFilter', value: [2100, 2104] } + }); + } + + render() { + return ( +
      + + { this.table = node; }} data={products}> + Product ID + Product Name + Product Price + +
      + ); + } +} diff --git a/types/react-bootstrap-table/tslint.json b/types/react-bootstrap-table/tslint.json index bf0a68ff4e..6fafe521cb 100644 --- a/types/react-bootstrap-table/tslint.json +++ b/types/react-bootstrap-table/tslint.json @@ -1,10 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "ban-types": false, - "prefer-method-signature": false, - "strict-export-declare-modifiers": false, - "no-empty-interface": false - } + "extends": "dtslint/dt.json" } diff --git a/types/react-bootstrap-table/v2/index.d.ts b/types/react-bootstrap-table/v2/index.d.ts new file mode 100644 index 0000000000..11c0f7f943 --- /dev/null +++ b/types/react-bootstrap-table/v2/index.d.ts @@ -0,0 +1,758 @@ +// Type definitions for react-bootstrap-table 2.6 +// Project: https://github.com/AllenFang/react-bootstrap-table +// Definitions by: Frank Laub , Aleksander Lode , Josué Us +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +// documentation taken from http://allenfang.github.io/react-bootstrap-table/docs.html + +import { ComponentClass, Props, ReactElement } from 'react'; +import { EventEmitter } from 'events'; + +/** + * Interface spec for sepcifying functionality to handle remotely + * + * Consult [documentation](https://allenfang.github.io/react-bootstrap-table/docs.html#remote) + * for more info + */ +export interface RemoteObjSpec { + /** + * If set, cell edits will be handled remotely + */ + cellEdit?: boolean; + /** + * If set insertions will be handled remotely + */ + insertRow?: boolean; + /** + * If set deletion will be handled remotely + */ + dropRow?: boolean; + /** + * If set filters will be handled remotely + */ + filter?: boolean; + /** + * If set search will be handled remotely + */ + search?: boolean; + /** + * If set, exporting CSV will be handled remotely + */ + exportCSV?: boolean; + /** + * If set sorting will be handled remotely + */ + sort?: boolean; + /** + * If set pagination will be handled remotely + */ + pagination?: boolean; +} + +export interface BootstrapTableProps extends Props { + /** + * Set version='4' to use bootstrap@4, else bootstrap@3 is used. + */ + version?: string; + /** + * Use data to specify the data that you want to display on table. + */ + data: any[]; + /** + * If set, data is remote (use also fetchInfo) + */ + remote?: ((remobeObj: RemoteObjSpec) => RemoteObjSpec) | boolean; // Updated to support ^3.0.0 + /** + * Use keyField to tell table which column is unique. This is same as isKey in + * Tips: You need choose one configuration to set key field: keyField or isKey in + */ + keyField?: string; + /** + * Use height to set the height of table, default is 100%. + */ + height?: string; + /** + * Set the max column width (pixels) + */ + maxHeight?: string; + /** + * Enable striped by setting striped to true. Same as Bootstrap table class .table-striped, default is false. + */ + striped?: boolean; + /** + * Enable hover by setting hover to true. Same as Bootstrap table class .table-hover, default is false. + */ + hover?: boolean; + /** + * Enable condensed by setting condensed to true. Same as Bootstrap table class .table-condensed, default is false. + */ + condensed?: boolean; + /** + * Become a borderless table by setting bordered to false, default is true. + */ + bordered?: boolean; + /** + * Enable pagination by setting pagination to true, default is false. + */ + pagination?: boolean; + /** + * Assign the class name of row(tr). This attribute accept a string or function and function is a better way to do more customization. + * If a string given, means the value will be presented as the row class. + * If a function given, will pass rowData and rowIndex as params and should return string for presenting class. for examples: + * @example + * function trClassFormat(rowData,rowIndex){ + * return rowIndex%2==0?"tr-odd":"tr-even"; //return a class name. + * } + */ + trClassName?: string | ((rowData: any, rowIndex: number) => string); + /** + * Enable row insertion by setting insertRow to true, default is false. + * If you enable row insertion, there's a button on the upper left side of table. + */ + insertRow?: boolean; + /** + * Enable row deletion by setting deleteRow to true, default is false. + * If you enable row deletion, there's a button on the upper left side of table. + */ + deleteRow?: boolean; + /** + * Enable column filter by setting columnFilter to true, default is false. + * If enabled, there're input text field per column under the table, user can input your filter condition by each column. + */ + columnFilter?: boolean; + /** + * Enable search by setting search to true, default is false. + * If enabled, there is a on the upper left side of the table. The default place holder is Search + */ + search?: boolean; + /** + * Set searchPlaceholder to change the placeholder in search field, default is Search. + */ + searchPlaceholder?: string; + /** + * Enable strict search, default is false. + * More info here: https://github.com/AllenFang/react-bootstrap-table/issues/1199 + */ + strictSearch?: boolean; + /** + * Enable multi search by multiColumnSearch, default is false. + * If you want to use multi search, you must enable search at first. + * Tips: Use space to delimited search text. EX: 3 4, which means match all 3 or 4 datas in table. + */ + multiColumnSearch?: boolean; + /** + * Enable export csv function, default is false. + * If you enable, there's a button on the upper left side of table. + */ + exportCSV?: boolean; + /** + * Set CSV filename (e.g. items.csv). Default is spreadsheet.csv + */ + csvFileName?: () => string | string; + /** + * Enable row selection on table. selectRow accept an object which have the following properties + */ + selectRow?: SelectRow; + /** + * Enable cell editing on table. cellEdit accept an object which have the following properties + */ + cellEdit?: CellEdit; + /** + * For some options setting on this component, you can set the options attribute and give an object which contain following properties + */ + options?: Options; + fetchInfo?: FetchInfo; + printable?: boolean; + tableStyle?: any; + containerStyle?: any; + headerStyle?: any; + bodyStyle?: any; + ignoreSinglePage?: boolean; + containerClass?: string; + tableContainerClass?: string; + headerContainerClass?: string; + bodyContainerClass?: string; + expandableRow?: (row: any) => boolean; + expandComponent?: (row: any) => any; +} + +export type SelectRowMode = 'none' | 'radio' | 'checkbox'; + +export interface SelectRow { + /** + * For specifing the selection is single(radio) or multiple(checkbox). + */ + mode: SelectRowMode; + /** + * Click the row will trigger selection on that row if enable clickToSelect, default is false. + */ + clickToSelect?: boolean; + /** + * If true, click the row will trigger selection on that row and also trigger cell editing if you enabled cell edit. Default is false. + */ + clickToSelectAndEditCell?: boolean; + /** + * You can assign the background color of row which be selected. + */ + bgColor?: string; + /** + * You can assign the class name of row which be selected. + */ + className?: string; + /** + * Give an array data to perform which rows you want to be selected when table loading. + * The content of array should be the rowkey which you want to be selected. + */ + selected?: string[] | number[]; + /** + * if true, the radio/checkbox column will be hide. + * You can enable this attribute if you enable clickToSelect and you don't want to show the selection column. + */ + hideSelectColumn?: boolean; + /** + * Default is false, if enabled, there will be a button on top of table for toggling selected rows only. + */ + showOnlySelected?: boolean; + /** + * Accept a custom callback function, if a row be selected or unselected, this function will be called. + * This callback function taking three arguments row, isSelected and event: + * `row`: is the row data which you wanted to select or unselect. + * `isSelected`: it's a boolean value means "whether or not that row will be selected?". + * `event`: The event target object. + * If return value of this (function) is false, the select or deselect action will not be applied. + */ + onSelect?: (row: any, isSelected: boolean, event: any) => boolean; + /** + * Accept a custom callback function, if click select all checkbox, this function will be called. + * This callback function taking two arguments isSelected and currentSelectedAndDisplayData: + * `isSelected`: it's a boolean value means "whether or not that row will be selected?". + * `currentSelectedAndDisplayData`: If pagination enabled, this result is the data which in a page. In contrast, this is all data in table. + * If return value of this function is false, the select all or deselect all action will not be applied. + */ + onSelectAll?: (isSelected: boolean, currentSelectedAndDisplayData: any) => boolean; + + /** + * Provide a list of unselectable row keys. + */ + unselectable?: number[]; +} + +export type CellEditClickMode = 'none' | 'click' | 'dbclick'; + +export interface CellEdit { + /** + * To spectify which condition will trigger cell editing.(click or dbclick) + */ + mode: CellEditClickMode; + /** + * Enable blurToSave will trigger a saving event on cell when mouse blur on the input field. Default is false. + * In the default condition, you need to press ENTER to save the cell. + */ + blurToSave?: boolean; + /** + * Accept a custom callback function, before cell saving, this function will be called. + * This callback function taking three arguments:row, cellName and cellValue + * It's necessary to return a bool value which whether apply this cell editing. + */ + beforeSaveCell?: (row: any, cellName: string, cellValue: any) => boolean; + /** + * Accept a custom callback function, after cell saving, this function will be called. + * This callback function taking three arguments:row, cellName and cellValue + */ + afterSaveCell?: (row: any, cellName: string, cellValue: any) => void; +} + +export type SortOrder = 'asc' | 'desc'; + +export interface Options { + /** + * Manage sort field by yourself + */ + sortName?: string; + /** + * Manage sort order by yourself + */ + sortOrder?: SortOrder; + /** + * Assign a default sort field. + */ + defaultSortName?: string; + /** + * Assign a default sort ordering. + */ + defaultSortOrder?: SortOrder; + /** + * False to disable sort indicator on header column, default is true. + */ + sortIndicator?: boolean; + /** + * Change the displaying text on table if data is empty. + */ + noDataText?: string | ReactElement; + /** + * A delay for trigger search after a keyup (millisecond) + */ + searchDelayTime?: number; + /** + * A custom text on export csv button + */ + exportCSVText?: string; + /** + * Default is false, if true means you want to ignore any editable configuration when row insert. + */ + ignoreEditable?: boolean; + /** + * Only work on enable search. If true, there will be a button beside search input field for clear search field text. + */ + clearSearch?: boolean; + /** + * Assign a callback function which will be called after table update. + */ + afterTableComplete?: Function; + /** + * Assign a callback function which will be called after row delete. + * This function taking one argument: rowKeys, which means the row key you dropped. + */ + afterDeleteRow?: (rowKeys: string[]) => void; + /** + * Assign a callback function which will be called after row insert. + * This function taking one argument: row, which means the whole row data you added. + */ + afterInsertRow?: (row: any) => void; + /** + * Customize the text of previouse page button + */ + prePage?: string; + /** + * Customize the text of next page button + */ + nextPage?: string; + /** + * Customize the text of first page button + */ + firstPage?: string; + /** + * Customize the text of last page button + */ + lastPage?: string; + /** + * Accept a number, which means the page you want to show as default. + */ + page?: number; + /** + * You can change the dropdown list for size per page if you enable pagination. + */ + sizePerPageList?: number[]; + /** + * Means the size per page you want to locate as default. + */ + sizePerPage?: number; + /** + * To define the pagination bar length, default is 5. + */ + paginationSize?: number; + /** + * To define where to start counting the pages. + */ + pageStartIndex?: number; + /** + * Assign a callback function which will be called after page changed. + * This function taking two argument: page and sizePerPage. + * `page`: Current page. + * `sizePerPage`: The data size which in one page. + */ + onPageChange?: (page: number, sizePerPage: number) => void; + /** + * Assign a callback function which will be called after size per page dropdown changed. + * This function taking one argument: sizePerPage. + * `sizePerPage`: The data size which in one page. + */ + onSizePerPageList?: (sizePerPage: number) => void; + /** + * Assign a callback function which will be called after trigger sorting. + * This function taking two argument: `sortName` and `sortOrde`r. + * `sortName`: The sort column name + * `sortOrder`: The sort ordering. + */ + onSortChange?: (sortName: string, sortOrder: SortOrder) => void; + /** + * Assign a callback function which will be called after trigger searching. + * This function taking two argument: search and result. + * `search`: The search text which user input. + * `result`: The results after searching. + */ + afterSearch?: (search: string, result: any) => void; + /** + * Assign a callback function which will be called after trigger column filtering. + * This function taking two argument: filterConds and result. + * `filterConds`: It's an array object which contain all column filter conditions. + * `result`: The results after filtering. + */ + afterColumnFilter?: (filterConds: any[], result: any) => void; + /** + * Assign a callback function which will be called after a row click. + * This function taking one argument: row which is the row data which you click on. + */ + onRowClick?: (row: any) => void; + /** + * Assign a callback function which will be called after a row double click. + * This function taking one argument: row which is the row data which you double click on. + */ + onRowDoubleClick?: (row: any) => void; + /** + * Background color on expanded rows. + */ + expandRowBgColor?: string; + /** + * Assign a callback function which will be called when mouse enter into the table. + */ + onMouseEnter?: Function; + /** + * Assign a callback function which will be called when mouse leave from the table. + */ + onMouseLeave?: Function; + /** + * Assign a callback function which will be called when mouse over a row in table. + * This function taking one argument: row which is the row data which mouse over. + */ + onRowMouseOver?: Function; + /** + * Assign a callback function which will be called when mouse leave from a row in table. + * This function taking one argument: row which is the row data which mouse out. + */ + onRowMouseOut?: Function; + + /** + * Assign a callback function which will be called when row dropping. + * It give you a chance to customize your confirmation for row deletion. + * This function taking two argument: next and rowKeys: + * `next`: If you confirm to drop row, call next() to continue the process + * `rowKeys` is the row keys which been deleted, you can call next function to apply this deletion. + */ + handleConfirmDeleteRow?: (next: Function, rowKeys: any[]) => void; + paginationShowsTotal?: boolean | ((start: number, to: number, total: number) => string | ReactElement); + onSearchChange?: Function; + onAddRow?: Function; + onExportToCSV?: Function; + + insertText?: string; + deleteText?: string; + saveText?: string; + closeText?: string; + // Customization properties + /** + * Callback function to be called when a cell is modified + * + * https://allenfang.github.io/react-bootstrap-table/example.html#remote + */ + onCellEdit?: (row: any, field: string, value: any) => any; + /** + * Callback function to be called when filter changing + * + * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-filtering.js#L67 + */ + onFilterChange?: (filterObj: any) => any; + /** + * Callback function which will be called when a row will be deleted + * + * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-delete-row.js#L27 + */ + onDeleteRow?: (rows: any) => any; + /** + * A callback which will be called after page changed + * + * https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/remote/remote-store-paging.js#L30 + */ + onpageChange?: (page: any, sizePerPage: number) => any; +} + +interface FetchInfo { + dataTotalSize?: number; +} + +export interface BootstrapTable extends ComponentClass { + /** + * Call this function to insert an new row to table. + */ + handleAddRow(row: any): void; + /** + * Call this function to insert an new row as first row on table. + */ + handleAddRowAtBegin(row: any): void; + /** + * Call this function to drop rows in table. + */ + handleDropRow(rowKeys: any[]): void; + /** + * Call this function to do column filtering on table. + */ + handleFilterData(filter: any): void; + /** + * Call this function with search text for fully searching. + */ + handleSearch(search: string): void; + /** + * Call this function to sort table. + */ + handleSort(order: SortOrder, field: string): void; + /** + * Call this function to get the page by a rowkey + */ + getPageByRowKey(rowKey: string): any; + /** + * Call this function to export table as csv. + */ + handleExportCSV(): void; + /** + * Clean all the selection state on table. + */ + cleanSelected(): void; +} +interface BootstrapTable extends ComponentClass { } +declare const BootstrapTable: BootstrapTable; +export type DataAlignType = 'left' | 'center' | 'right' | 'start' | 'end'; + +export interface TableHeaderColumnProps extends Props { + /** + * The field of data you want to show on column. + */ + dataField?: string; + /** + * Use isKey to tell table which column is unique. This is same as keyField in + * Tips: You need choose one configuration to set key field: isKey or keyField in + */ + isKey?: boolean; + /** + * Set the column width. ex: 150, it's means 150px + */ + width?: string; + /** + * Set align in column, value is left, center, right, start and end. + */ + dataAlign?: DataAlignType; + + /** + * Alignment of text in the column header. + */ + headerAlign?: DataAlignType; + /** + * True to enable table sorting. Default is disabled. + */ + dataSort?: boolean; + /** + * Default search string. + */ + defaultSearch?: string; + /** + * Allow user to render a custom sort caret. You should give a function and should return a JSX. + * This function taking one arguments: order which present the sort order currently. + */ + caretRender?: Function; + /** + * Give an Object like following to able to customize your own editing component. + * This Object should contain these two property: + * getElement(REQUIRED): Accept a callback function and take two arguments: onUpdate and props. + * customEditorParameters: Another extra data for custom cell edit component. + */ + customEditor?: { getElement: (onUpdate: any, props: any) => ReactElement, customEditorParameters?: object }; + /** + * To customize the column. This callback function should return a String or a React Component. + * In addition, this function taking two argument: cell and row. + */ + dataFormat?: (cell: any, row: any, formatExtraData?: any) => string | ReactElement; + /** + * To to enable search or filter data on formatting. Default is false + */ + filterFormatted?: boolean; + /** + * True to hide column. + */ + hidden?: boolean; + /** + * True to hide from insert dialog + */ + hiddenOnInsert?: boolean; + /** + * True to hide the dropdown for sizePerPage. + */ + hideSizePerPage?: boolean; + /** + * False to disable search functionality on column, default is true. + */ + searchable?: boolean; + /** + * Give a customize function for data sorting. + * This function taking four arguments: a, b, order, sortField, extraData + */ + sortFunc?: (a: any, b: any, order: SortOrder, sortField: any, extraData: any) => number; + /** + * It's a extra data for custom sort function, if defined, this data will be pass as fifth argument in sortFunc. + */ + sortFuncExtraData?: any; + /** + * Add custom css class on table header column, this attribute only accept String or Function. + * If Function, it taking four arguments: cell, row, rowIndex, columnIndex. + * In addition, this function should return a String which is the class name you want to add on. + */ + className?: string | ((cell: any, row: any, rowIndex: number, columnIndex: number) => string); + /** + * Add custom css class on table body column, this attribute only accept String or Function. + * If Function, it taking four arguments: cell, row, rowIndex, columnIndex. + * In addition, this function should return a String which is the class name you want to add on. + */ + columnClassName?: String | ((cell: any, row: any, rowIndex: number, columnIndex: number) => string); + /** + * Add True to set column editable, false is non-editable. If give Object, + * you can do more customization when editing cell. This object have following properties: + * @example + * { + * type: //edit type, avaiable value is textarea, select, checkbox + * validator: //give function for validation and taking only one "cell value" as argument. This function should return Bool. + * options:{ + * values: //values means data in select or checkbox.If checkbox, use ':'(colon) to separate value, ex: Y:N + * } + * } + */ + editable?: boolean | Editable; + /** + * It only work when you enable insertRow and be assign on rowKey column. + * If true, the row key will be generated automatically after a row insertion. + */ + autoValue?: boolean; + /** + * To Enable a column filter within header column. + * This feature support a lots of filter type and condition. Please check example + * Following is the format for filter + */ + filter?: Filter; + + onSort?: Function; + + /** + * Header for column in generated CSV file + */ + csvHeader?: string; + csvFormat?: Function; + columnTitle?: boolean; + sort?: SortOrder; + formatExtraData?: any; + + /** + * Row in the header on which this header column present. + */ + row?: number; + + /** + * Indicates how many rows this column takes. + * Default: 1 + */ + rowSpan?: number; + + /** + * Indicates how many columns this column takes. + * Default: 1 + */ + colSpan?: number; + + /** + * Return the value you want to be filtered on that column. + * It's useful if your column data is an object. + */ + filterValue?: Function; + + /** + * Allow you to add your custom attributes on TD element. + */ + tdAttr?: object; + + /** + * Allow you to add your custom style object on TD element. + */ + tdStyle?: object; + + /** + * Allow you to add your custom style object on TH element. + */ + thStyle?: object; +} +export interface Editable { + type?: string; // edit type, avaiable value is textarea, select, checkbox + /** + * Function for validation and taking only one "cell value" as argument. This function should return Bool. + */ + validator?: (cell: any) => boolean; + /** + * @example + * { + * values: //values means data in select or checkbox. If checkbox, use ':'(colon) to separate value, ex: Y:N + * } + */ + options?: any; + + /** + * Configuration for the textarea editable type + */ + cols?: number; + rows?: number; +} +export type SetFilterCallback = (targetValue: any) => boolean; +export interface ApplyFilterParameter { + callback: SetFilterCallback; +} + +export type FilterType = 'TextFilter' | 'RegexFilter' | 'SelectFilter' | 'NumberFilter' | 'DateFilter' | 'CustomFilter'; +export interface Filter { + /** + * "TextFilter"||"SelectFilter"||"NumberFilter"||"DateFilter"||"RegexFilter"||"YOUR_CUSTOM_FILTER" + */ + type?: FilterType; + /** + * Default value on filter. If type is NumberFilter or DateFilter, this value will like { number||date: xxx, comparator: '>' } + */ + defaultValue?: any; + /** + * Assign a millisecond for delay when trigger filtering, default is 500. + */ + delay?: number; + /** + * Only work on TextFilter. Assign the placeholder text on text and regex filter + */ + placeholder?: string | RegExp; + /** + * Only work on NumberFilter. Accept an array which conatin the filter condition, like: ['<','>','='] + */ + numberComparators?: string[]; + + /** + * Options for the filter. + */ + options?: any; + + /** + * Comparison condition for the NumberFilter + */ + condition?: string; + + /** + * Get element which represent filter. + */ + getElement?: (filterHandler: (parameters?: ApplyFilterParameter) => void, filterParameters: any) => JSX.Element; + + /** + * Parameters for custom filter + */ + customFilterParameters?: any; +} + +export interface TableHeaderColumn extends ComponentClass { } +declare const TableHeaderColumn: TableHeaderColumn; + +declare class TableDataSet extends EventEmitter { + constructor(data: any); + setData(data: any): void; + clear(): void; + getData(): any; +} diff --git a/types/react-bootstrap-table/v2/react-bootstrap-table-tests.tsx b/types/react-bootstrap-table/v2/react-bootstrap-table-tests.tsx new file mode 100644 index 0000000000..c8f25dfa56 --- /dev/null +++ b/types/react-bootstrap-table/v2/react-bootstrap-table-tests.tsx @@ -0,0 +1,175 @@ +import * as React from 'react'; +import { render } from 'react-dom'; +import { BootstrapTable, TableHeaderColumn, ApplyFilterParameter, Filter } from 'react-bootstrap-table'; + +const products = [{ + id: 1, + name: "Item name 1", + price: 100 +}, { + id: 2, + name: "Item name 2", + price: 100 +}]; + +// It's a data format example. +function priceFormatter(cell: any, row: any) { + return ' ' + cell; +} + +render( + + Product ID + Product Name + Product Price + , + document.getElementById("app") +); + +const qualityType = { + 0: 'good', + 1: 'bad', + 2: 'unknown' +}; + +function enumFormatter(cell: any, row: any, enumObject: any) { + return enumObject[cell]; +} + +class SelectFilterWithDefaultValue extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Quality + + ); + } +} + +class TextFilterWithCondition extends React.Component { + render() { + return ( + + Product ID + Product Name + Product Price + + ); + } +} + +function getCustomFilter(filterHandler: (parameters?: ApplyFilterParameter) => void, customFilterParameters: any) { + return ( +
      + ); +} + +class CustomFilter extends React.Component { + render() { + const filter: Filter = { type: 'CustomFilter', getElement: getCustomFilter, customFilterParameters: { textOK: 'yes', textNOK: 'no' } }; + return ( + + Product ID + Product Name + Product Is In Stock + + ); + } +} + +class RemoteProps extends React.Component { + render() { + const filter: Filter = { type: 'CustomFilter', getElement: getCustomFilter, customFilterParameters: { textOK: 'yes', textNOK: 'no' } }; + return ( + { + remoteObj.cellEdit = true; + return remoteObj; + }} + options={{ + onCellEdit: (row: any, fieldName: string, value: any) => { console.info(row); } + }} + > + Product ID + Product Name + Product Is In Stock + + ); + } +} + +class RemoteBool extends React.Component { + render() { + const filter: Filter = { type: 'CustomFilter', getElement: getCustomFilter, customFilterParameters: { textOK: 'yes', textNOK: 'no' } }; + return ( + + Product ID + Product Name + Product Is In Stock + + ); + } +} + +/** + * See http://allenfang.github.io/react-bootstrap-table/docs.html#tdAttr + */ +const tdAttrExample = + Product ID + Product Name + Product Price +; + +/** + * See http://allenfang.github.io/react-bootstrap-table/docs.html#tdStyle + */ +const tdStyleExample = + Product ID + Product Name + Product Price +; + +/** + * See http://allenfang.github.io/react-bootstrap-table/docs.html#thStyle + */ +const thStyleExample = + Product ID + Product Name + Product Price +; + +// Adopted from https://github.com/AllenFang/react-bootstrap-table/blob/master/examples/js/column-header-span/column-header-span-complex.js +export default class ColumnHeaderSpanComplex extends React.Component { + render() { + const selectRow = { + mode: 'checkbox', + bgColor: 'rgb(238, 193, 213)' + }; + + const cellEdit = { + mode: 'click', + blurToSave: true + }; + return ( + + ID + Product + name + price + Coupon + In stock + Customer + name + order + + ); + } +} diff --git a/types/react-bootstrap-table/v2/tsconfig.json b/types/react-bootstrap-table/v2/tsconfig.json new file mode 100644 index 0000000000..eee5850865 --- /dev/null +++ b/types/react-bootstrap-table/v2/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "paths": { + "react-bootstrap-table": [ + "react-bootstrap-table/v2" + ] + }, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-bootstrap-table-tests.tsx" + ] +} diff --git a/types/react-bootstrap-table/v2/tslint.json b/types/react-bootstrap-table/v2/tslint.json new file mode 100644 index 0000000000..bf0a68ff4e --- /dev/null +++ b/types/react-bootstrap-table/v2/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "ban-types": false, + "prefer-method-signature": false, + "strict-export-declare-modifiers": false, + "no-empty-interface": false + } + } diff --git a/types/react-bootstrap/lib/DropdownToggle.d.ts b/types/react-bootstrap/lib/DropdownToggle.d.ts index e5655c22f8..d166c5ae25 100644 --- a/types/react-bootstrap/lib/DropdownToggle.d.ts +++ b/types/react-bootstrap/lib/DropdownToggle.d.ts @@ -9,6 +9,7 @@ declare namespace DropdownToggle { useAnchor?: boolean; bsClass?:string; // Added since v0.30.0 bsStyle?:string; + bsSize?:string; } } declare class DropdownToggle extends React.Component { } diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index d09784acb6..3e79703242 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -161,6 +161,13 @@ declare namespace AdazzleReactDataGrid { * @default false */ enableCellSelect?: boolean + + /** + * Enables cells to be dragged and dropped + * @default false + */ + enableDragAndDrop?: boolean + /** * Called when a cell is selected. * @param coordinates The row and column indices of the selected cell. @@ -198,6 +205,13 @@ declare namespace AdazzleReactDataGrid { * @param row object behind the row */ onRowClick?: (rowIdx : number, row : object) => void + + /** + * An event function called when a row is expanded with the toggle + * @param props OnRowExpandToggle object + */ + onRowExpandToggle?: (props: OnRowExpandToggle ) => void + /** * Responsible for returning an Array of values that can be used for filtering * a column that is column.filterable and using a column.filterRenderer that @@ -419,6 +433,24 @@ declare namespace AdazzleReactDataGrid { action: 'cellUpdate' | 'cellDrag' | 'columnFill' | 'copyPaste' } + /** + * Information about the row toggler + */ + interface OnRowExpandToggle { + /** + * The name of the column group the row is in + */ + columnGroupName: string + /** + * The name of the expanded row + */ + name: string + /** + * If it should expand or not + */ + shouldExpand: boolean + } + /** * Some filter to be applied to the grid's contents */ @@ -455,6 +487,7 @@ declare namespace AdazzleReactDataGrid { export import DragHandleDoubleClickEvent = AdazzleReactDataGrid.DragHandleDoubleClickEvent; export import CellCopyPasteEvent = AdazzleReactDataGrid.CellCopyPasteEvent; export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent; + export import OnRowExpandToggle = AdazzleReactDataGrid.OnRowExpandToggle; // Actual classes exposed on module.exports /** diff --git a/types/react-data-grid/react-data-grid-tests.tsx b/types/react-data-grid/react-data-grid-tests.tsx index 6d5ff3b4da..1b42af7ae6 100644 --- a/types/react-data-grid/react-data-grid-tests.tsx +++ b/types/react-data-grid/react-data-grid-tests.tsx @@ -249,6 +249,13 @@ class Example extends React.Component { this.setState({rows: rows}); } + onRowExpandToggle = ({ columnGroupName, name, shouldExpand }:ReactDataGrid.OnRowExpandToggle ) => { + let expandedRows = Object.assign({}, this.state.expandedRows); + expandedRows[columnGroupName] = Object.assign({}, expandedRows[columnGroupName]); + expandedRows[columnGroupName][name] = {isExpanded: shouldExpand}; + this.setState({expandedRows: expandedRows}); + } + onRowClick(rowIdx:number, row: Object) { // Do nothing, just test that it accepts an event } @@ -300,10 +307,12 @@ class Example extends React.Component { } enableRowSelect={true} rowHeight={50} diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 5a29b38149..a92446371d 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -4,7 +4,7 @@ import DatePicker from 'react-datepicker'; class ReactDatePicker extends React.Component<{}, { startDate: moment.Moment; displayName: string; }> { constructor(props: {}) { - super(); + super(props); this.state = { startDate: moment(), displayName: 'Example' diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts index cd2713a459..058777bc29 100644 --- a/types/react-daum-postcode/index.d.ts +++ b/types/react-daum-postcode/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kimminsik-bernard/react-daum-postcode // Definitions by: Sa-ryong Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Component } from 'react'; diff --git a/types/react-dnd-touch-backend/index.d.ts b/types/react-dnd-touch-backend/index.d.ts index 2920ce3891..6cf6037048 100644 --- a/types/react-dnd-touch-backend/index.d.ts +++ b/types/react-dnd-touch-backend/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/yahoo/react-dnd-touch-backend#readme // Definitions by: Daniel Król , Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as ReactDnd from "react-dnd"; diff --git a/types/react-document-title/index.d.ts b/types/react-document-title/index.d.ts index 63acedfdeb..fa22fe30dc 100644 --- a/types/react-document-title/index.d.ts +++ b/types/react-document-title/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/gaearon/react-document-title // Definitions by: Cleve Littlefield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as React from 'react'; diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index 05362460d4..caa5605ef5 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -59,7 +59,7 @@ export interface SyntheticEventData extends OptionalEventProperties { export type EventSimulator = (element: Element | Component, eventData?: SyntheticEventData) => void; export interface MockedComponentClass { - new (): any; + new (props: {}): any; } export interface ShallowRenderer { diff --git a/types/react-ga/index.d.ts b/types/react-ga/index.d.ts index 83d7a7218e..56d9715ed1 100644 --- a/types/react-ga/index.d.ts +++ b/types/react-ga/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-ga 2.1 // Project: https://github.com/react-ga/react-ga -// Definitions by: Tim Aldridge +// Definitions by: Tim Aldridge , Vasya Aksyonov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface EventArgs { @@ -54,7 +54,8 @@ export interface OutboundLinkArgs { } export function initialize(trackingCode: string, options?: InitializeOptions): void; -export function ga(): any; +export function ga(): (...args: any[]) => any; +export function ga(...args: any[]): any; export function set(fieldsObject: FieldsObject): void; export function send(fieldsObject: FieldsObject): void; export function pageview(path: string): void; diff --git a/types/react-ga/react-ga-tests.ts b/types/react-ga/react-ga-tests.ts index dbc1d0970c..9e1ba7b23b 100644 --- a/types/react-ga/react-ga-tests.ts +++ b/types/react-ga/react-ga-tests.ts @@ -63,6 +63,12 @@ describe("Testing react-ga v2.1.2", () => { it("Able to make ga calls", () => { ga.ga(); }); + it("Able to make ga calls with any arguments", () => { + ga.ga("create", "UA-65432-1", "auto", "trackerName"); + }); + it("Able to make returned ga calls with any arguments", () => { + ga.ga()("create", "UA-65432-1", "auto", "trackerName"); + }); it("Able to make send calls", () => { const fieldObject: ga.FieldsObject = { page: '/users' diff --git a/types/react-grid-layout/index.d.ts b/types/react-grid-layout/index.d.ts index bf3f5805d9..7c59c0bf39 100644 --- a/types/react-grid-layout/index.d.ts +++ b/types/react-grid-layout/index.d.ts @@ -64,6 +64,11 @@ declare namespace ReactGridLayout { */ maxH?: number; + /** + * set by DragEvents (onDragStart, onDrag, onDragStop) and ResizeEvents (onResizeStart, onResize, onResizeStop) + */ + moved?: boolean; + /** * If true, equal to `isDraggable: false` and `isResizable: false`. */ @@ -168,6 +173,11 @@ declare namespace ReactGridLayout { */ isResizable?: boolean; + /** + * Enable or disable grid rearrangement when dragging/resizing an element. + */ + isRearrangeable?: boolean; + /** * Uses CSS3 `translate()` instead of position top/left. * This makes about 6x faster paint performance. diff --git a/types/react-intl-redux/index.d.ts b/types/react-intl-redux/index.d.ts index bd5069d8f1..e47a48110c 100644 --- a/types/react-intl-redux/index.d.ts +++ b/types/react-intl-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ratson/react-intl-redux // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { Action } from "redux" import { Provider as ReduxProvider } from "react-redux" diff --git a/types/react-lazyload/react-lazyload-tests.tsx b/types/react-lazyload/react-lazyload-tests.tsx index e6f0f9bc81..f673652ef5 100644 --- a/types/react-lazyload/react-lazyload-tests.tsx +++ b/types/react-lazyload/react-lazyload-tests.tsx @@ -7,7 +7,7 @@ interface State { class Normal extends React.Component<{}, State> { constructor() { - super(); + super({}); const arr: string[] = []; for (let i = 0; i < 200; i++) { arr.push(`${i}`); diff --git a/types/react-mdl/index.d.ts b/types/react-mdl/index.d.ts index d157987929..33dccccd07 100644 --- a/types/react-mdl/index.d.ts +++ b/types/react-mdl/index.d.ts @@ -584,7 +584,7 @@ declare namespace __ReactMDL { class Tabs extends __MDLComponent { } - interface TextfieldProps extends MDLHTMLAttributes, React.DOMAttributes { + interface TextfieldProps extends MDLHTMLAttributes, React.DOMAttributes { label: string; disabled?: boolean; error?: React.ReactNode; @@ -594,7 +594,7 @@ declare namespace __ReactMDL { id?: string; inputClassName?: string; maxRows?: number; - onChange?: React.FormEventHandler; + onChange?: React.FormEventHandler; pattern?: string; required?: boolean; rows?: number; diff --git a/types/react-native-elements/index.d.ts b/types/react-native-elements/index.d.ts index b3f9b37a07..a880dad13f 100644 --- a/types/react-native-elements/index.d.ts +++ b/types/react-native-elements/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Kyle Roach // Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as React from 'react'; import { @@ -255,11 +255,9 @@ export interface ButtonProps extends TouchableWithoutFeedbackProps { fontWeight?: string; /** - * Moves icon to right of title - * - * @default false + * Icon configuration for icon on right side of title */ - iconRight?: boolean; + iconRight?: ButtonIcon; /** * onPress method diff --git a/types/react-native-elements/react-native-elements-tests.tsx b/types/react-native-elements/react-native-elements-tests.tsx index b6a8ba8c83..29155829b2 100644 --- a/types/react-native-elements/react-native-elements-tests.tsx +++ b/types/react-native-elements/react-native-elements-tests.tsx @@ -222,8 +222,7 @@ class ButtonTest extends React.Component { {' '} + {' '} + {' '} + {' '} + {' '} + {' '} + +
      + ); + } +} + +class Example8 extends React.Component { + render() { + return ( +
      + {' '} + {' '} + {' '} + {' '} + {' '} + +
      + ); + } +} + +const Example9 = ( +
      + {' '} + +
      +); + +const Example10 = ( +
      + {' '} + +
      +); + +const Example11 = ( +
      + + +
      +); + +const Example12 = ( +
      + {' '} + +
      +); + +const Example13 = ( +
      + {' '} + +
      +); + +class Example14 extends React.Component { + constructor(props: any) { + super(props); + + this.state = { cSelected: [] }; + + this.onRadioBtnClick = this.onRadioBtnClick.bind(this); + this.onCheckboxBtnClick = this.onCheckboxBtnClick.bind(this); + } + + onRadioBtnClick(rSelected: number) { + this.setState({ rSelected }); + } + + onCheckboxBtnClick(selected: number) { + const index = this.state.cSelected.indexOf(selected); + if (index < 0) { + this.state.cSelected.push(selected); + } else { + this.state.cSelected.splice(index, 1); + } + this.setState({ cSelected: [...this.state.cSelected] }); + } + + render() { + return ( +
      +
      Radio Buttons
      + + + + + +

      Selected: {this.state.rSelected}

      + +
      Checkbox Buttons
      + + + + + +

      Selected: {JSON.stringify(this.state.cSelected)}

      +
      + ); + } +} + +// ------------- Button Dropdown +class Example15 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( + + + Button Dropdown + + + Header + Action + Another Action + + { + // something happens here + }}>Another Action + + + ); + } +} + +const Example16 = ( + true}> + + Text + + + Header + Action + Another Action + + Another Action + + +); + +const Example17 = (props: any) => ( + true}> + + + + Header + Action + Another Action + + Another Action + + +); + +const Example18 = ( +
      + true}> + + Large Button + + + Another Action + Another Action + + + + true}> + + Small Button + + + Another Action + Another Action + + +
      +); + +const Example19 = ( + true} dropup> + + Dropup + + + Another Action + Another Action + + +); + +// --------------- ButtonGroup +class Example20 extends React.Component { + render() { + return ( + + {' '} + {' '} + + + ); + } +} + +class Example21 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + ); + } +} + +const Example22 = (props: any) => ( +
      + + + + + + + + + + + + + + + + + +
      +); + +const Example23 = (props: any) => ( + + + + true}> + + Dropdown + + + Dropdown Link + Dropdown Link + + + +); + +const Example24 = (props: any) => ( + + + + true}> + + Dropdown + + + Dropdown Link + Dropdown Link + + + +); + +// ------------------ Cards +const Example25 = (props: any) => { + return ( +
      + + + + Card title + Card subtitle + Some quick example text to build on the card title and make up the bulk of the card's content. + + + +
      + ); +}; + +const Example26 = (props: any) => { + return ( +
      + + + Card title + Card subtitle + + Card image cap + + Some quick example text to build on the card title and make up the bulk of the card's content. + Card Link + Another Link + + +
      + ); +}; + +const Example27 = (props: any) => { + return ( + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + + ); +}; + +const Example28 = (props: any) => { + return ( +
      + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + +
      + ); +}; + +const Example29 = (props: any) => { + return ( +
      + + Header + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + Footer + + + + Featured + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + Footer + +
      + ); +}; + +const Example30 = (props: any) => { + return ( +
      + + + + Card Title + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + Last updated 3 mins ago + + + + + + Card Title + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + Last updated 3 mins ago + + + + +
      + ); +}; + +const Example31 = (props: any) => { + return ( +
      + + + + Card Title + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + Last updated 3 mins ago + + + +
      + ); +}; + +const Example32 = (props: any) => { + return ( +
      + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + +
      + ); +}; + +const Example33 = (props: any) => { + return ( +
      + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + +
      + ); +}; + +const Example34 = (props: any) => { + return ( + + + + + Card title + Card subtitle + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + + + + + + Card title + Card subtitle + This card has supporting text below as a natural lead-in to additional content. + + + + + + + Card title + Card subtitle + + This is a wider card with supporting text below as a natural lead-in to additional content. This + card has even longer content than the first to show that equal height action. + + + + + + ); +}; + +const Example35 = (props: any) => { + return ( + + + + + Card title + Card subtitle + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + + + + + + Card title + Card subtitle + This card has supporting text below as a natural lead-in to additional content. + + + + + + + Card title + Card subtitle + + This is a wider card with supporting text below as a natural lead-in to additional content. This card has + even longer content than the first to show that equal height action. + + + + + + ); +}; + +const Example36 = (props: any) => { + return ( + + + + + Card title + Card subtitle + This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. + + + + + + + + + Card title + Card subtitle + This card has supporting text below as a natural lead-in to additional content. + + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + + + Card title + Card subtitle + + This is a wider card with supporting text below as a natural lead-in to additional content. This card + has even longer content than the first to show that equal height action. + + + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + ); +}; + +// ------------------ Collapse + +class Example37 extends React.Component { + constructor(props: any) { + super(props); + this.toggle = this.toggle.bind(this); + this.state = { collapse: false }; + } + + toggle() { + this.setState({ collapse: !this.state.collapse }); + } + + render() { + return ( +
      + + + + + Anim pariatur cliche reprehenderit, + enim eiusmod high life accusamus terry richardson ad squid. Nihil + anim keffiyeh helvetica, craft beer labore wes anderson cred + nesciunt sapiente ea proident. + + + +
      + ); + } +} + +class Example38 extends React.Component { + constructor(props: any) { + super(props); + this.onOpened = this.onOpened.bind(this); + this.onClosed = this.onClosed.bind(this); + this.toggle = this.toggle.bind(this); + this.state = { collapse: false, status: 'Closed' }; + } + + onOpened() { + this.setState({ ...this.state, status: 'Opened' }); + } + + onClosed() { + this.setState({ ...this.state, status: 'Closed' }); + } + + toggle() { + const status = !this.state.collapse ? 'Opening...' : 'Closing...'; + this.setState({ collapse: !this.state.collapse, status }); + } + + render() { + return ( +
      + +
      Current state: {this.state.status}
      + + + + Anim pariatur cliche reprehenderit, + enim eiusmod high life accusamus terry richardson ad squid. Nihil + anim keffiyeh helvetica, craft beer labore wes anderson cred + nesciunt sapiente ea proident. + + + +
      + ); + } +} + +// ------- Dropdown + +class Example39 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( + + + Dropdown + + + Header + Action + Another Action + + Another Action + + + ); + } +} + +const Example40 = (props: any) => ( + false}> + + Dropdown + + + Header + Action + Another Action + + Another Action + + +); + +const Example41 = (props: any) => ( + Header +); + +const Example42 = (props: any) => ( +
      + + Action + Action + true}> + asdfasd + sadfas + + + true}> + sadfasd + sadf + + + true}> + asdf + sasdfsdf + + +
      +); + +class Example43 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( + + + Custom Dropdown Content + + +
      Custom dropdown item
      +
      Custom dropdown item
      +
      Custom dropdown item
      +
      Custom dropdown item
      +
      +
      + ); + } +} + +function Example44() { + return ( + + + Dropdown + + + Header + Action + Another Action + + Another Action + + + ); +} + +// ------------------ Form +class Example45 extends React.Component { + render() { + return ( +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is some placeholder block-level help text for the above input. + It's a bit lighter and easily wraps to a new line. + + + + Radio Buttons + + + + + + + + + + + + + + +
      + ); + } +} + +class Example46 extends React.Component { + render() { + return ( +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is some placeholder block-level help text for the above input. + It's a bit lighter and easily wraps to a new line. + + + + + Radio Buttons + + + + + + + + + + + + + + + + + + + + + + + + + +
      + ); + } +} + +class Example47 extends React.Component { + render() { + return ( +
      + + {' '} + + + {' '} + + {' '} + + + {' '} + +
      + ); + } +} + +class Example48 extends React.Component { + render() { + return ( +
      + + + + Success! You did it! + Example help text that remains unchanged. + + + + + Whoops, check your formatting and try again. + Example help text that remains unchanged. + + + + + Oh noes! that name is already taken + Example help text that remains unchanged. + +
      + ); + } +} + +class Example49 extends React.Component { + render() { + return ( +
      + + + Some static value + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is some placeholder block-level help text for the above input. + It's a bit lighter and easily wraps to a new line. + + + + + + + + +
      + ); + } +} + +class Example50 extends React.Component { + render() { + return ( +
      + + + + + + + + + + + + +
      + ); + } +} + +class Example51 extends React.Component { + render() { + return ( +
      + + + + + {' '} + + + + + {' '} + +
      + ); + } +} + +const Example52 = (props: any) => { + return ( +
      + + @ + + +
      + + + + + + +
      + + + @example.com + +
      + + $ + $ + + $ + $ + +
      + + $ + + .00 + +
      + ); +}; + +const Example53 = (props: any) => { + return ( +
      + + To the Left! + + +
      + + + To the Right! + +
      + + To the Left! + + To the Right! + +
      + ); +}; + +const Example54 = (props: any) => { + return ( +
      + + @lg + + +
      + + @normal + + +
      + + @sm + + +
      + ); +}; + +const Example55 = (props: any) => { + return ( +
      + + + + +
      + + + + +
      + + + + + +
      + ); +}; + +const Example56 = (props: any) => { + return ( +
      + + @lg + + +
      + + @normal + + +
      + + @sm + + +
      + ); +}; + +const Example57 = (props: any) => { + return ( +
      + + + + +
      + + + + +
      + + + + + +
      + ); +}; + +const Example58 = (props: any) => { + return ( +
      + + To the Left! + + +
      + + + To the Right! + +
      + + To the Left! + + To the Right! + +
      + ); +}; + +const Example59 = (props: any) => { + return ( +
      + +

      Hello, world!

      +

      This is a simple hero unit, a simple Jumbotron-style component for calling extra attention to featured content or information.

      +
      +

      It uses utility classes for typgraphy and spacing to space content out within the larger container.

      +

      + +

      +
      +
      + ); +}; + +const Example60 = (props: any) => { + return ( +
      + + +

      Fluid jumbotron

      +

      This is a modified jumbotron that occupies the entire horizontal space of its parent.

      +
      +
      +
      + ); +}; + +class Example61 extends React.Component { + render() { + return ( + + + .col + + + .col + .col + .col + .col + + + .col-3 + .col-auto - variable width content + .col-3 + + + .col-6 + .col-6 + + + .col-6 .col-sm-4 + .col-6 .col-sm-4 + .col .col-sm-4 + + + .col .col-sm-6 .col-sm-push-2 .col-sm-pull-2 .col-sm-offset-2 + + + .col .col-sm-12 .col-md-6 .col-md-offset-3 + + + .col .col-sm .col-sm-offset-1 + .col .col-sm .col-sm-offset-1 + + + ); + } +} + +class Example62 extends React.Component { + render() { + return ( + + Cras justo odio + Dapibus ac facilisis in + Morbi leo risus + Porta ac consectetur ac + Vestibulum at eros + + ); + } +} + +class Example63 extends React.Component { + render() { + return ( + + Cras justo odio 14 + Dapibus ac facilisis in 2 + Morbi leo risus 1 + + ); + } +} + +class Example64 extends React.Component { + render() { + return ( + + Cras justo odio + Dapibus ac facilisis in + Morbi leo risus + Porta ac consectetur ac + Vestibulum at eros + + ); + } +} + +class Example65 extends React.Component { + render() { + return ( +
      +

      Anchors

      +

      Be sure to not use the standard .btn classes here.

      + + Cras justo odio + Dapibus ac facilisis in + Morbi leo risus + Porta ac consectetur ac + Vestibulum at eros + +

      +

      Buttons

      + + Cras justo odio + Dapibus ac facilisis in + Morbi leo risus + Porta ac consectetur ac + Vestibulum at eros + +
      + ); + } +} + +class Example66 extends React.Component { + render() { + return ( + + Cras justo odio + Dapibus ac facilisis in + Morbi leo risus + Porta ac consectetur ac + + ); + } +} + +class Example67 extends React.Component { + render() { + return ( + + + List group item heading + + Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit. + + + + List group item heading + + Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit. + + + + List group item heading + + Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit. + + + + ); + } +} + +// ------------- Media +const Example68 = () => { + return ( + + + + + + + Media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus + odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. + Donec lacinia congue felis in faucibus. + + + ); +}; + +const Example69 = () => { + return ( + + + + + + + Media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus + odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. + Donec lacinia congue felis in faucibus. + + + + + + + Nested media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + ); +}; + +const Example70 = () => { + return ( +
      + + + + + + + Top aligned media + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + + + + + Middle aligned media + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + + + + + Bottom aligned media + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + +
      + ); +}; + +const Example71 = () => { + return ( + + + + + + + + Media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + + + Nested media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. + Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi + vulputate fringilla. Donec lacinia congue felis in faucibus. + + + + + + + Nested media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. + Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi + vulputate fringilla. Donec lacinia congue felis in faucibus. + + + + + + + + + + + Nested media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + + + + Media heading + + Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras + purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate + fringilla. Donec lacinia congue felis in faucibus. + + + + + + + ); +}; + +// --------------- Modal +class ModalExample72 extends React.Component { + constructor(props: any) { + super(props); + this.state = { + modal: false + }; + + this.toggle = this.toggle.bind(this); + } + + toggle() { + this.setState({ + modal: !this.state.modal + }); + } + + render() { + return ( +
      + + + Modal title + + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et + dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex + ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat + nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit + anim id est laborum. + + + {' '} + + + +
      + ); + } +} + +class ModalExample73 extends React.Component { + constructor(props: any) { + super(props); + this.state = { + modal: false, + backdrop: true + }; + + this.toggle = this.toggle.bind(this); + this.changeBackdrop = this.changeBackdrop.bind(this); + } + + toggle() { + this.setState({ + modal: !this.state.modal + }); + } + + changeBackdrop(e: React.ChangeEvent) { + let value = e.target.value; + if (value !== 'static') { + value = JSON.parse(value); + } + this.setState({ backdrop: value }); + } + + render() { + return ( +
      +
      e.preventDefault()}> + + {' '} + + + + + + + {' '} + +
      + + Modal title + + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et + dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip + ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu + fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt + mollit anim id est laborum. + + + {' '} + + + +
      + ); + } +} + +class ModalExample74 extends React.Component { + constructor(props: any) { + super(props); + this.state = { + modal: false, + nestedModal: false, + }; + + this.toggle = this.toggle.bind(this); + this.toggleNested = this.toggleNested.bind(this); + } + + toggle() { + this.setState({ + modal: !this.state.modal + }); + } + + toggleNested() { + this.setState({ + nestedModal: !this.state.nestedModal + }); + } + + render() { + return ( +
      + + + Modal title + + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et + dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex + ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu + fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt + mollit anim id est laborum. +
      + + + Nested Modal title + Stuff and things + + {' '} + + + +
      + + {' '} + + +
      +
      + ); + } +} + +class Example75 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +class Example76 extends React.Component { + constructor(props: any) { + super(props); + + this.toggleNavbar = this.toggleNavbar.bind(this); + this.state = { + collapsed: true + }; + } + + toggleNavbar() { + this.setState({ + collapsed: !this.state.collapsed + }); + } + render() { + return ( +
      + + + + reactstrap + + + +
      + ); + } +} + +class Example77 extends React.Component { + render() { + return ( +
      +

      List Based

      + +
      +

      Link Based

      + +
      + ); + } +} + +class Example78 extends React.Component { + render() { + return ( +
      +

      List Based

      + +
      +

      Link based

      + +
      + ); + } +} + +class Example79 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( +
      + +
      + ); + } +} + +class Example80 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + dropdownOpen: false + }; + } + + toggle() { + this.setState({ + dropdownOpen: !this.state.dropdownOpen + }); + } + + render() { + return ( +
      + +
      + ); + } +} + +// ----------- Pagination +class Example81 extends React.Component { + render() { + return ( + + + + + + + 1 + + + + + 2 + + + + + 3 + + + + + 4 + + + + + 5 + + + + + + + ); + } +} + +class Example82 extends React.Component { + render() { + return ( + + + + + + + 1 + + + + + 2 + + + + + 3 + + + + + 4 + + + + + 5 + + + + + + + ); + } +} + +class Example83 extends React.Component { + render() { + return ( + + + + + + + 1 + + + + + 2 + + + + + 3 + + + + + + + ); + } +} + +class Example84 extends React.Component { + render() { + return ( + + + + + + + 1 + + + + + 2 + + + + + 3 + + + + + + + ); + } +} + +// ------------------------- Popover +class Example85 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + popoverOpen: false + }; + } + + toggle() { + this.setState({ + popoverOpen: !this.state.popoverOpen + }); + } + + render() { + return ( +
      + + + Popover Title + Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. + +
      + ); + } +} + +class PopoverItem extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + popoverOpen: false + }; + } + + toggle() { + this.setState({ + popoverOpen: !this.state.popoverOpen + }); + } + + render() { + return ( + + + + Popover Title + Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. + + + ); + } +} + +class PopoverExampleMulti extends React.Component}> { + constructor(props: any) { + super(props); + + this.state = { + popovers: [ + { + placement: 'top', + text: 'Top' + }, + { + placement: 'bottom', + text: 'Bottom' + }, + { + placement: 'left', + text: 'Left' + }, + { + placement: 'right', + text: 'Right' + } + ] + }; + } + + render() { + return ( +
      + {this.state.popovers.map((popover, i) => { + return ; + })} +
      + ); + } +} + +// ------------------------- Progress + +const Example86 = (props: any) => { + return ( +
      +
      0%
      + +
      25%
      + +
      50%
      + +
      75%
      + +
      100%
      + +
      Multiple bars
      + + + + + + + +
      + ); +}; + +const Example87 = (props: any) => { + return ( +
      + + + + + +
      + ); +}; + +const Example88 = (props: any) => { + return ( +
      + 25% + 1/2 + You're almost there! + You did it! + + Meh + Wow! + Cool + 20% + !! + +
      + ); +}; + +const Example89 = (props: any) => { + return ( +
      + + + + + + + + + + + +
      + ); +}; + +const Example90 = (props: any) => { + return ( +
      + + + + + + + + + + + +
      + ); +}; + +const Example91 = (props: any) => { + return ( +
      +
      Plain
      + + + + + + + +
      With Labels
      + + Meh + Wow! + 25% + LOOK OUT!! + +
      Stripes and Animations
      + + Stripes + Animated Stripes + Plain + +
      + ); +}; + +const Example92 = (props: any) => { + return ( +
      +
      1 of 5
      + +
      50 of 135
      + +
      75 of 111
      + +
      463 of 500
      + + +
      Various (40) of 55
      + + 5 + 15 + 10 + 10 + +
      + ); +}; + +// --------------- Table +class Example93 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example94 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example95 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example96 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example97 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example98 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #First NameLast NameUsername
      1MarkOtto@mdo
      2JacobThornton@fat
      3Larrythe Bird@twitter
      + ); + } +} + +class Example99 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #Table headingTable headingTable headingTable headingTable headingTable heading
      1Table cellTable cellTable cellTable cellTable cellTable cell
      2Table cellTable cellTable cellTable cellTable cellTable cell
      3Table cellTable cellTable cellTable cellTable cellTable cell
      + ); + } +} + +class Example100 extends React.Component { + render() { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      #Table headingTable headingTable headingTable headingTable headingTable heading
      1Table cellTable cellTable cellTable cellTable cellTable cell
      2Table cellTable cellTable cellTable cellTable cellTable cell
      3Table cellTable cellTable cellTable cellTable cellTable cell
      + ); + } +} + +class Example101 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + activeTab: '1' + }; + } + + toggle(tab: string) { + if (this.state.activeTab !== tab) { + this.setState({ + activeTab: tab + }); + } + } + render() { + return ( +
      + + + + + +

      Tab 1 Contents

      + +
      +
      + + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + + + Special Title Treatment + With supporting text below as a natural lead-in to additional content. + + + + + +
      +
      + ); + } +} + +class Example102 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + tooltipOpen: false + }; + } + + toggle() { + this.setState({ + tooltipOpen: !this.state.tooltipOpen + }); + } + + render() { + return ( +
      +

      Somewhere in here is a tooltip.

      + + Hello world! + +
      + ); + } +} + +class Example103 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + tooltipOpen: false + }; + } + + toggle() { + this.setState({ + tooltipOpen: !this.state.tooltipOpen + }); + } + + render() { + return ( +
      +

      Sometimes you need to allow users to select text within a tooltip.

      + + Try to select this text! + +
      + ); + } +} + +class TooltipItem extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + tooltipOpen: false + }; + } + + toggle() { + this.setState({ + tooltipOpen: !this.state.tooltipOpen + }); + } + + render() { + return ( + + + + Tooltip Content! + + + ); + } +} + +class TooltipExampleMulti extends React.Component { + constructor(props: any) { + super(props); + + this.state = { + tooltips: [ + { + placement: 'top', + text: 'Top' + }, + { + placement: 'bottom', + text: 'Bottom' + }, + { + placement: 'left', + text: 'Left' + }, + { + placement: 'right', + text: 'Right' + } + ] + }; + } + + render() { + return ( +
      + {this.state.tooltips.map((tooltip: {placement: string; text: string; }, i: number) => { + return ; + })} +
      + ); + } +} + +function Example() { + return ( +
      +

      Somewhere in here is a tooltip.

      + + Hello world! + +
      + ); +} + +function Example104() { + const props = { + className: 'my-input', + style: { + borderColor: 'black', + } + }; + + return ( + + + + + + + + ); +} + +function Example105() { + return ( + + + + +
      + Item +
      +
      +
      + ); +} + +function Example106() { + return ( + + ); +} + +const CSSModuleExample = (props: any) => { + const cssModule = { + btn: 'hash' + }; + + return ( + + ); +}; + +class Example107 extends React.Component { + private input: HTMLInputElement; + + render() { + return { this.input = input; }} />; + } +} + +class Example108 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +class Example109 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +class Example110 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +class Example111 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +class Example112 extends React.Component { + constructor(props: any) { + super(props); + + this.toggle = this.toggle.bind(this); + this.state = { + isOpen: false + }; + } + toggle() { + this.setState({ + isOpen: !this.state.isOpen + }); + } + render() { + return ( +
      + + + reactstrap + + + + +
      + ); + } +} + +const Example113 = (props: any) => { + return ( +
      + + + Anim pariatur cliche reprehenderit, + enim eiusmod high life accusamus terry richardson ad squid. Nihil + anim keffiyeh helvetica, craft beer labore wes anderson cred + nesciunt sapiente ea proident. + + +
      + ); + }; diff --git a/types/reactstrap/v4/tsconfig.json b/types/reactstrap/v4/tsconfig.json new file mode 100644 index 0000000000..73578a9178 --- /dev/null +++ b/types/reactstrap/v4/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "jsx": "react", + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "reactstrap": ["reactstrap/v4"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "reactstrap-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/reactstrap/v4/tslint.json b/types/reactstrap/v4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/reactstrap/v4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 404fe5c444..55feba3ad6 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -654,6 +654,7 @@ export interface SectorProps { startAngle?: number; endAngle?: number; cornerRadius?: number; + fill?: string; onClick?: RechartsFunction; onMouseDown?: RechartsFunction; onMouseUp?: RechartsFunction; @@ -716,6 +717,7 @@ export interface TooltipProps { itemSorter?: ItemSorter; isAnimationActive?: boolean; animationBegin?: number; + animationDuration?: number; animationEasing?: AnimationEasingType; filterNull?: boolean; } diff --git a/types/recharts/recharts-tests.tsx b/types/recharts/recharts-tests.tsx index 9951fc775b..9783a264d5 100644 --- a/types/recharts/recharts-tests.tsx +++ b/types/recharts/recharts-tests.tsx @@ -1,37 +1,115 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import { CartesianGrid, Line, LineChart, XAxis, YAxis, Tooltip, ReferenceLine, ReferenceArea } from 'recharts'; +import { CartesianGrid, Line, LineChart, PieChart, Pie, Sector, XAxis, YAxis, Tooltip, ReferenceLine, ReferenceArea, ResponsiveContainer } from 'recharts'; -const Component = (props: {}) => { - const data = [ - {name: 'Page A', uv: 4000, pv: 2400, amt: 2400}, - {name: 'Page B', uv: 3000, pv: 1398, amt: 2210}, - {name: 'Page C', uv: 2000, pv: 9800, amt: 2290}, - {name: 'Page D', uv: 2780, pv: 3908, amt: 2000}, - {name: 'Page E', uv: 1890, pv: 4800, amt: 2181}, - {name: 'Page F', uv: 2390, pv: 3800, amt: 2500}, - {name: 'Page G', uv: 3490, pv: 4300, amt: 2100}, - ]; +interface ComponentState { + activeIndex: number; +} - return ( - - - - - - - - - - - ); -}; +class Component extends React.Component<{}, ComponentState> { + constructor(props: any) { + super(props); + this.state = { + activeIndex: 0 + }; + } -ReactDOM.render(, document.getElementById('app')); + render() { + const data = [ + { name: 'Page A', uv: 4000, pv: 2400, amt: 2400 }, + { name: 'Page B', uv: 3000, pv: 1398, amt: 2210 }, + { name: 'Page C', uv: 2000, pv: 9800, amt: 2290 }, + { name: 'Page D', uv: 2780, pv: 3908, amt: 2000 }, + { name: 'Page E', uv: 1890, pv: 4800, amt: 2181 }, + { name: 'Page F', uv: 2390, pv: 3800, amt: 2500 }, + { name: 'Page G', uv: 3490, pv: 4300, amt: 2100 }, + ]; + + const data2 = [ + { name: 'Group A', value: 400 }, + { name: 'Group B', value: 300 }, + { name: 'Group C', value: 300 }, + { name: 'Group D', value: 200 } + ]; + + const renderActiveShape = (props: any) => { + const RADIAN = Math.PI / 180; + const { cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle, + fill, payload, percent, value } = props; + const sin = Math.sin(-RADIAN * midAngle); + const cos = Math.cos(-RADIAN * midAngle); + const sx = cx + (outerRadius + 10) * cos; + const sy = cy + (outerRadius + 10) * sin; + const mx = cx + (outerRadius + 30) * cos; + const my = cy + (outerRadius + 30) * sin; + const ex = mx + (cos >= 0 ? 1 : -1) * 22; + const ey = my; + const textAnchor = cos >= 0 ? 'start' : 'end'; + + return ( + + {payload.name} + + + + + = 0 ? 1 : -1) * 12} y={ey} textAnchor={textAnchor} fill="#333">{`PV ${value}`} + = 0 ? 1 : -1) * 12} y={ey} dy={18} textAnchor={textAnchor} fill="#999"> + {`(Rate ${(percent * 100).toFixed(2)}%)`} + + + ); + }; + return ( + + + + + + + + + + + + + + + + ); + } +} + +ReactDOM.render(, document.getElementById('app')); diff --git a/types/redis/index.d.ts b/types/redis/index.d.ts index 13b7cbeb45..5f7e1d1e10 100644 --- a/types/redis/index.d.ts +++ b/types/redis/index.d.ts @@ -41,7 +41,7 @@ export interface ClientOpts { retry_unfulfilled_commands?: boolean; auth_pass?: string; password?: string; - db?: string; + db?: string | number; family?: string; rename_commands?: { [command: string]: string }; tls?: any; diff --git a/types/redux-auth-wrapper/index.d.ts b/types/redux-auth-wrapper/index.d.ts index 52bea44218..8734efeb75 100644 --- a/types/redux-auth-wrapper/index.d.ts +++ b/types/redux-auth-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mjrussell/redux-auth-wrapper // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { ComponentClass, StatelessComponent, ComponentType, ReactType } from "react"; diff --git a/types/redux-devtools/index.d.ts b/types/redux-devtools/index.d.ts index 6e51b2bf6d..ceb8abc246 100644 --- a/types/redux-devtools/index.d.ts +++ b/types/redux-devtools/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index 8020763db4..e964299ad3 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -16,15 +16,15 @@ export type Formatter = (value: any, name: string) => any; export type Parser = (value: any, name: string) => any; export type Validator = (value: any, allValues?: any, props?: any) => any; -interface EventHandler { +export interface EventHandler { (event: Event): void; } -interface EventOrValueHandler extends EventHandler { +export interface EventOrValueHandler extends EventHandler { (value: any): void; } -interface CommonFieldProps { +export interface CommonFieldProps { name: string; onBlur: EventOrValueHandler>; onChange: EventOrValueHandler>; @@ -33,8 +33,9 @@ interface CommonFieldProps { onFocus: EventHandler>; } -interface BaseFieldProps

      extends Partial { +export interface BaseFieldProps

      extends Partial { name: string; + label?: string; component?: ComponentType

      | "input" | "select" | "textarea", format?: Formatter | null; normalize?: Normalizer; @@ -53,7 +54,10 @@ export interface GenericField

      extends Component & P> { getRenderedComponent(): Component; } -type GenericFieldHTMLAttributes = InputHTMLAttributes | SelectHTMLAttributes | TextareaHTMLAttributes; +export type GenericFieldHTMLAttributes = + InputHTMLAttributes | + SelectHTMLAttributes | + TextareaHTMLAttributes; export class Field

      extends Component & P> implements GenericField

      { dirty: boolean; diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index dba9b95633..cde07c264c 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -14,6 +14,7 @@ import { WrappedFieldProps, Fields, GenericFields, + BaseFieldProps, WrappedFieldsProps, FieldArray, GenericFieldArray, diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts index cf943129d8..6df38927e7 100644 --- a/types/redux-form/v6/index.d.ts +++ b/types/redux-form/v6/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { ComponentClass, diff --git a/types/redux-storage/redux-storage-tests.ts b/types/redux-storage/redux-storage-tests.ts index 4e84468a64..b8d9ccdbb0 100644 --- a/types/redux-storage/redux-storage-tests.ts +++ b/types/redux-storage/redux-storage-tests.ts @@ -23,7 +23,7 @@ const initialStateLoader = createLoader(storageEngine); const storageMiddleware = createMiddleware(storageEngine, [], []); -const store = applyMiddleware(storageMiddleware)(createStore)(enhancedReducer); +const store = applyMiddleware(storageMiddleware)(createStore)(enhancedReducer); initialStateLoader(store).then(() => { // render app @@ -33,7 +33,7 @@ initialStateLoader(store).then(() => { // Test for React Native Async Storage engine const storageEngineReactNative = createReactNativeAsyncStorageEngine("test"); const storageMiddlewareReactNative = createMiddleware(storageEngine); -const storeReactNative = applyMiddleware(storageMiddlewareReactNative)(createStore)(enhancedReducer); +const storeReactNative = applyMiddleware(storageMiddlewareReactNative)(createStore)(enhancedReducer); initialStateLoader(storeReactNative).then(() => { // render app }) diff --git a/types/request-promise-native/index.d.ts b/types/request-promise-native/index.d.ts index 02d1fc1520..29e0e0f72c 100644 --- a/types/request-promise-native/index.d.ts +++ b/types/request-promise-native/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/request/request-promise-native // Definitions by: Gustavo Henke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import request = require('request'); import http = require('http'); diff --git a/types/requestretry/index.d.ts b/types/requestretry/index.d.ts index 73078ad71e..3963ce2c17 100644 --- a/types/requestretry/index.d.ts +++ b/types/requestretry/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Eric Byers // Andrew Throener // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/response-time/index.d.ts b/types/response-time/index.d.ts index 2dd6533403..8a06ba04fd 100644 --- a/types/response-time/index.d.ts +++ b/types/response-time/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/response-time // Definitions by: Uros Smolnik , TonyYang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /* =================== USAGE =================== diff --git a/types/restify-cookies/index.d.ts b/types/restify-cookies/index.d.ts index 8f00f97538..a4ab9f5f47 100644 --- a/types/restify-cookies/index.d.ts +++ b/types/restify-cookies/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/nathschmidt/restify-cookies // Definitions by: weekens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as restify from 'restify'; diff --git a/types/restify-plugins/index.d.ts b/types/restify-plugins/index.d.ts index 05a289c529..4f495ce593 100644 --- a/types/restify-plugins/index.d.ts +++ b/types/restify-plugins/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/restify/plugins // Definitions by: Костя Третяк // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { RequestHandler, Server, Request, Response, Route } from 'restify'; import Logger = require('bunyan'); @@ -14,9 +15,6 @@ export namespace pre { */ function context(): RequestHandler; - /** - * - */ function dedupeSlashes(): RequestHandler; /** @@ -73,9 +71,6 @@ export interface AuditLoggerOptions { */ printLog?: boolean; - /** - * - */ body?: boolean; } @@ -165,14 +160,8 @@ export interface BodyParserOptions { */ rejectUnknown?: boolean; - /** - * - */ reviver?: any; - /** - * - */ maxFieldsSize?: number; } @@ -342,9 +331,6 @@ export interface MetricsCallback { */ err: Error; - /** - * - */ metrics: MetricsCallbackOptions; req: Request; diff --git a/types/restling/index.d.ts b/types/restling/index.d.ts index 2a06d6c3aa..fc6c75e6cd 100644 --- a/types/restling/index.d.ts +++ b/types/restling/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/lucasfeliciano/restling // Definitions by: Alessandro vergani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Promise from "bluebird"; import * as Restler from "restler"; diff --git a/types/run-sequence/tsconfig.json b/types/run-sequence/tsconfig.json index 33e3e06aff..412efd6845 100644 --- a/types/run-sequence/tsconfig.json +++ b/types/run-sequence/tsconfig.json @@ -12,11 +12,6 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ - "q/v0" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/saml2-js/index.d.ts b/types/saml2-js/index.d.ts index 5ea6fcea07..d0a66d0246 100644 --- a/types/saml2-js/index.d.ts +++ b/types/saml2-js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Clever/saml2 // Definitions by: horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 declare module "saml2-js" { diff --git a/types/selectize/index.d.ts b/types/selectize/index.d.ts index 449d09ce52..042e628e12 100644 --- a/types/selectize/index.d.ts +++ b/types/selectize/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/brianreavis/selectize.js // Definitions by: Adi Dahiya , Natalie Bausch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace Selectize { // see https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md @@ -11,6 +12,11 @@ declare namespace Selectize { // General // ------------------------------------------------------------------------------------------------------------ + /** + * An array of the initial selected values. By default this is populated from the original input element. + */ + items?: T[]; + /** * The string to separate items by. This option is only used when Selectize is instantiated from a * element. @@ -94,6 +100,13 @@ declare namespace Selectize { */ hideSelected?: boolean; + /** + * If true, the dropdown will be closed after a selection is made. + * + * Default: false + */ + closeAfterSelect?: boolean; + /** * If true, Selectize will treat any options with a "" value like normal. This defaults to false to * accomodate the common