diff --git a/package.json b/package.json index b12e3fe2eb..db67595b77 100644 --- a/package.json +++ b/package.json @@ -23,8 +23,5 @@ "devDependencies": { "dtslint": "github:Microsoft/dtslint#production", "types-publisher": "Microsoft/types-publisher#production" - }, - "dependencies": { - "@egjs/axes": "^2.0.0" } } diff --git a/scripts/fix-tslint.ts b/scripts/fix-tslint.ts index 419ebcd0de..36cb23ebbd 100644 --- a/scripts/fix-tslint.ts +++ b/scripts/fix-tslint.ts @@ -39,7 +39,16 @@ function fix(config: any): any { const out: any = {}; for (const key in config) { let value = config[key]; - out[key] = value; + out[key] = key === "rules" ? fixRules(value) : value; } return out; } + +function fixRules(rules: any): any { + const out: any = {}; + for (const key in rules) { + out[key] = rules[key]; + } + return out; +} + diff --git a/scripts/material-ui/generate.js b/scripts/material-ui/generate.js deleted file mode 100644 index 06e6983a44..0000000000 --- a/scripts/material-ui/generate.js +++ /dev/null @@ -1,147 +0,0 @@ -const {get} = require('https') -const {readdir, readFile, writeFile} = require('fs') -const {join, extname, basename, dirname, relative} = require('path') - -const token = process.env.GITHUB_ACCESS_TOKEN || '' - -const toMixedCase = (name) => { - let dist = name[0].toUpperCase() - for (let i = 1; i < name.length; i++) { - const c = name[i] - if (c !== '-') { - dist += c - continue - } - i++ - dist += name[i].toUpperCase() - } - return dist -} - -const github = (path) => new Promise((resolve, reject) => { - get({ - headers: {'user-agent': 'DefinitelyTyped/material-ui/generate'}, - host: 'api.github.com', - path, - }, (res) => { - if ((res.statusCode / 100 >> 0) != 2) { - reject(`GitHub response: ${res.statusCode} ${res.statusMessage}`) - return - } - let data = ''; - res - .on('data', (chunk) => data += chunk) - .on('end', () => resolve(JSON.parse(data))) - }).on('error', reject) -}) - -const categories = () => github(`/repos/callemall/material-ui/contents/src/svg-icons?ref=master&access_token=${token}`) - -const contents = (path) => github(`/repos/callemall/material-ui/contents/${path}?ref=master&access_token=${token}`) - -const collator = new Intl.Collator() - -const resolvePath = (filename) => join(__dirname, '../../types/material-ui', filename) - -const readText = (filename) => new Promise((resolve, reject) => { - readFile(resolvePath(filename), 'utf8', (err, data) => { - if (err != null) { - reject(err) - return - } - resolve(data) - }) -}) - -const writeText = (filename, text) => new Promise((resolve, reject) => { - writeFile(resolvePath(filename), text, 'utf8', (err) => { - if (err != null) { - reject(err) - return - } - resolve() - }) -}) - -const inject = (content) => { - content.category = this.name - return content -} - -const rMark = /(\/{2} \{{3})[\s\S]*?(\/{2} \}{3})/g - -categories() - .then((cats) => Promise.all(Array.prototype.map.call(cats, (cat) => contents(cat.path) - .then((cons) => Array.prototype.map.call(cons, (con) => { - con.category = cat.name - return con - })) - ))) - .then((contentsList) => Array.prototype.concat.apply([], contentsList) - .map((content) => { - const {path} = content - const name = basename(path, extname(path)) - content.id = join(relative('src', dirname(path)), name) - content.className = toMixedCase(content.category) + toMixedCase(name) - return content - }) - .sort((a, b) => collator.compare(a.id, b.id)) - .reduce((prev, content) => { - const {dts, test} = prev - dts.individuals.push(`declare module 'material-ui/${content.id}' { - export import ${content.className} = __MaterialUI.SvgIcon; - export default ${content.className}; -}`) - dts.summarizeds.push(` export import ${content.className} = __MaterialUI.SvgIcon; // require('material-ui/${content.id}');`) - - test.individuals.push(`import _${content.className} from 'material-ui/${content.id}';`) - test.summarizeds.push(` ${content.className},`) - return prev - }, { - dts: {individuals: [], summarizeds: []}, - test: {individuals: [], summarizeds: []}, - }) -) - .then(({dts, test}) => { - return Promise.all([ - (() => { - const {individuals, summarizeds} = dts - const file = 'index.d.ts' - let index = 0 - return readText(file) - .then((script) => writeText(file, script.replace(rMark, (_, p1, p2) => { - let text = '' - switch (index) { - case 0: - text = individuals.join('\n\n') - break - case 1: - text = summarizeds.join('\n') - break - } - index++ - return p1 + '\n' + text + '\n' + p2 - }))) - })(), - (() => { - const {individuals, summarizeds} = test - const file = join('material-ui-tests.tsx') - let index = 0 - return readText(file) - .then((script) => writeText(file, script.replace(rMark, (_, p1, p2) => { - let text = '' - switch (index) { - case 0: - text = individuals.join('\n') - break - case 1: - text = summarizeds.join('\n') - break - } - index++ - return p1 + '\n' + text + '\n' + p2 - }))) - })(), - ]) - }) - .catch((err) => console.error(err)) diff --git a/types/ably/tslint.json b/types/ably/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/ably/tslint.json +++ b/types/ably/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/adone/tslint.json b/types/adone/tslint.json index f0ae61d2bf..ef323bd7a5 100644 --- a/types/adone/tslint.json +++ b/types/adone/tslint.json @@ -5,9 +5,11 @@ "align": false, "no-namespace": false, "strict-export-declare-modifiers": false, + "no-any-union": false, "no-boolean-literal-compare": false, "no-mergeable-namespace": false, "no-single-declare-module": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "unified-signatures": false, "space-before-function-paren": false diff --git a/types/aframe/tslint.json b/types/aframe/tslint.json index d88586e5bd..71ee04c4e1 100644 --- a/types/aframe/tslint.json +++ b/types/aframe/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/angular-resource/tslint.json b/types/angular-resource/tslint.json index ff19c22fa3..b4b1464296 100644 --- a/types/angular-resource/tslint.json +++ b/types/angular-resource/tslint.json @@ -8,6 +8,7 @@ "no-object-literal-type-assertion": false, "ban-types": false, "space-before-function-paren": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/arcgis-to-geojson-utils/tslint.json b/types/arcgis-to-geojson-utils/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/arcgis-to-geojson-utils/tslint.json +++ b/types/arcgis-to-geojson-utils/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index f5b9e76f81..aef18b665b 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,25 +1,24 @@ - // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; -var args: any; +let args: any; -var simpleExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse example', +const simpleExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse example', }); simpleExample.addArgument( - ['-f', '--foo'], - { - help: 'foo bar', - } + ['-f', '--foo'], + { + help: 'foo bar', + } ); simpleExample.addArgument( - ['-b', '--bar'], - { - help: 'bar foo', - } + ['-b', '--bar'], + { + help: 'bar foo', + } ); simpleExample.printHelp(); @@ -35,13 +34,10 @@ args = simpleExample.parseArgs('--foo 5 --bar 6'.split(' ')); console.dir(args); console.log('-----------'); - - - -var choicesExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse examples: choice' +const choicesExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: choice' }); choicesExample.addArgument(['foo'], { choices: 'abc' }); @@ -55,56 +51,53 @@ console.log('-----------'); // choicesExample.parseArgs(['X']); // console.dir(args); - - - -var constantExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse examples: constant' +const constantExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: constant' }); constantExample.addArgument( - ['-a'], - { - action: 'storeConst', - dest: 'answer', - help: 'store constant', - constant: 42 - } + ['-a'], + { + action: 'storeConst', + dest: 'answer', + help: 'store constant', + constant: 42 + } ); constantExample.addArgument( - ['--str'], - { - action: 'appendConst', - dest: 'types', - help: 'append constant "str" to types', - constant: 'str' - } + ['--str'], + { + action: 'appendConst', + dest: 'types', + help: 'append constant "str" to types', + constant: 'str' + } ); constantExample.addArgument( - ['--int'], - { - action: 'appendConst', - dest: 'types', - help: 'append constant "int" to types', - constant: 'int' - } + ['--int'], + { + action: 'appendConst', + dest: 'types', + help: 'append constant "int" to types', + constant: 'int' + } ); constantExample.addArgument( - ['--true'], - { - action: 'storeTrue', - help: 'store true constant' - } + ['--true'], + { + action: 'storeTrue', + help: 'store true constant' + } ); constantExample.addArgument( - ['--false'], - { - action: 'storeFalse', - help: 'store false constant' - } + ['--false'], + { + action: 'storeFalse', + help: 'store false constant' + } ); constantExample.printHelp(); @@ -113,27 +106,24 @@ console.log('-----------'); args = constantExample.parseArgs('-a --str --int --true'.split(' ')); console.dir(args); - - - -var nargsExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse examples: nargs' +const nargsExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: nargs' }); nargsExample.addArgument( - ['-f', '--foo'], - { - help: 'foo bar', - nargs: 1 - } + ['-f', '--foo'], + { + help: 'foo bar', + nargs: 1 + } ); nargsExample.addArgument( - ['-b', '--bar'], - { - help: 'bar foo', - nargs: '*' - } + ['-b', '--bar'], + { + help: 'bar foo', + nargs: '*' + } ); nargsExample.printHelp(); @@ -145,40 +135,34 @@ console.log('-----------'); args = nargsExample.parseArgs('--bar b c f --foo a'.split(' ')); console.dir(args); - - - -var parent_parser = new ArgumentParser({ addHelp: false }); +const parent_parser = new ArgumentParser({ addHelp: false }); // note addHelp:false to prevent duplication of the -h option parent_parser.addArgument( - ['--parent'], - { type: 'int', help: 'parent' } + ['--parent'], + { type: 'int', help: 'parent' } ); -var foo_parser = new ArgumentParser({ - parents: [parent_parser], - description: 'child1' +const foo_parser = new ArgumentParser({ + parents: [parent_parser], + description: 'child1' }); foo_parser.addArgument(['foo']); args = foo_parser.parseArgs(['--parent', '2', 'XXX']); console.log(args); -var bar_parser = new ArgumentParser({ - parents: [parent_parser], - description: 'child2' +const bar_parser = new ArgumentParser({ + parents: [parent_parser], + description: 'child2' }); bar_parser.addArgument(['--bar']); args = bar_parser.parseArgs(['--bar', 'YYY']); console.log(args); - - - -var prefixCharsExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse examples: prefix_chars', - prefixChars: '-+' +const prefixCharsExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: prefix_chars', + prefixChars: '-+' }); prefixCharsExample.addArgument(['+f', '++foo']); prefixCharsExample.addArgument(['++bar'], { action: 'storeTrue' }); @@ -193,39 +177,36 @@ console.dir(args); args = prefixCharsExample.parseArgs(['++foo', '2', '++bar']); console.dir(args); - - - -var subparserExample = new ArgumentParser({ - version: '0.0.1', - addHelp: true, - description: 'Argparse examples: sub-commands' +const subparserExample = new ArgumentParser({ + version: '0.0.1', + addHelp: true, + description: 'Argparse examples: sub-commands' }); -var subparsers = subparserExample.addSubparsers({ - title: 'subcommands', - dest: "subcommand_name" +const subparsers = subparserExample.addSubparsers({ + title: 'subcommands', + dest: "subcommand_name" }); -var bar = subparsers.addParser('c1', { addHelp: true, help: 'c1 help' }); +let bar = subparsers.addParser('c1', { addHelp: true, help: 'c1 help' }); bar.addArgument( - ['-f', '--foo'], - { - action: 'store', - help: 'foo3 bar3' - } + ['-f', '--foo'], + { + action: 'store', + help: 'foo3 bar3' + } ); -var bar = subparsers.addParser( - 'c2', - { aliases: ['co'], addHelp: true, help: 'c2 help' } +bar = subparsers.addParser( + 'c2', + { aliases: ['co'], addHelp: true, help: 'c2 help' } ); bar.addArgument( - ['-b', '--bar'], - { - action: 'store', - type: 'int', - help: 'foo3 bar3' - } + ['-b', '--bar'], + { + action: 'store', + type: 'int', + help: 'foo3 bar3' + } ); subparserExample.printHelp(); console.log('-----------'); @@ -241,66 +222,51 @@ console.dir(args); console.log('-----------'); subparserExample.parseArgs(['c1', '-h']); - - - -var functionExample = new ArgumentParser({ description: 'Process some integers.' }); +const functionExample = new ArgumentParser({ description: 'Process some integers.' }); function sum(arr: number[]) { - return arr.reduce(function(a, b) { - return a + b; - }, 0); + return arr.reduce((a, b) => a + b, 0); } function max(arr: number[]) { - return Math.max.apply(Math, arr); + return Math.max.apply(Math, arr); } - functionExample.addArgument(['integers'], { - metavar: 'N', - type: 'int', - nargs: '+', - help: 'an integer for the accumulator' + metavar: 'N', + type: 'int', + nargs: '+', + help: 'an integer for the accumulator' }); functionExample.addArgument(['--sum'], { - dest: 'accumulate', - action: 'storeConst', - constant: sum, - defaultValue: max, - help: 'sum the integers (default: find the max)' + dest: 'accumulate', + action: 'storeConst', + constant: sum, + defaultValue: max, + help: 'sum the integers (default: find the max)' }); args = functionExample.parseArgs('--sum 1 2 -1'.split(' ')); console.log(args.accumulate(args.integers)); - - - -var formatterExample = new ArgumentParser({ - prog: 'PROG', - formatterClass: RawDescriptionHelpFormatter, - description: 'Keep the formatting\n' + - ' exactly as it is written\n' + - '\n' + - 'here\n' +const formatterExample = new ArgumentParser({ + prog: 'PROG', + formatterClass: RawDescriptionHelpFormatter, + description: `Keep the formatting\nexactly as it is written\n\nhere\n`, }); formatterExample.addArgument(['--foo'], { - help: ' foo help should not\n' + - ' retain this odd formatting' + help: `foo help should not\nretain this odd formatting`, }); formatterExample.addArgument(['spam'], { - 'help': 'spam help' + help: 'spam help', }); -var group = formatterExample.addArgumentGroup({ - title: 'title', - description: ' This text\n' + - ' should be indented\n' + - ' exactly like it is here\n' +const group = formatterExample.addArgumentGroup({ + title: 'title', + description: `This text\nshould be indented\nexactly like it is here\n`, }); group.addArgument(['--bar'], { - help: 'bar help' + help: 'bar help' }); formatterExample.printHelp(); diff --git a/types/argparse/index.d.ts b/types/argparse/index.d.ts index 2661b01c12..f19aadbe96 100644 --- a/types/argparse/index.d.ts +++ b/types/argparse/index.d.ts @@ -1,31 +1,39 @@ -// Type definitions for argparse v1.0.3 +// Type definitions for argparse 1.0 // Project: https://github.com/nodeca/argparse // Definitions by: Andrew Schurman +// Tomasz Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 - -export declare class ArgumentParser extends ArgumentGroup { +export class ArgumentParser extends ArgumentGroup { constructor(options?: ArgumentParserOptions); - addSubparsers(options?: SubparserOptions): SubParser; - parseArgs(args?: string[], ns?: Namespace | Object): any; + parseArgs(args?: string[], ns?: Namespace | object): any; printUsage(): void; printHelp(): void; formatUsage(): string; formatHelp(): string; - parseKnownArgs(args?: string[], ns?: Namespace | Object): any[]; + parseKnownArgs(args?: string[], ns?: Namespace | object): any[]; convertArgLineToArg(argLine: string): string[]; exit(status: number, message: string): void; error(err: string | Error): void; } -interface Namespace { } +export class Namespace { + constructor(options: object); + get(key: K, defaultValue?: D): this[K] | D; + isset(key: K): boolean; + set(key: K, value: V): this; + set(key: K, value: V): this & Record; + set(obj: K): this & K; + unset(key: K, defaultValue?: D): this[K] | D; +} -declare class SubParser { +export class SubParser { addParser(name: string, options?: SubArgumentParserOptions): ArgumentParser; } -declare class ArgumentGroup { +export class ArgumentGroup { addArgument(args: string[], options?: ArgumentOptions): void; addArgumentGroup(options?: ArgumentGroupOptions): ArgumentGroup; addMutuallyExclusiveGroup(options?: { required: boolean }): ArgumentGroup; @@ -33,7 +41,7 @@ declare class ArgumentGroup { getDefault(dest: string): any; } -interface SubparserOptions { +export interface SubparserOptions { title?: string; description?: string; prog?: string; @@ -44,12 +52,12 @@ interface SubparserOptions { metavar?: string; } -interface SubArgumentParserOptions extends ArgumentParserOptions { +export interface SubArgumentParserOptions extends ArgumentParserOptions { aliases?: string[]; help?: string; } -interface ArgumentParserOptions { +export interface ArgumentParserOptions { description?: string; epilog?: string; addHelp?: boolean; @@ -62,26 +70,27 @@ interface ArgumentParserOptions { version?: string; } -interface ArgumentGroupOptions { +export interface ArgumentGroupOptions { prefixChars?: string; argumentDefault?: any; title?: string; description?: string; } -export declare class HelpFormatter { } -export declare class ArgumentDefaultsHelpFormatter { } -export declare class RawDescriptionHelpFormatter { } -export declare class RawTextHelpFormatter { } +export class HelpFormatter { } +export class ArgumentDefaultsHelpFormatter { } +export class RawDescriptionHelpFormatter { } +export class RawTextHelpFormatter { } -interface ArgumentOptions { +export interface ArgumentOptions { action?: string; optionStrings?: string[]; dest?: string; nargs?: string | number; constant?: any; defaultValue?: any; - type?: string | Function; + // type may be a string (primitive) or a Function (constructor) + type?: string | Function; // tslint:disable-line:ban-types choices?: string | string[]; required?: boolean; help?: string; diff --git a/types/argparse/tslint.json b/types/argparse/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/argparse/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 3c576e2dc8..7f01a53e3a 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -205,7 +205,7 @@ declare namespace autobahn { type DeferFactory = () => When.Promise; - type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; + type OnChallengeHandler = (session: Session, method: string, extra: any) => string; interface IConnectionOptions { use_es6_promises?: boolean; diff --git a/types/awesomplete/tslint.json b/types/awesomplete/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/awesomplete/tslint.json +++ b/types/awesomplete/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/bittorrent-protocol/tslint.json b/types/bittorrent-protocol/tslint.json index dfea11be1a..62d2486032 100644 --- a/types/bittorrent-protocol/tslint.json +++ b/types/bittorrent-protocol/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "no-misused-new": false + // TODOs + "no-misused-new": false, + "no-any-union": false } } diff --git a/types/bluebird-global/tslint.json b/types/bluebird-global/tslint.json index b936b5e2b9..1d81af2349 100644 --- a/types/bluebird-global/tslint.json +++ b/types/bluebird-global/tslint.json @@ -5,6 +5,7 @@ "no-empty-interface": false, "array-type": false, "unified-signatures": false, - "ban-types": false + "ban-types": false, + "no-unnecessary-generics": false } } diff --git a/types/botvs/tslint.json b/types/botvs/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/botvs/tslint.json +++ b/types/botvs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/bunnymq/tslint.json b/types/bunnymq/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/bunnymq/tslint.json +++ b/types/bunnymq/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/chai-as-promised/chai-as-promised-tests.ts b/types/chai-as-promised/chai-as-promised-tests.ts index 7e422521aa..2157f0cc3c 100644 --- a/types/chai-as-promised/chai-as-promised-tests.ts +++ b/types/chai-as-promised/chai-as-promised-tests.ts @@ -26,6 +26,7 @@ thenableNum = chai.expect(thenableNum).to.notify(() => console.log('done')); // BDD API (should) thenableNum = thenableNum.should.be.fulfilled; thenableNum = thenableNum.should.eventually.deep.equal(3); +thenableNum = thenableNum.should.eventually.become(3); thenableNum = thenableNum.should.become(3); thenableNum = thenableNum.should.be.rejected; thenableNum = thenableNum.should.be.rejectedWith(Error); diff --git a/types/chai-as-promised/index.d.ts b/types/chai-as-promised/index.d.ts index 0dde8837dd..459758aa55 100644 --- a/types/chai-as-promised/index.d.ts +++ b/types/chai-as-promised/index.d.ts @@ -1,6 +1,10 @@ -// Type definitions for chai-as-promised +// Type definitions for chai-as-promised 7.1.0 // Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 , Yuki Kokubun , Leonard Thieu +// Definitions by: jt000 , +// Yuki Kokubun , +// Leonard Thieu , +// Mike Lazer-Walker , +// Matt Bishop // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -25,22 +29,25 @@ declare namespace Chai { become(expected: any): PromisedAssertion; fulfilled: PromisedAssertion; rejected: PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; + rejectedWith: PromisedThrow; notify(fn: Function): PromisedAssertion; } // Eventually does not have .then(), but PromisedAssertion have. interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { // From chai-as-promised - become(expected: PromiseLike): PromisedAssertion; + become(expected: any): PromisedAssertion; fulfilled: PromisedAssertion; rejected: PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; + rejectedWith: PromisedThrow; notify(fn: Function): PromisedAssertion; // From chai not: PromisedAssertion; deep: PromisedDeep; + ordered: PromisedOrdered; + nested: PromisedNested; + any: PromisedKeyFilter; all: PromisedKeyFilter; a: PromisedTypeComparison; an: PromisedTypeComparison; @@ -51,6 +58,7 @@ declare namespace Chai { false: PromisedAssertion; null: PromisedAssertion; undefined: PromisedAssertion; + NaN: PromisedAssertion; exist: PromisedAssertion; empty: PromisedAssertion; arguments: PromisedAssertion; @@ -63,20 +71,36 @@ declare namespace Chai { property: PromisedProperty; ownProperty: PromisedOwnProperty; haveOwnProperty: PromisedOwnProperty; + ownPropertyDescriptor: PromisedOwnPropertyDescriptor; + haveOwnPropertyDescriptor: PromisedOwnPropertyDescriptor; length: PromisedLength; lengthOf: PromisedLength; - match(regexp: RegExp | string, message?: string): PromisedAssertion; + match: PromisedMatch; + matches: PromisedMatch; string(string: string, message?: string): PromisedAssertion; keys: PromisedKeys; key(string: string): PromisedAssertion; throw: PromisedThrow; throws: PromisedThrow; Throw: PromisedThrow; - respondTo(method: string, message?: string): PromisedAssertion; + respondTo: PromisedRespondTo; + respondsTo: PromisedRespondTo; itself: PromisedAssertion; - satisfy(matcher: Function, message?: string): PromisedAssertion; - closeTo(expected: number, delta: number, message?: string): PromisedAssertion; + satisfy: PromisedSatisfy; + satisfies: PromisedSatisfy; + closeTo: PromisedCloseTo; + approximately: PromisedCloseTo; members: PromisedMembers; + increase: PromisedPropertyChange; + increases: PromisedPropertyChange; + decrease: PromisedPropertyChange; + decreases: PromisedPropertyChange; + change: PromisedPropertyChange; + changes: PromisedPropertyChange; + extensible: PromisedAssertion; + sealed: PromisedAssertion; + frozen: PromisedAssertion; + oneOf(list: any[], message?: string): PromisedAssertion; } interface PromisedAssertion extends Eventually, PromiseLike { @@ -99,6 +123,8 @@ declare namespace Chai { at: PromisedAssertion; of: PromisedAssertion; same: PromisedAssertion; + but: PromisedAssertion; + does: PromisedAssertion; } interface PromisedNumericComparison { @@ -129,10 +155,28 @@ declare namespace Chai { (constructor: Object, message?: string): PromisedAssertion; } - interface PromisedDeep { - equal: PromisedEqual; + interface PromisedCloseTo { + (expected: number, delta: number, message?: string): PromisedAssertion; + } + + interface PromisedNested { include: PromisedInclude; property: PromisedProperty; + members: PromisedMembers; + } + + interface PromisedDeep { + equal: PromisedEqual; + equals: PromisedEqual; + eq: PromisedEqual; + include: PromisedInclude; + property: PromisedProperty; + members: PromisedMembers; + ordered: PromisedOrdered + } + + interface PromisedOrdered { + members: PromisedMembers; } interface PromisedKeyFilter { @@ -151,6 +195,11 @@ declare namespace Chai { (name: string, message?: string): PromisedAssertion; } + interface PromisedOwnPropertyDescriptor { + (name: string, descriptor: PropertyDescriptor, message?: string): PromisedAssertion; + (name: string, message?: string): PromisedAssertion; + } + interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { (length: number, message?: string): PromisedAssertion; } @@ -160,13 +209,21 @@ declare namespace Chai { (value: string, message?: string): PromisedAssertion; (value: number, message?: string): PromisedAssertion; keys: PromisedKeys; + deep: PromisedDeep; + ordered: PromisedOrdered; members: PromisedMembers; + any: PromisedKeyFilter; all: PromisedKeyFilter; } + interface PromisedMatch { + (regexp: RegExp | string, message?: string): PromisedAssertion; + } + interface PromisedKeys { (...keys: string[]): PromisedAssertion; (keys: any[]): PromisedAssertion; + (keys: Object): PromisedAssertion; } interface PromisedThrow { @@ -179,10 +236,22 @@ declare namespace Chai { (constructor: Function, expected?: RegExp, message?: string): PromisedAssertion; } + interface PromisedRespondTo { + (method: string, message?: string): PromisedAssertion; + } + + interface PromisedSatisfy { + (matcher: Function, message?: string): PromisedAssertion; + } + interface PromisedMembers { (set: any[], message?: string): PromisedAssertion; } + interface PromisedPropertyChange { + (object: Object, property: string, message?: string): PromisedAssertion; + } + // For Assert API interface Assert { eventually: PromisedAssert; @@ -198,7 +267,9 @@ declare namespace Chai { export interface PromisedAssert { fail(actual?: any, expected?: any, msg?: string, operator?: string): PromiseLike; + isOk(val: any, msg?: string): PromiseLike; ok(val: any, msg?: string): PromiseLike; + isNotOk(val: any, msg?: string): PromiseLike; notOk(val: any, msg?: string): PromiseLike; equal(act: any, exp: any, msg?: string): PromiseLike; @@ -210,12 +281,26 @@ declare namespace Chai { deepEqual(act: any, exp: any, msg?: string): PromiseLike; notDeepEqual(act: any, exp: any, msg?: string): PromiseLike; + isAbove(val: number, above: number, msg?: string): PromiseLike; + isAtLeast(val: number, atLeast: number, msg?: string): PromiseLike; + isAtBelow(val: number, below: number, msg?: string): PromiseLike; + isAtMost(val: number, atMost: number, msg?: string): PromiseLike; + isTrue(val: any, msg?: string): PromiseLike; isFalse(val: any, msg?: string): PromiseLike; + isNotTrue(val: any, msg?: string): PromiseLike; + isNotFalse(val: any, msg?: string): PromiseLike; + isNull(val: any, msg?: string): PromiseLike; isNotNull(val: any, msg?: string): PromiseLike; + isNaN(val: any, msg?: string): PromiseLike; + isNotNaN(val: any, msg?: string): PromiseLike; + + exists(val: any, msg?: string): PromiseLike; + notExists(val: any, msg?: string): PromiseLike; + isUndefined(val: any, msg?: string): PromiseLike; isDefined(val: any, msg?: string): PromiseLike; @@ -287,10 +372,46 @@ declare namespace Chai { operator(val: any, operator: string, val2: any, msg?: string): PromiseLike; closeTo(act: number, exp: number, delta: number, msg?: string): PromiseLike; + approximately(act: number, exp: number, delta: number, msg?: string): PromiseLike; sameMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + sameDeepMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + sameOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + notSameOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + sameDeepOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + notSameDeepOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + includeOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + notIncludeOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + includeDeepOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + notIncludeDeepOrderedMembers(set1: any[], set2: any[], msg?: string): PromiseLike; includeMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + includeDeepMembers(set1: any[], set2: any[], msg?: string): PromiseLike; + + oneOf(val: any, list: any[], msg?: string): PromiseLike; + + changes(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; + doesNotChange(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; + increases(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; + doesNotIncrease(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; + decreases(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; + doesNotDecrease(modifier: Function, obj: Object, property: string, msg?: string): PromiseLike; ifError(val: any, msg?: string): PromiseLike; + + isExtensible(obj: Object, msg?: string): PromiseLike; + isNotExtensible(obj: Object, msg?: string): PromiseLike; + + isSealed(obj: Object, msg?: string): PromiseLike; + sealed(obj: Object, msg?: string): PromiseLike; + isNotSealed(obj: Object, msg?: string): PromiseLike; + notSealed(obj: Object, msg?: string): PromiseLike; + + isFrozen(obj: Object, msg?: string): PromiseLike; + frozen(obj: Object, msg?: string): PromiseLike; + isNotFrozen(obj: Object, msg?: string): PromiseLike; + notFrozen(obj: Object, msg?: string): PromiseLike; + + isEmpty(val: any, msg?: string): PromiseLike; + isNotEmpty(val: any, msg?: string): PromiseLike; } } diff --git a/types/chai-http/chai-http-tests.ts b/types/chai-http/chai-http-tests.ts index 7c1c7a6b42..f4f65cae7b 100644 --- a/types/chai-http/chai-http-tests.ts +++ b/types/chai-http/chai-http-tests.ts @@ -41,6 +41,16 @@ chai.request(app) .get('/search') .query({ name: 'foo', limit: 10 }); +chai.request(app) + .get('/download') + .buffer() + .parse((res, cb) => { + let data = ''; + res.setEncoding('binary'); + res.on('data', (chunk: any) => { data += chunk; }); + res.on('end', () => { cb(undefined, new Buffer(data, 'binary')); }); + }); + chai.request(app) .put('/user/me') .send({ passsword: '123', confirmPassword: '123' }) diff --git a/types/chai-http/index.d.ts b/types/chai-http/index.d.ts index f0957cc454..6a9404c9da 100644 --- a/types/chai-http/index.d.ts +++ b/types/chai-http/index.d.ts @@ -49,6 +49,8 @@ declare global { type: string; status: number; text: string; + setEncoding(encoding: string): void; + on(event: string, fn: (...args: any[]) => void): void; } interface Request extends FinishedRequest { @@ -59,6 +61,7 @@ declare global { auth(user: string, name: string): Request; field(name: string, val: string): Request; buffer(): Request; + parse(fn: (res: Response, cb: (e?: Error, r?: any) => void) => void): Request; end(callback?: (err: any, res: Response) => void): FinishedRequest; } diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f04fbc1119..607f6924f8 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -4,15 +4,14 @@ // Fabien Lavocat // KentarouTakeda // Larry Bahr +// Daniel Luz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - declare class Chart { static readonly Chart: typeof Chart; constructor( - context: string | JQuery | CanvasRenderingContext2D | HTMLCanvasElement | string[] | CanvasRenderingContext2D[] | HTMLCanvasElement[], + context: string | CanvasRenderingContext2D | HTMLCanvasElement | ArrayLike, options: Chart.ChartConfiguration ); config: Chart.ChartConfiguration; @@ -83,6 +82,8 @@ declare namespace Chart { type ScaleType = 'category' | 'linear' | 'logarithmic' | 'time' | 'radialLinear'; + type PointStyle = 'circle' | 'cross' | 'crossRot' | 'dash' | 'line' | 'rect' | 'rectRounded' | 'rectRot' | 'star' | 'triangle'; + type PositionType = 'left' | 'right' | 'top' | 'bottom'; interface ChartArea { @@ -175,7 +176,7 @@ declare namespace Chart { interface ChartTitleOptions { display?: boolean; - position?: string; + position?: PositionType; fullWdith?: boolean; fontSize?: number; fontFamily?: string; @@ -187,10 +188,12 @@ declare namespace Chart { interface ChartLegendOptions { display?: boolean; - position?: string; + position?: PositionType; fullWidth?: boolean; - onClick?(event: any, legendItem: any): void; + onClick?(event: MouseEvent, legendItem: ChartLegendItem): void; + onHover?(event: MouseEvent, legendItem: ChartLegendItem): void; labels?: ChartLegendLabelOptions; + reverse?: boolean; } interface ChartLegendLabelOptions { @@ -293,7 +296,7 @@ declare namespace Chart { interface ChartPointOptions { radius?: number; - pointStyle?: string; + pointStyle?: PointStyle; backgroundColor?: ChartColor; borderWidth?: number; borderColor?: ChartColor; @@ -332,6 +335,7 @@ declare namespace Chart { interface TickOptions { autoSkip?: boolean; + autoSkipPadding?: boolean; callback?(value: any, index: any, values: any): string|number; display?: boolean; fontColor?: ChartColor; @@ -386,7 +390,7 @@ declare namespace Chart { type ChartColor = string | CanvasGradient | CanvasPattern | string[]; interface ChartDataSets { - cubicInterpolationMode?: string; + cubicInterpolationMode?: 'default' | 'monotone'; backgroundColor?: ChartColor | ChartColor[]; borderWidth?: number; borderColor?: ChartColor; @@ -394,10 +398,15 @@ declare namespace Chart { borderDash?: number[]; borderDashOffset?: number; borderJoinStyle?: string; + borderSkipped?: PositionType; data?: number[] | ChartPoint[]; - fill?: boolean; + fill?: boolean | number | string; + hoverBackgroundColor?: string | string[]; + hoverBorderColor?: string | string[]; + hoverBorderWidth?: number | number[]; label?: string; lineTension?: number; + steppedLine?: 'before' | 'after' | boolean; pointBorderColor?: ChartColor | ChartColor[]; pointBackgroundColor?: ChartColor | ChartColor[]; pointBorderWidth?: number | number[]; @@ -407,14 +416,15 @@ declare namespace Chart { pointHoverBackgroundColor?: ChartColor | ChartColor[]; pointHoverBorderColor?: ChartColor | ChartColor[]; pointHoverBorderWidth?: number | number[]; - pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; + pointStyle?: PointStyle | HTMLImageElement | Array; xAxisID?: string; yAxisID?: string; type?: string; hidden?: boolean; hideInLegendAndTooltip?: boolean; + showLine?: boolean; stack?: string; - spanGaps?: string; + spanGaps?: boolean; } interface ChartScales { diff --git a/types/check-sum/tslint.json b/types/check-sum/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/check-sum/tslint.json +++ b/types/check-sum/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/chocolatechipjs/tslint.json b/types/chocolatechipjs/tslint.json index 04f74b7c27..ce367ade18 100644 --- a/types/chocolatechipjs/tslint.json +++ b/types/chocolatechipjs/tslint.json @@ -5,6 +5,8 @@ "adjacent-overload-signatures": false, "ban-types": false, "dt-header": false, - "unified-signatures": false + "no-any-union": false, + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/continuation-local-storage/tslint.json b/types/continuation-local-storage/tslint.json index 4b7077d438..0c26acc12f 100644 --- a/types/continuation-local-storage/tslint.json +++ b/types/continuation-local-storage/tslint.json @@ -7,6 +7,7 @@ "one-variable-per-declaration": false, "space-before-function-paren": false, "no-var": false, - "interface-over-type-literal": false + "interface-over-type-literal": false, + "no-unnecessary-generics": false } } diff --git a/types/core-js/tslint.json b/types/core-js/tslint.json index a62d0d4e68..deb0a8f9b2 100644 --- a/types/core-js/tslint.json +++ b/types/core-js/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false + "ban-types": false, + "no-unnecessary-generics": false } } diff --git a/types/cote/tslint.json b/types/cote/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/cote/tslint.json +++ b/types/cote/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/csv-stringify/tslint.json b/types/csv-stringify/tslint.json index 11584e5acd..963be749a2 100644 --- a/types/csv-stringify/tslint.json +++ b/types/csv-stringify/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { + "no-any-union": false, "prefer-method-signature": false } } diff --git a/types/cucumber/tslint.json b/types/cucumber/tslint.json index 3db14f85ea..215db37b37 100644 --- a/types/cucumber/tslint.json +++ b/types/cucumber/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "no-any-union": false, + "rules": { + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/cucumber/v1/tslint.json b/types/cucumber/v1/tslint.json index 3db14f85ea..3fe527d08f 100644 --- a/types/cucumber/v1/tslint.json +++ b/types/cucumber/v1/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/cwise-parser/tslint.json b/types/cwise-parser/tslint.json index 531fb4ef87..71ee04c4e1 100644 --- a/types/cwise-parser/tslint.json +++ b/types/cwise-parser/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" -} \ No newline at end of file + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/cwise/tslint.json b/types/cwise/tslint.json index 531fb4ef87..bee01cfc64 100644 --- a/types/cwise/tslint.json +++ b/types/cwise/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } } \ No newline at end of file diff --git a/types/d3-array/tslint.json b/types/d3-array/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-array/tslint.json +++ b/types/d3-array/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-axis/tslint.json b/types/d3-axis/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-axis/tslint.json +++ b/types/d3-axis/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-brush/tslint.json b/types/d3-brush/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-brush/tslint.json +++ b/types/d3-brush/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-chord/tslint.json b/types/d3-chord/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-chord/tslint.json +++ b/types/d3-chord/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-collection/tslint.json b/types/d3-collection/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-collection/tslint.json +++ b/types/d3-collection/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-contour/tslint.json b/types/d3-contour/tslint.json index 08016de61a..54efb0b84e 100644 --- a/types/d3-contour/tslint.json +++ b/types/d3-contour/tslint.json @@ -1,6 +1,7 @@ { - "extends": "dtslint/dt.json", - "rules": { - "unified-signatures": false - } + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false, + "no-unnecessary-generics": false + } } diff --git a/types/d3-dispatch/tslint.json b/types/d3-dispatch/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-dispatch/tslint.json +++ b/types/d3-dispatch/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-drag/tslint.json b/types/d3-drag/tslint.json index b8825c1674..26ee29cf50 100644 --- a/types/d3-drag/tslint.json +++ b/types/d3-drag/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODO "no-this-assignment": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-force/tslint.json b/types/d3-force/tslint.json index b8825c1674..26ee29cf50 100644 --- a/types/d3-force/tslint.json +++ b/types/d3-force/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODO "no-this-assignment": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-geo/tslint.json b/types/d3-geo/tslint.json index 680a816ce2..3020672011 100644 --- a/types/d3-geo/tslint.json +++ b/types/d3-geo/tslint.json @@ -4,6 +4,10 @@ // TODO "no-this-assignment": false, "unified-signatures": false, - "max-line-length": [false, 200] + "max-line-length": [ + false, + 200 + ], + "no-unnecessary-generics": false } } diff --git a/types/d3-quadtree/tslint.json b/types/d3-quadtree/tslint.json index 38aa3fb5b3..9e3df4b94a 100644 --- a/types/d3-quadtree/tslint.json +++ b/types/d3-quadtree/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "unified-signatures": false, - "no-empty-interface": false + "no-empty-interface": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-queue/tslint.json b/types/d3-queue/tslint.json index b8825c1674..c3beb085cb 100644 --- a/types/d3-queue/tslint.json +++ b/types/d3-queue/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { // TODO + "no-any-union": false, "no-this-assignment": false, "unified-signatures": false } diff --git a/types/d3-request/tslint.json b/types/d3-request/tslint.json index 70edbfa511..a965459d61 100644 --- a/types/d3-request/tslint.json +++ b/types/d3-request/tslint.json @@ -1,8 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO + // TODOs + "no-any-union": false, "no-this-assignment": false, + "no-unnecessary-generics": false, "unified-signatures": false, "max-line-length": [false, 145] } diff --git a/types/d3-sankey/tslint.json b/types/d3-sankey/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-sankey/tslint.json +++ b/types/d3-sankey/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-scale/tslint.json b/types/d3-scale/tslint.json index 604d5950cf..9846c79a4d 100644 --- a/types/d3-scale/tslint.json +++ b/types/d3-scale/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "unified-signatures": false, - "callable-types": false + "callable-types": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-selection/tslint.json b/types/d3-selection/tslint.json index b8825c1674..26ee29cf50 100644 --- a/types/d3-selection/tslint.json +++ b/types/d3-selection/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODO "no-this-assignment": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-shape/tslint.json b/types/d3-shape/tslint.json index 108ab49c45..b1ba182ba6 100644 --- a/types/d3-shape/tslint.json +++ b/types/d3-shape/tslint.json @@ -4,6 +4,7 @@ // TODO "no-this-assignment": false, "unified-signatures": false, - "callable-types": false + "callable-types": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-transition/tslint.json b/types/d3-transition/tslint.json index b8825c1674..26ee29cf50 100644 --- a/types/d3-transition/tslint.json +++ b/types/d3-transition/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODO "no-this-assignment": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-voronoi/tslint.json b/types/d3-voronoi/tslint.json index 08b1465cd6..54efb0b84e 100644 --- a/types/d3-voronoi/tslint.json +++ b/types/d3-voronoi/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/d3-zoom/tslint.json b/types/d3-zoom/tslint.json index b8825c1674..26ee29cf50 100644 --- a/types/d3-zoom/tslint.json +++ b/types/d3-zoom/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODO "no-this-assignment": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/datatables.net-buttons/datatables.net-buttons-tests.ts b/types/datatables.net-buttons/datatables.net-buttons-tests.ts index 015917c456..3323f6fdb9 100644 --- a/types/datatables.net-buttons/datatables.net-buttons-tests.ts +++ b/types/datatables.net-buttons/datatables.net-buttons-tests.ts @@ -8,10 +8,20 @@ $(document).ready(function () { extend: 'excel', text: 'Excel', className: 'class', + filename: "exported_file.csv", exportOptions: { columns: ':visible' } }, + { + extend: 'excel', + text: 'Excel', + className: 'class', + filename: "exported_file.csv", + exportOptions: { + columns: [1, 6, 2, 3, 4] + } + }, { action: function (e, dt, node, config) { }, available: function (dt, config) { return true; }, diff --git a/types/datatables.net-buttons/index.d.ts b/types/datatables.net-buttons/index.d.ts index a5b32c1bf6..1bdf212b03 100644 --- a/types/datatables.net-buttons/index.d.ts +++ b/types/datatables.net-buttons/index.d.ts @@ -86,6 +86,11 @@ declare namespace DataTables { */ title?: string; + /** + * Define what the exported filename should be + */ + filename?: string; + exportOptions?: ButtonExportOptions; autoPrint?: boolean; customize?: FunctionButtonCustomize; @@ -95,7 +100,7 @@ declare namespace DataTables { (dt: DataTables.Api, config: any): boolean } export interface ButtonExportOptions { - columns?: string; + columns?: string | number | string[] | number[]; } export interface ButtonKey { diff --git a/types/deepmerge/deepmerge-tests.ts b/types/deepmerge/deepmerge-tests.ts index 5467cb83f0..dcd21ff3c3 100644 --- a/types/deepmerge/deepmerge-tests.ts +++ b/types/deepmerge/deepmerge-tests.ts @@ -1,19 +1,29 @@ import * as deepmerge from "deepmerge"; const x = { - foo: { bar: 3 }, - array: [{ does: 'work', too: [1, 2, 3] }] + foo: { bar: 3 }, + array: [{ does: 'work', too: [1, 2, 3] }] }; const y = { - foo: { baz: 4 }, - quux: 5, - array: [{ does: 'work', too: [4, 5, 6] }, { really: 'yes' }] + foo: { baz: 4 }, + quux: 5, + array: [{ does: 'work', too: [4, 5, 6] }, { really: 'yes' }] }; const expected = { - foo: { bar: 3, baz: 4 }, - array: [{ does: 'work', too: [1, 2, 3, 4, 5, 6] }, { really: 'yes' }], - quux: 5 + foo: { bar: 3, baz: 4 }, + array: [{ does: 'work', too: [1, 2, 3, 4, 5, 6] }, { really: 'yes' }], + quux: 5 }; -const result = deepmerge(x, y); +const result = deepmerge(x, y); +const anyResult = deepmerge(x, y); + +function reverseConcat(dest: number[], src: number[]) { + return src.concat(dest); +} + +const withOptions = deepmerge(x, y, { + clone: false, + arrayMerge: reverseConcat +}); diff --git a/types/deepmerge/index.d.ts b/types/deepmerge/index.d.ts index 96d0412aa6..797e52c8a5 100644 --- a/types/deepmerge/index.d.ts +++ b/types/deepmerge/index.d.ts @@ -1,17 +1,20 @@ // Type definitions for deepmerge 1.3 // Project: https://github.com/KyleAMathews/deepmerge // Definitions by: marvinscharle +// syy1125 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 export = deepmerge; -declare function deepmerge(x: T, y: T, options?: deepmerge.Options): T; +declare function deepmerge(x: Partial, y: Partial, options?: deepmerge.Options): T; +declare function deepmerge(x: T1, y: T2, options?: deepmerge.Options): T1 & T2; declare namespace deepmerge { - interface Options { + interface Options { clone?: boolean; - arrayMerge?(destination: T, source: T, options?: Options): T; + arrayMerge?(destination: any[], source: any[], options?: Options): any[]; } - function all(objects: T[], options?: Options): T; + function all(objects: Array>, options?: Options): T; } diff --git a/types/delay/tslint.json b/types/delay/tslint.json index 21fecfef93..bf610ae17f 100644 --- a/types/delay/tslint.json +++ b/types/delay/tslint.json @@ -1,7 +1,8 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "await-promise": false - } + "extends": "dtslint/dt.json", + "rules": { + // TODO + "await-promise": false, + "no-unnecessary-generics": false + } } diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index aa6c03bf29..199fe1de75 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -488,6 +488,7 @@ declare namespace Dockerode { CpusetCpus: string; CpusetMems: string; Devices?: any; + DiskQuota: number; KernelMemory: number; Memory: number; MemoryReservation: number; diff --git a/types/documentdb/tslint.json b/types/documentdb/tslint.json index 2750cc0197..71ee04c4e1 100644 --- a/types/documentdb/tslint.json +++ b/types/documentdb/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/ember-testing-helpers/tsconfig.json b/types/ember-testing-helpers/tsconfig.json index aaf474ecba..cd7634bd25 100644 --- a/types/ember-testing-helpers/tsconfig.json +++ b/types/ember-testing-helpers/tsconfig.json @@ -14,7 +14,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "allowSyntheticDefaultImports": true }, "files": [ "index.d.ts", diff --git a/types/ember/tsconfig.json b/types/ember/tsconfig.json index d2f27dfec9..fbc4052a08 100644 --- a/types/ember/tsconfig.json +++ b/types/ember/tsconfig.json @@ -14,10 +14,11 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "allowSyntheticDefaultImports": true }, "files": [ "index.d.ts", "ember-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/ember/tslint.json b/types/ember/tslint.json index 7c941bb9c6..309f39a5d1 100644 --- a/types/ember/tslint.json +++ b/types/ember/tslint.json @@ -4,9 +4,11 @@ // Heavy use of Function type in this older package. "ban-types": false, "jsdoc-format": false, + "no-any-union": false, "no-misused-new": false, // not sure what this means "no-single-declare-module": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false } } diff --git a/types/engine.io-client/tsconfig.json b/types/engine.io-client/tsconfig.json index 257ae8bb42..e98b3db085 100644 --- a/types/engine.io-client/tsconfig.json +++ b/types/engine.io-client/tsconfig.json @@ -8,7 +8,6 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strict": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/engine.io-client/tslint.json b/types/engine.io-client/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/engine.io-client/tslint.json +++ b/types/engine.io-client/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 878dc2c082..8ebb11ce94 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -56,7 +56,7 @@ export interface CommonWrapper

{ * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. * @param node */ - contains(node: ReactElement): boolean; + contains(node: ReactElement | string): boolean; /** * Returns whether or not a given react element exists in the shallow render tree. diff --git a/types/enzyme/tslint.json b/types/enzyme/tslint.json index 1c1a051bd3..67c3be0ed0 100644 --- a/types/enzyme/tslint.json +++ b/types/enzyme/tslint.json @@ -1,8 +1,9 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODOs - "dt-header": false, - "no-duplicate-imports": false - } + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "dt-header": false, + "no-duplicate-imports": false, + "no-unnecessary-generics": false + } } diff --git a/types/esri-leaflet-geocoder/tslint.json b/types/esri-leaflet-geocoder/tslint.json index fd2834499c..48743df77b 100644 --- a/types/esri-leaflet-geocoder/tslint.json +++ b/types/esri-leaflet-geocoder/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODOs + "no-any-union": false, "no-object-literal-type-assertion": false } } diff --git a/types/exceljs/tslint.json b/types/exceljs/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/exceljs/tslint.json +++ b/types/exceljs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/expect/tslint.json b/types/expect/tslint.json index 420d80e8f3..00e5a6b547 100644 --- a/types/expect/tslint.json +++ b/types/expect/tslint.json @@ -1,8 +1,9 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-void-expression": false, - "no-duplicate-imports": false - } + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-void-expression": false, + "no-duplicate-imports": false, + "no-unnecessary-generics": false + } } diff --git a/types/express-graphql/express-graphql-tests.ts b/types/express-graphql/express-graphql-tests.ts index 6b9c0b9169..d476682104 100644 --- a/types/express-graphql/express-graphql-tests.ts +++ b/types/express-graphql/express-graphql-tests.ts @@ -1,6 +1,6 @@ -import * as express from "express"; +import * as express from 'express'; import 'express-session'; -import * as graphqlHTTP from "express-graphql"; +import * as graphqlHTTP from 'express-graphql'; const app = express(); const schema = {}; @@ -8,19 +8,29 @@ const schema = {}; const graphqlOption: graphqlHTTP.OptionsObj = { graphiql: true, schema: schema, - formatError: (error:Error) => ({ - message: error.message, + formatError: (error: Error) => ({ + message: error.message }) }; const graphqlOptionRequest = (request: express.Request): graphqlHTTP.OptionsObj => ({ graphiql: true, schema: schema, - context: request.session, + context: request.session }); -app.use("/graphql1", graphqlHTTP(graphqlOption)); +const graphqlOptionRequestAsync = async (request: express.Request): Promise => { + return { + graphiql: true, + schema: await Promise.resolve(schema), + context: request.session + }; +}; -app.use("/graphql2", graphqlHTTP(graphqlOptionRequest)); +app.use('/graphql1', graphqlHTTP(graphqlOption)); -app.listen(8080); +app.use('/graphql2', graphqlHTTP(graphqlOptionRequest)); + +app.use('/graphqlasync', graphqlHTTP(graphqlOptionRequestAsync)); + +app.listen(8080, () => console.log('GraphQL Server running on localhost:8080')); diff --git a/types/express-graphql/index.d.ts b/types/express-graphql/index.d.ts index 680e83668b..077e3ab736 100644 --- a/types/express-graphql/index.d.ts +++ b/types/express-graphql/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for express-graphql // Project: https://www.npmjs.org/package/express-graphql -// Definitions by: Isman Usoh , Nitin Tutlani +// Definitions by: Isman Usoh +// Nitin Tutlani +// Daniel Fader // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Request, Response } from "express"; @@ -12,7 +14,7 @@ declare namespace graphqlHTTP { * Used to configure the graphQLHTTP middleware by providing a schema * and other configuration options. */ - export type Options = ((req: Request) => OptionsObj) | OptionsObj + export type Options = ((req: Request) => OptionsObj) | ((req: Request) => Promise) | OptionsObj export type OptionsObj = { /** * A GraphQL schema from graphql-js. diff --git a/types/express-graphql/tsconfig.json b/types/express-graphql/tsconfig.json index 3394d7c54a..8cec14e03c 100644 --- a/types/express-graphql/tsconfig.json +++ b/types/express-graphql/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es2015", "lib": [ "es6" ], @@ -19,4 +20,4 @@ "index.d.ts", "express-graphql-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/fabric/tslint.json b/types/fabric/tslint.json index 8697a364c3..17bb596f5d 100644 --- a/types/fabric/tslint.json +++ b/types/fabric/tslint.json @@ -5,6 +5,7 @@ "adjacent-overload-signatures": false, "ban-types": false, "interface-name": false, + "no-any-union": false, "no-empty-interface": false, "space-within-parens": false, "strict-export-declare-modifiers": false, diff --git a/types/falcor/tslint.json b/types/falcor/tslint.json index 3db14f85ea..3393f9dcca 100644 --- a/types/falcor/tslint.json +++ b/types/falcor/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/fast-list/tslint.json b/types/fast-list/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/fast-list/tslint.json +++ b/types/fast-list/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/firebird/tslint.json b/types/firebird/tslint.json index b63c1c3846..188dc816e2 100644 --- a/types/firebird/tslint.json +++ b/types/firebird/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-boolean-literal-compare": false + "no-boolean-literal-compare": false, + "no-unnecessary-generics": false } } diff --git a/types/fluent-ffmpeg/index.d.ts b/types/fluent-ffmpeg/index.d.ts index e1380dc78e..87bdbfe15c 100644 --- a/types/fluent-ffmpeg/index.d.ts +++ b/types/fluent-ffmpeg/index.d.ts @@ -105,6 +105,11 @@ declare namespace Ffmpeg { size?: string; } + interface AudioVideoFilter { + filter: string; + options: string | string[] | {}; + } + class FfmpegCommand extends events.EventEmitter { constructor(options?: FfmpegCommandOptions); constructor(input?: string | stream.Readable, options?: FfmpegCommandOptions); @@ -144,10 +149,10 @@ declare namespace Ffmpeg { audioFrequency(freq: number): FfmpegCommand; withAudioQuality(quality: number): FfmpegCommand; audioQuality(quality: number): FfmpegCommand; - withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand; - withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand; - audioFilter(filters: { filter: string, options: any }): FfmpegCommand; - audioFilters(filters: { filter: string, options: any }): FfmpegCommand; + withAudioFilter(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + withAudioFilters(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + audioFilter(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + audioFilters(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; // options/video; withNoVideo(): FfmpegCommand; @@ -156,10 +161,10 @@ declare namespace Ffmpeg { videoCodec(codec: string): FfmpegCommand; withVideoBitrate(bitrate: string | number): FfmpegCommand; videoBitrate(bitrate: string | number): FfmpegCommand; - withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand; - withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand; - videoFilter(filters: { filter: string, options: any }): FfmpegCommand; - videoFilters(filters: { filter: string, options: any }): FfmpegCommand; + withVideoFilter(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + withVideoFilters(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + videoFilter(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; + videoFilters(filters: string | string[] | AudioVideoFilter[]): FfmpegCommand; withOutputFps(fps: number): FfmpegCommand; withOutputFPS(fps: number): FfmpegCommand; withFpsOutput(fps: number): FfmpegCommand; diff --git a/types/fluent-ffmpeg/tslint.json b/types/fluent-ffmpeg/tslint.json index d88586e5bd..6338577095 100644 --- a/types/fluent-ffmpeg/tslint.json +++ b/types/fluent-ffmpeg/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } } diff --git a/types/flux-standard-action/index.d.ts b/types/flux-standard-action/index.d.ts index 388132bea6..ce328e9be8 100644 --- a/types/flux-standard-action/index.d.ts +++ b/types/flux-standard-action/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for flux-standard-action 0.5.0 // Project: https://github.com/acdlite/flux-standard-action // Definitions by: Qubo +// Simon Fridlund // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,12 +17,12 @@ export interface Action { /** Usage: `var action: Action & AnyMeta;` */ export interface AnyMeta { - meta: any + meta?: any; } /** Usage: `var action: Action & TypedMeta;` */ export interface TypedMeta { - meta: T + meta?: T; } export declare function isFSA(action: any): action is Action; diff --git a/types/from2/tslint.json b/types/from2/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/from2/tslint.json +++ b/types/from2/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index 1af094260d..f405486adb 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -14,7 +14,7 @@ const fd = 0; const modeNum = 0; const modeStr = ""; const object = {}; -const errorCallback = (err: Error) => { }; +const errorCallback = (err: Error | null) => { }; const readOptions: fs.ReadOptions = { reviver: {} }; diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index df3324aca5..60c112c68b 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -14,140 +14,141 @@ import { Stats } from "fs"; export * from "fs"; export function copy(src: string, dest: string, options?: CopyOptions): Promise; -export function copy(src: string, dest: string, callback: (err: Error) => void): void; -export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, callback: (err: Error | null) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error | null) => void): void; export function copySync(src: string, dest: string, options?: CopyOptions): void; export function move(src: string, dest: string, options?: MoveOptions): Promise; -export function move(src: string, dest: string, callback: (err: Error) => void): void; -export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function move(src: string, dest: string, callback: (err: Error | null) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error | null) => void): void; export function moveSync(src: string, dest: string, options?: MoveOptions): void; export function createFile(file: string): Promise; -export function createFile(file: string, callback: (err: Error) => void): void; +export function createFile(file: string, callback: (err: Error | null) => void): void; export function createFileSync(file: string): void; export function ensureDir(path: string): Promise; -export function ensureDir(path: string, callback: (err: Error) => void): void; +export function ensureDir(path: string, callback: (err: Error | null) => void): void; export function ensureDirSync(path: string): void; export function mkdirs(dir: string): Promise; -export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirs(dir: string, callback: (err: Error | null) => void): void; export function mkdirp(dir: string): Promise; -export function mkdirp(dir: string, callback: (err: Error) => void): void; +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, callback: (err: Error) => void): void; +export function outputFile(file: string, data: any, callback: (err: Error | null) => void): void; export function outputFileSync(file: string, data: any): void; export function readJson(file: string, options?: ReadOptions): Promise; -export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; -export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; export function readJSON(file: string, options?: ReadOptions): Promise; -export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; -export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, callback: (err: Error | null, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error | null, jsonObject: any) => void): void; export function readJsonSync(file: string, options?: ReadOptions): any; export function readJSONSync(file: string, options?: ReadOptions): any; export function remove(dir: string): Promise; -export function remove(dir: string, callback: (err: Error) => void): void; +export function remove(dir: string, callback: (err: Error | null) => void): void; export function removeSync(dir: string): void; export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; -export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; -export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error | null) => void): void; export function outputJson(file: string, data: any, options?: WriteOptions): Promise; -export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; -export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error | null) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error | null) => void): void; export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; -export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; -export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, callback: (err: Error | null) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; export function writeJson(file: string, object: any, options?: WriteOptions): Promise; -export function writeJson(file: string, object: any, callback: (err: Error) => void): void; -export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, callback: (err: Error | null) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error | null) => void): void; export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; export function ensureFile(path: string): Promise; -export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFile(path: string, callback: (err: Error | null) => void): void; export function ensureFileSync(path: string): void; export function ensureLink(src: string, dest: string): Promise; -export function ensureLink(src: string, dest: string, callback: (err: Error) => void): void; +export function ensureLink(src: string, dest: string, callback: (err: Error | null) => void): void; export function ensureLinkSync(src: string, dest: string): void; export function ensureSymlink(src: string, dest: string, type?: SymlinkType): Promise; -export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error) => void): void; -export function ensureSymlink(src: string, dest: string, callback: (err: Error) => void): void; +export function ensureSymlink(src: string, dest: string, type: SymlinkType, callback: (err: Error | null) => void): void; +export function ensureSymlink(src: string, dest: string, callback: (err: Error | null) => void): void; export function ensureSymlinkSync(src: string, dest: string, type?: SymlinkType): void; export function emptyDir(path: string): Promise; -export function emptyDir(path: string, callback: (err: Error) => void): void; +export function emptyDir(path: string, callback: (err: Error | null) => void): void; export function emptyDirSync(path: string): void; export function pathExists(path: string): Promise; -export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExists(path: string, callback: (err: Error | null, exists: boolean) => void): void; export function pathExistsSync(path: string): boolean; // fs async methods // copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts /** Tests a user's permissions for the file specified by path. */ -export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; -export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; export function access(path: string | Buffer, mode?: number): Promise; -export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, callback: (err: NodeJS.ErrnoException) => void): void; -export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, + callback: (err: NodeJS.ErrnoException | null) => void): void; +export function appendFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; export function appendFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; -export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function chmod(path: string | Buffer, mode: string | number): Promise; export function chown(path: string | Buffer, uid: number, gid: number): Promise; -export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; -export function close(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function close(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function close(fd: number): Promise; -export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function fchmod(fd: number, mode: string | number): Promise; -export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function fchown(fd: number, uid: number, gid: number): Promise; export function fdatasync(fd: number, callback: () => void): void; export function fdatasync(fd: number): Promise; -export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; export function fstat(fd: number): Promise; -export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function fsync(fd: number): Promise; -export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; -export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function ftruncate(fd: number, len?: number): Promise; -export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; -export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function futimes(fd: number, atime: number, mtime: number): Promise; export function futimes(fd: number, atime: Date, mtime: Date): Promise; -export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function lchown(path: string | Buffer, uid: number, gid: number): Promise; -export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; -export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; export function lstat(path: string | Buffer): Promise; /** @@ -156,7 +157,7 @@ export function lstat(path: string | Buffer): Promise; * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; /** * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -164,35 +165,36 @@ export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoExcept * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function mkdir(path: string | Buffer): Promise; -export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; -export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; -export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; -export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; -export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; +export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; +export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; // tslint:disable-next-line:unified-signatures export function readFile(file: string | Buffer | number, encoding: string): Promise; export function readFile(file: string | Buffer | number): Promise; -export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; export function readdir(path: string | Buffer): Promise; -export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => any): void; export function readlink(path: string | Buffer): Promise; -export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; -export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => any): void; export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; -export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function rename(oldPath: string, newPath: string): Promise; /** @@ -201,17 +203,17 @@ export function rename(oldPath: string, newPath: string): Promise; * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function rmdir(path: string | Buffer): Promise; -export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => any): void; export function stat(path: string | Buffer): Promise; -export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; -export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; -export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function truncate(path: string | Buffer, len?: number): Promise; /** @@ -220,25 +222,25 @@ export function truncate(path: string | Buffer, len?: number): Promise; * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ -export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function unlink(path: string | Buffer): Promise; export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; -export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException | null) => void): void; export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; -export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; -export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; export function write(fd: number, data: any, offset: number, encoding?: string): Promise; -export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +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) => void): void; +export function writeFile(file: string | Buffer | number, data: any, options: { encoding?: string; mode?: number; flag?: 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. @@ -247,7 +249,7 @@ export function writeFile(file: string | Buffer | number, data: any, options: { * @param callback The created folder path is passed as a string to the callback's second parameter. */ export function mkdtemp(prefix: string): Promise; -export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; +export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; export interface PathEntry { path: string; diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index a8e84d478b..4cdef77a80 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -42,11 +42,7 @@ declare namespace gapi.auth2 { /** * Get permission from the user to access the specified scopes offline. */ - grantOfflineAccess(options?: { - scope?: string; - prompt?: "select_account" | "consent"; - app_package_name?: string; - }): any; + grantOfflineAccess(options?: OfflineAccessOptions): Promise<{code: string}>; /** * Attaches the sign-in flow to the specified container's click handler. @@ -107,6 +103,17 @@ declare namespace gapi.auth2 { scope?: string; } + /** + * Definitions by: John + * Interface that represents the different configuration parameters for the GoogleAuth.grantOfflineAccess(options) method. + * Reference: https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauth2offlineaccessoptions + */ + interface OfflineAccessOptions { + scope?: string; + prompt?: "select_account" | "consent"; + app_package_name?: string; + } + /** * Interface that represents the different configuration parameters for the gapi.auth2.init method. * Reference: https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauth2clientconfig diff --git a/types/get-stream/tslint.json b/types/get-stream/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/get-stream/tslint.json +++ b/types/get-stream/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index 3642cca521..3a9c3175c8 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -294,8 +294,9 @@ outMat4 = mat4.fromXRotation(outMat4, Math.PI); outMat4 = mat4.fromYRotation(outMat4, Math.PI); outMat4 = mat4.fromZRotation(outMat4, Math.PI); outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); -outVec3 = mat4.getTranslation(outVec3, mat4A) -outQuat = mat4.getRotation(outQuat, mat4A) +outVec3 = mat4.getTranslation(outVec3, mat4A); +outVec3 = mat4.getScaling(outVec3, mat4A); +outQuat = mat4.getRotation(outQuat, mat4A); outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); outMat4 = mat4.fromQuat(outMat4, quatB); @@ -643,8 +644,9 @@ outMat4 = _mat4.fromXRotation(outMat4, Math.PI); outMat4 = _mat4.fromYRotation(outMat4, Math.PI); outMat4 = _mat4.fromZRotation(outMat4, Math.PI); outMat4 = _mat4.fromRotationTranslation(outMat4, quatA, vec3A); -outVec3 = _mat4.getTranslation(outVec3, mat4A) -outQuat = _mat4.getRotation(outQuat, mat4A) +outVec3 = _mat4.getTranslation(outVec3, mat4A); +outVec3 = _mat4.getScaling(outVec3, mat4A); +outQuat = _mat4.getRotation(outQuat, mat4A); outMat4 = _mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); outMat4 = _mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); outMat4 = _mat4.fromQuat(outMat4, quatB); diff --git a/types/gl-matrix/index.d.ts b/types/gl-matrix/index.d.ts index 89f28934b8..1e6d310ed6 100644 --- a/types/gl-matrix/index.d.ts +++ b/types/gl-matrix/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for gl-matrix 2.2.2 // Project: https://github.com/toji/gl-matrix // Definitions by: Mattijs Kneppers , based on definitions by Tat +// Austin Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'gl-matrix' { @@ -2450,6 +2451,17 @@ declare module 'gl-matrix' { */ public static getTranslation(out: vec3, mat: mat4): vec3; + /** + * Returns the scaling factor component of a transformation matrix. + * If a matrix is built with fromRotationTranslationScale with a + * normalized Quaternion parameter, the returned vector will be + * the same as the scaling vector originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getScaling(out: vec3, mat: mat4): vec3; + /** * Returns a quaternion representing the rotational component * of a transformation matrix. If a matrix is built with diff --git a/types/google-protobuf/tslint.json b/types/google-protobuf/tslint.json index a88c66859c..b04385bb7a 100644 --- a/types/google-protobuf/tslint.json +++ b/types/google-protobuf/tslint.json @@ -1,16 +1,17 @@ { - "extends": "dtslint/dt.json", - "rules": { - "align": false, - "array-type": false, - "new-parens": false, - "no-consecutive-blank-lines": false, - "interface-over-type-literal": false, - "no-relative-import-in-test": false, - "no-var": false, - "prefer-declare-function": false, - "semicolon": false, - "strict-export-declare-modifiers": false, - "trim-file": false - } + "extends": "dtslint/dt.json", + "rules": { + "align": false, + "array-type": false, + "new-parens": false, + "no-consecutive-blank-lines": false, + "interface-over-type-literal": false, + "no-relative-import-in-test": false, + "no-var": false, + "prefer-declare-function": false, + "semicolon": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "no-unnecessary-generics": false + } } diff --git a/types/google.analytics/tslint.json b/types/google.analytics/tslint.json index 57e94004d5..d802652174 100644 --- a/types/google.analytics/tslint.json +++ b/types/google.analytics/tslint.json @@ -3,6 +3,7 @@ "rules": { "dt-header": false, "ban-types": false, - "unified-signatures": false + "unified-signatures": false, + "no-unnecessary-generics": false } } diff --git a/types/graphql-relay/tslint.json b/types/graphql-relay/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/graphql-relay/tslint.json +++ b/types/graphql-relay/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/graphql/UNUSED_FILES.txt b/types/graphql/UNUSED_FILES.txt deleted file mode 100644 index df0fadfe79..0000000000 --- a/types/graphql/UNUSED_FILES.txt +++ /dev/null @@ -1 +0,0 @@ -execution/values.d.ts \ No newline at end of file diff --git a/types/graphql/execution/index.d.ts b/types/graphql/execution/index.d.ts index be3038be95..82d6bce853 100644 --- a/types/graphql/execution/index.d.ts +++ b/types/graphql/execution/index.d.ts @@ -4,3 +4,5 @@ export { responsePathAsArray, ExecutionResult } from './execute'; + +export { getDirectiveValues } from './values'; diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index 3f6e909ed7..79a0176f8d 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -23,3 +23,16 @@ export function getArgumentValues( node: FieldNode | DirectiveNode, variableValues?: { [key: string]: any } ): { [key: string]: any }; + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { directives?: Array }, + variableValues?: { [key: string]: any } +): void | { [key: string]: any }; diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 971ae5945b..905dcbdd7b 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for graphql 0.10 +// Type definitions for graphql 0.11 // Project: https://www.npmjs.com/package/graphql // Definitions by: TonyYang // Caleb Meredith @@ -6,6 +6,8 @@ // Firede // Kepennar // Mikhail Novikov +// Ivan Goncharov +// Hagai Cohen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -27,6 +29,7 @@ export { execute, defaultFieldResolver, responsePathAsArray, + getDirectiveValues, ExecutionResult, } from './execution'; @@ -34,7 +37,37 @@ export { export { validate, ValidationContext, + + // All validation rules in the GraphQL Specification. specifiedRules, + + // Individual validation rules. + ArgumentsOfCorrectTypeRule, + DefaultValuesOfCorrectTypeRule, + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedNonNullArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, } from './validation'; // Create and format GraphQL errors. diff --git a/types/graphql/subscription/subscribe.d.ts b/types/graphql/subscription/subscribe.d.ts index b7b40076bf..30efc010ec 100644 --- a/types/graphql/subscription/subscribe.d.ts +++ b/types/graphql/subscription/subscribe.d.ts @@ -14,7 +14,7 @@ export function subscribe( operationName?: string, fieldResolver?: GraphQLFieldResolver, subscribeFieldResolver?: GraphQLFieldResolver -): AsyncIterator; +): Promise | ExecutionResult>; export function createSourceEventStream( schema: GraphQLSchema, @@ -26,4 +26,4 @@ export function createSourceEventStream( }, operationName?: string, fieldResolver?: GraphQLFieldResolver -): AsyncIterable; +): Promise>; diff --git a/types/graphql/validation/index.d.ts b/types/graphql/validation/index.d.ts index a3ebc6a208..7f897fe78d 100644 --- a/types/graphql/validation/index.d.ts +++ b/types/graphql/validation/index.d.ts @@ -1,2 +1,132 @@ export { validate, ValidationContext } from './validate'; export { specifiedRules } from './specifiedRules'; + +// Spec Section: "Argument Values Type Correctness" +export { + ArgumentsOfCorrectType as ArgumentsOfCorrectTypeRule +} from './rules/ArgumentsOfCorrectType'; + +// Spec Section: "Variable Default Values Are Correctly Typed" +export { + DefaultValuesOfCorrectType as DefaultValuesOfCorrectTypeRule +} from './rules/DefaultValuesOfCorrectType'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { + FieldsOnCorrectType as FieldsOnCorrectTypeRule +} from './rules/FieldsOnCorrectType'; + +// Spec Section: "Fragments on Composite Types" +export { + FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule +} from './rules/FragmentsOnCompositeTypes'; + +// Spec Section: "Argument Names" +export { + KnownArgumentNames as KnownArgumentNamesRule +} from './rules/KnownArgumentNames'; + +// Spec Section: "Directives Are Defined" +export { + KnownDirectives as KnownDirectivesRule +} from './rules/KnownDirectives'; + +// Spec Section: "Fragment spread target defined" +export { + KnownFragmentNames as KnownFragmentNamesRule +} from './rules/KnownFragmentNames'; + +// Spec Section: "Fragment Spread Type Existence" +export { + KnownTypeNames as KnownTypeNamesRule +} from './rules/KnownTypeNames'; + +// Spec Section: "Lone Anonymous Operation" +export { + LoneAnonymousOperation as LoneAnonymousOperationRule +} from './rules/LoneAnonymousOperation'; + +// Spec Section: "Fragments must not form cycles" +export { + NoFragmentCycles as NoFragmentCyclesRule +} from './rules/NoFragmentCycles'; + +// Spec Section: "All Variable Used Defined" +export { + NoUndefinedVariables as NoUndefinedVariablesRule +} from './rules/NoUndefinedVariables'; + +// Spec Section: "Fragments must be used" +export { + NoUnusedFragments as NoUnusedFragmentsRule +} from './rules/NoUnusedFragments'; + +// Spec Section: "All Variables Used" +export { + NoUnusedVariables as NoUnusedVariablesRule +} from './rules/NoUnusedVariables'; + +// Spec Section: "Field Selection Merging" +export { + OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule +} from './rules/OverlappingFieldsCanBeMerged'; + +// Spec Section: "Fragment spread is possible" +export { + PossibleFragmentSpreads as PossibleFragmentSpreadsRule +} from './rules/PossibleFragmentSpreads'; + +// Spec Section: "Argument Optionality" +export { + ProvidedNonNullArguments as ProvidedNonNullArgumentsRule +} from './rules/ProvidedNonNullArguments'; + +// Spec Section: "Leaf Field Selections" +export { + ScalarLeafs as ScalarLeafsRule +} from './rules/ScalarLeafs'; + +// Spec Section: "Subscriptions with Single Root Field" +export { + SingleFieldSubscriptions as SingleFieldSubscriptionsRule +} from './rules/SingleFieldSubscriptions'; + +// Spec Section: "Argument Uniqueness" +export { + UniqueArgumentNames as UniqueArgumentNamesRule +} from './rules/UniqueArgumentNames'; + +// Spec Section: "Directives Are Unique Per Location" +export { + UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule +} from './rules/UniqueDirectivesPerLocation'; + +// Spec Section: "Fragment Name Uniqueness" +export { + UniqueFragmentNames as UniqueFragmentNamesRule +} from './rules/UniqueFragmentNames'; + +// Spec Section: "Input Object Field Uniqueness" +export { + UniqueInputFieldNames as UniqueInputFieldNamesRule +} from './rules/UniqueInputFieldNames'; + +// Spec Section: "Operation Name Uniqueness" +export { + UniqueOperationNames as UniqueOperationNamesRule +} from './rules/UniqueOperationNames'; + +// Spec Section: "Variable Uniqueness" +export { + UniqueVariableNames as UniqueVariableNamesRule +} from './rules/UniqueVariableNames'; + +// Spec Section: "Variables are Input Types" +export { + VariablesAreInputTypes as VariablesAreInputTypesRule +} from './rules/VariablesAreInputTypes'; + +// Spec Section: "All Variable Usages Are Allowed" +export { + VariablesInAllowedPosition as VariablesInAllowedPositionRule +} from './rules/VariablesInAllowedPosition'; diff --git a/types/graphql/validation/rules/ArgumentsOfCorrectType.d.ts b/types/graphql/validation/rules/ArgumentsOfCorrectType.d.ts new file mode 100644 index 0000000000..f7247d0a9c --- /dev/null +++ b/types/graphql/validation/rules/ArgumentsOfCorrectType.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Argument values of correct type + * + * A GraphQL document is only valid if all field argument literal values are + * of the type expected by their position. + */ +export function ArgumentsOfCorrectType(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/DefaultValuesOfCorrectType.d.ts b/types/graphql/validation/rules/DefaultValuesOfCorrectType.d.ts new file mode 100644 index 0000000000..88b3a824f2 --- /dev/null +++ b/types/graphql/validation/rules/DefaultValuesOfCorrectType.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Variable default values of correct type + * + * A GraphQL document is only valid if all variable default values are of the + * type expected by their definition. + */ +export function DefaultValuesOfCorrectType(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/FieldsOnCorrectType.d.ts b/types/graphql/validation/rules/FieldsOnCorrectType.d.ts new file mode 100644 index 0000000000..19609b2b65 --- /dev/null +++ b/types/graphql/validation/rules/FieldsOnCorrectType.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectType(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts b/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts new file mode 100644 index 0000000000..d6fffd4337 --- /dev/null +++ b/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts @@ -0,0 +1,10 @@ +import { ValidationContext } from '../index'; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypes(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/KnownArgumentNames.d.ts b/types/graphql/validation/rules/KnownArgumentNames.d.ts new file mode 100644 index 0000000000..4477b62a75 --- /dev/null +++ b/types/graphql/validation/rules/KnownArgumentNames.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/KnownDirectives.d.ts b/types/graphql/validation/rules/KnownDirectives.d.ts new file mode 100644 index 0000000000..68c6acf549 --- /dev/null +++ b/types/graphql/validation/rules/KnownDirectives.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectives(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/KnownFragmentNames.d.ts b/types/graphql/validation/rules/KnownFragmentNames.d.ts new file mode 100644 index 0000000000..b904f22d89 --- /dev/null +++ b/types/graphql/validation/rules/KnownFragmentNames.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/KnownTypeNames.d.ts b/types/graphql/validation/rules/KnownTypeNames.d.ts new file mode 100644 index 0000000000..48b15318da --- /dev/null +++ b/types/graphql/validation/rules/KnownTypeNames.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/LoneAnonymousOperation.d.ts b/types/graphql/validation/rules/LoneAnonymousOperation.d.ts new file mode 100644 index 0000000000..4ce6abcba9 --- /dev/null +++ b/types/graphql/validation/rules/LoneAnonymousOperation.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperation(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/NoFragmentCycles.d.ts b/types/graphql/validation/rules/NoFragmentCycles.d.ts new file mode 100644 index 0000000000..fed5982fc8 --- /dev/null +++ b/types/graphql/validation/rules/NoFragmentCycles.d.ts @@ -0,0 +1,3 @@ +import { ValidationContext } from '../index'; + +export function NoFragmentCycles(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/NoUndefinedVariables.d.ts b/types/graphql/validation/rules/NoUndefinedVariables.d.ts new file mode 100644 index 0000000000..51d30b8fd1 --- /dev/null +++ b/types/graphql/validation/rules/NoUndefinedVariables.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariables(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/NoUnusedFragments.d.ts b/types/graphql/validation/rules/NoUnusedFragments.d.ts new file mode 100644 index 0000000000..7f4d431299 --- /dev/null +++ b/types/graphql/validation/rules/NoUnusedFragments.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragments(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/NoUnusedVariables.d.ts b/types/graphql/validation/rules/NoUnusedVariables.d.ts new file mode 100644 index 0000000000..6eb2d984aa --- /dev/null +++ b/types/graphql/validation/rules/NoUnusedVariables.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariables(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts b/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts new file mode 100644 index 0000000000..f21edbd2cb --- /dev/null +++ b/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts @@ -0,0 +1,10 @@ +import { ValidationContext } from '../index'; + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMerged(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts b/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts new file mode 100644 index 0000000000..8defb47721 --- /dev/null +++ b/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts @@ -0,0 +1,10 @@ +import { ValidationContext } from '../index'; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreads(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts b/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts new file mode 100644 index 0000000000..4d5334b9fb --- /dev/null +++ b/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null) field arguments + * have been provided. + */ +export function ProvidedNonNullArguments(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/ScalarLeafs.d.ts b/types/graphql/validation/rules/ScalarLeafs.d.ts new file mode 100644 index 0000000000..afdc575671 --- /dev/null +++ b/types/graphql/validation/rules/ScalarLeafs.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafs(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts new file mode 100644 index 0000000000..01a2654a16 --- /dev/null +++ b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts @@ -0,0 +1,8 @@ +import { ValidationContext } from '../index'; + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptions(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueArgumentNames.d.ts b/types/graphql/validation/rules/UniqueArgumentNames.d.ts new file mode 100644 index 0000000000..8cc166d07a --- /dev/null +++ b/types/graphql/validation/rules/UniqueArgumentNames.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts b/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts new file mode 100644 index 0000000000..70ea02cd9c --- /dev/null +++ b/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ +export function UniqueDirectivesPerLocation(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueFragmentNames.d.ts b/types/graphql/validation/rules/UniqueFragmentNames.d.ts new file mode 100644 index 0000000000..c505968f6a --- /dev/null +++ b/types/graphql/validation/rules/UniqueFragmentNames.d.ts @@ -0,0 +1,8 @@ +import { ValidationContext } from '../index'; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueInputFieldNames.d.ts b/types/graphql/validation/rules/UniqueInputFieldNames.d.ts new file mode 100644 index 0000000000..cebd71b79b --- /dev/null +++ b/types/graphql/validation/rules/UniqueInputFieldNames.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueOperationNames.d.ts b/types/graphql/validation/rules/UniqueOperationNames.d.ts new file mode 100644 index 0000000000..5b12cc0eed --- /dev/null +++ b/types/graphql/validation/rules/UniqueOperationNames.d.ts @@ -0,0 +1,8 @@ +import { ValidationContext } from '../index'; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/UniqueVariableNames.d.ts b/types/graphql/validation/rules/UniqueVariableNames.d.ts new file mode 100644 index 0000000000..ef8712fbc1 --- /dev/null +++ b/types/graphql/validation/rules/UniqueVariableNames.d.ts @@ -0,0 +1,8 @@ +import { ValidationContext } from '../index'; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNames(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/VariablesAreInputTypes.d.ts b/types/graphql/validation/rules/VariablesAreInputTypes.d.ts new file mode 100644 index 0000000000..df079e52f9 --- /dev/null +++ b/types/graphql/validation/rules/VariablesAreInputTypes.d.ts @@ -0,0 +1,9 @@ +import { ValidationContext } from '../index'; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypes(context: ValidationContext): any; diff --git a/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts b/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts new file mode 100644 index 0000000000..6d3e513876 --- /dev/null +++ b/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts @@ -0,0 +1,6 @@ +import { ValidationContext } from '../index'; + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPosition(context: ValidationContext): any; diff --git a/types/handsontable/tslint.json b/types/handsontable/tslint.json index 40e100fc9e..5f3a731336 100644 --- a/types/handsontable/tslint.json +++ b/types/handsontable/tslint.json @@ -4,6 +4,7 @@ // TODOs "ban-types": false, "dt-header": false, + "no-any-union": false, "no-single-declare-module": false } } diff --git a/types/hasha/tslint.json b/types/hasha/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/hasha/tslint.json +++ b/types/hasha/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/hellojs/tslint.json b/types/hellojs/tslint.json index 2750cc0197..d9d49e375e 100644 --- a/types/hellojs/tslint.json +++ b/types/hellojs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/heredatalens/tslint.json b/types/heredatalens/tslint.json index e60c15844f..d9d49e375e 100644 --- a/types/heredatalens/tslint.json +++ b/types/heredatalens/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" -} \ No newline at end of file + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/hexo-fs/hexo-fs-tests.ts b/types/hexo-fs/hexo-fs-tests.ts new file mode 100644 index 0000000000..71e6d99e1b --- /dev/null +++ b/types/hexo-fs/hexo-fs-tests.ts @@ -0,0 +1,991 @@ +import fs = require('hexo-fs'); +import path = require('path'); +import mocha = require('mocha'); +import chai = require('chai'); +import Promise = require('bluebird'); + +const should = chai.should(); +const { join } = path; + +function createDummyFolder(path: string) { + return Promise.all([ + // Normal files in a hidden folder + fs.writeFile(join(path, '.hidden', 'a.txt'), 'a'), + fs.writeFile(join(path, '.hidden', 'b.js'), 'b'), + // Normal folder in a hidden folder + fs.writeFile(join(path, '.hidden', 'c', 'd'), 'd'), + // Top-class files + fs.writeFile(join(path, 'e.txt'), 'e'), + fs.writeFile(join(path, 'f.js'), 'f'), + // A hidden file + fs.writeFile(join(path, '.g'), 'g'), + // Files in a normal folder + fs.writeFile(join(path, 'folder', 'h.txt'), 'h'), + fs.writeFile(join(path, 'folder', 'i.js'), 'i'), + // A hidden files in a normal folder + fs.writeFile(join(path, 'folder', '.j'), 'j') + ]); +} + +const tmpDir = join(__dirname, 'fs_tmp'); + +before(() => fs.mkdirs(tmpDir)); + +after((done) => { + fs.rmdir(tmpDir); + done(); +}); + +it('exists()', () => { + return fs.exists(tmpDir).then((exist) => { + exist.should.be.true; + }); +}); + +it('exists() - callback', (callback) => { + fs.exists(tmpDir, (exist) => { + exist.should.be.true; + callback(); + }); +}); + +it('mkdirs()', () => { + const target = join(tmpDir, 'a', 'b', 'c'); + + return fs.mkdirs(target).then(() => { + return fs.exists(target); + }).then((exist) => { + exist.should.be.true; + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('mkdirs() - callback', (callback) => { + const target = join(tmpDir, 'a', 'b', 'c'); + + fs.mkdirs(target, (err) => { + should.not.exist(err); + + fs.exists(target, (exist) => { + exist.should.be.true; + fs.rmdir(join(tmpDir, 'a'), callback); + }); + }); +}); + +it('mkdirsSync()', () => { + const target = join(tmpDir, 'a', 'b', 'c'); + + fs.mkdirsSync(target); + + return fs.exists(target).then((exist) => { + exist.should.be.true; + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('writeFile()', () => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + + return fs.writeFile(target, body).then(() => { + return fs.readFile(target); + }).then((content) => { + content.should.eql(body); + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('writeFile() - callback', (callback) => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + + fs.writeFile(target, body, (err) => { + should.not.exist(err); + + fs.readFile(target, (_, content) => { + content!.should.eql(body); + fs.rmdir(join(tmpDir, 'a'), callback); + }); + }); +}); + +it('writeFileSync()', () => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + + fs.writeFileSync(target, body); + + return fs.readFile(target).then((content) => { + content.should.eql(body); + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('appendFile()', () => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + const body2 = 'bar'; + + return fs.writeFile(target, body).then(() => { + return fs.appendFile(target, body2); + }).then(() => { + return fs.readFile(target); + }).then((content) => { + content.should.eql(body + body2); + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('appendFile() - callback', (callback) => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + const body2 = 'bar'; + + fs.writeFile(target, body, () => { + fs.appendFile(target, body2, (err) => { + should.not.exist(err); + + fs.readFile(target, (_, content) => { + content!.should.eql(body + body2); + fs.rmdir(join(tmpDir, 'a'), callback); + }); + }); + }); +}); + +it('appendFileSync()', () => { + const target = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + const body2 = 'bar'; + + return fs.writeFile(target, body).then(() => { + fs.appendFileSync(target, body2); + return fs.readFile(target); + }).then((content) => { + content.should.eql(body + body2); + return fs.rmdir(join(tmpDir, 'a')); + }); +}); + +it('copyFile()', () => { + const src = join(tmpDir, 'test.txt'); + const dest = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + + return fs.writeFile(src, body).then(() => { + return fs.copyFile(src, dest); + }).then(() => { + return fs.readFile(dest); + }).then((content) => { + content.should.eql(body); + + return Promise.all([ + fs.unlink(src), + fs.rmdir(join(tmpDir, 'a')) + ]); + }); +}); + +it('copyFile() - callback', (callback) => { + const src = join(tmpDir, 'test.txt'); + const dest = join(tmpDir, 'a', 'b', 'test.txt'); + const body = 'foo'; + + fs.writeFile(src, body, (err) => { + if (err) return callback(err); + + fs.copyFile(src, dest, (err) => { + if (err) return callback(err); + + fs.readFile(dest, (err, content) => { + if (err) return callback(err); + content!.should.eql(body); + + Promise.all([ + fs.unlink(src), + fs.rmdir(join(tmpDir, 'a')) + ]).asCallback(callback); + }); + }); + }); +}); + +it('copyDir()', () => { + const src = join(tmpDir, 'a'); + const dest = join(tmpDir, 'b'); + + return createDummyFolder(src).then(() => { + return fs.copyDir(src, dest); + }).then((files) => { + files.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + return Promise.all([ + fs.readFile(join(dest, 'e.txt')), + fs.readFile(join(dest, 'f.js')), + fs.readFile(join(dest, 'folder', 'h.txt')), + fs.readFile(join(dest, 'folder', 'i.js')) + ]); + }).then((result) => { + result.should.eql(['e', 'f', 'h', 'i']); + }).then(() => { + return Promise.all([ + fs.rmdir(src), + fs.rmdir(dest) + ]); + }); +}); + +it('copyDir() - callback', (callback) => { + const src = join(tmpDir, 'a'); + const dest = join(tmpDir, 'b'); + + createDummyFolder(src).then(() => { + fs.copyDir(src, dest, (err, files) => { + should.not.exist(err); + files!.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + Promise.all([ + fs.readFile(join(dest, 'e.txt')), + fs.readFile(join(dest, 'f.js')), + fs.readFile(join(dest, 'folder', 'h.txt')), + fs.readFile(join(dest, 'folder', 'i.js')) + ]).then((result) => { + result.should.eql(['e', 'f', 'h', 'i']); + }).then(() => { + return Promise.all([ + fs.rmdir(src), + fs.rmdir(dest) + ]); + }).asCallback(callback); + }); + }); +}); + +it('copyDir() - ignoreHidden off', () => { + const src = join(tmpDir, 'a'); + const dest = join(tmpDir, 'b'); + + return createDummyFolder(src).then(() => { + return fs.copyDir(src, dest, { ignoreHidden: false }); + }).then((files) => { + files.should.have.members([ + join('.hidden', 'a.txt'), + join('.hidden', 'b.js'), + join('.hidden', 'c', 'd'), + 'e.txt', + 'f.js', + '.g', + join('folder', 'h.txt'), + join('folder', 'i.js'), + join('folder', '.j') + ]); + + return Promise.all([ + fs.readFile(join(dest, '.hidden', 'a.txt')), + fs.readFile(join(dest, '.hidden', 'b.js')), + fs.readFile(join(dest, '.hidden', 'c', 'd')), + fs.readFile(join(dest, 'e.txt')), + fs.readFile(join(dest, 'f.js')), + fs.readFile(join(dest, '.g')), + fs.readFile(join(dest, 'folder', 'h.txt')), + fs.readFile(join(dest, 'folder', 'i.js')), + fs.readFile(join(dest, 'folder', '.j')) + ]); + }).then((result) => { + result.should.eql(['a', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j']); + }).then(() => { + return Promise.all([ + fs.rmdir(src), + fs.rmdir(dest) + ]); + }); +}); + +it('copyDir() - ignorePattern', () => { + const src = join(tmpDir, 'a'); + const dest = join(tmpDir, 'b'); + + return createDummyFolder(src).then(() => { + return fs.copyDir(src, dest, { ignorePattern: /\.js/ }); + }).then((files) => { + files.should.have.members(['e.txt', join('folder', 'h.txt')]); + + return Promise.all([ + fs.readFile(join(dest, 'e.txt')), + fs.readFile(join(dest, 'folder', 'h.txt')) + ]); + }).then((result) => { + result.should.eql(['e', 'h']); + }).then(() => { + return Promise.all([ + fs.rmdir(src), + fs.rmdir(dest) + ]); + }); +}); + +it('listDir()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.listDir(target); + }).then((files) => { + files.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + return fs.rmdir(target); + }); +}); + +it('listDir() - callback', (callback) => { + const target = join(tmpDir, 'test'); + + createDummyFolder(target).then(() => { + fs.listDir(target, (err, files) => { + if (err) return callback(err); + + files!.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + fs.rmdir(target, callback); + }); + }); +}); + +it('listDir() - ignoreHidden off', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.listDir(target, { ignoreHidden: false }); + }).then((files) => { + files.should.have.members([ + join('.hidden', 'a.txt'), + join('.hidden', 'b.js'), + join('.hidden', 'c', 'd'), + 'e.txt', + 'f.js', + '.g', + join('folder', 'h.txt'), + join('folder', 'i.js'), + join('folder', '.j') + ]); + + return fs.rmdir(target); + }); +}); + +it('listDir() - ignorePattern', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.listDir(target, { ignorePattern: /\.js/ }); + }).then((files) => { + files.should.have.members(['e.txt', join('folder', 'h.txt')]); + return fs.rmdir(target); + }); +}); + +it('listDirSync()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + const files = fs.listDirSync(target); + files.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + return fs.rmdir(target); + }); +}); + +it('listDirSync() - ignoreHidden off', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + const files = fs.listDirSync(target, { ignoreHidden: false }); + files.should.have.members([ + join('.hidden', 'a.txt'), + join('.hidden', 'b.js'), + join('.hidden', 'c', 'd'), + 'e.txt', + 'f.js', + '.g', + join('folder', 'h.txt'), + join('folder', 'i.js'), + join('folder', '.j') + ]); + + return fs.rmdir(target); + }); +}); + +it('listDirSync() - ignorePattern', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + const files = fs.listDirSync(target, { ignorePattern: /\.js/ }); + files.should.have.members(['e.txt', join('folder', 'h.txt')]); + return fs.rmdir(target); + }); +}); + +it('readFile()', () => { + const target = join(tmpDir, 'test.txt'); + const body = 'test'; + + return fs.writeFile(target, body).then(() => { + return fs.readFile(target); + }).then((content) => { + content.should.eql(body); + return fs.unlink(target); + }); +}); + +it('readFile() - callback', (callback) => { + const target = join(tmpDir, 'test.txt'); + const body = 'test'; + + fs.writeFile(target, body, (err) => { + if (err) return callback(err); + + fs.readFile(target, (err, content) => { + if (err) return callback(err); + + content!.should.eql(body); + + fs.unlink(target).asCallback(callback); + }); + }); +}); + +it('readFile() - escape BOM', () => { + const target = join(tmpDir, 'test.txt'); + const body = '\ufefffoo'; + + return fs.writeFile(target, body).then(() => { + return fs.readFile(target); + }).then((content) => { + content.should.eql('foo'); + return fs.unlink(target); + }); +}); + +it('readFile() - escape Windows line ending', () => { + const target = join(tmpDir, 'test.txt'); + const body = 'foo\r\nbar'; + + return fs.writeFile(target, body).then(() => { + return fs.readFile(target); + }).then((content) => { + content.should.eql('foo\nbar'); + return fs.unlink(target); + }); +}); + +it('readFileSync()', () => { + const target = join(tmpDir, 'test.txt'); + const body = 'test'; + + return fs.writeFile(target, body).then(() => { + fs.readFileSync(target).should.eql(body); + return fs.unlink(target); + }); +}); + +it('readFileSync() - escape BOM', () => { + const target = join(tmpDir, 'test.txt'); + const body = '\ufefffoo'; + + return fs.writeFile(target, body).then(() => { + fs.readFileSync(target).should.eql('foo'); + return fs.unlink(target); + }); +}); + +it('readFileSync() - escape Windows line ending', () => { + const target = join(tmpDir, 'test.txt'); + const body = 'foo\r\nbar'; + + return fs.writeFile(target, body).then(() => { + fs.readFileSync(target).should.eql('foo\nbar'); + return fs.unlink(target); + }); +}); + +it('unlink()', () => { + const target = join(tmpDir, 'test-unlink'); + + return fs.writeFile(target, '').then(() => { + return fs.exists(target); + }).then((exist) => { + exist.should.eql(true); + return fs.unlink(target); + }).then(() => { + return fs.exists(target); + }).then((exist) => { + exist.should.eql(false); + }); +}); + +it('emptyDir()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.emptyDir(target); + }).then>((files) => { + files.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), false], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), false], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDir() - callback', (callback) => { + const target = join(tmpDir, 'test'); + + createDummyFolder(target).then(() => { + fs.emptyDir(target, (err, files) => { + if (err) return callback(err); + + files!.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + Promise.map<[string, boolean], void>([ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), false], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), false], + [join(target, 'folder', '.j'), true] + ], (data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }).asCallback(callback); + }); + }); +}); + +it('emptyDir() - ignoreHidden off', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.emptyDir(target, { ignoreHidden: false }); + }).then>((files) => { + files.should.have.members([ + join('.hidden', 'a.txt'), + join('.hidden', 'b.js'), + join('.hidden', 'c', 'd'), + 'e.txt', + 'f.js', + '.g', + join('folder', 'h.txt'), + join('folder', 'i.js'), + join('folder', '.j') + ]); + + return [ + [join(target, '.hidden', 'a.txt'), false], + [join(target, '.hidden', 'b.js'), false], + [join(target, '.hidden', 'c', 'd'), false], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), false], + [join(target, '.g'), false], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), false], + [join(target, 'folder', '.j'), false] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDir() - ignorePattern', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.emptyDir(target, { ignorePattern: /\.js/ }); + }).then>((files) => { + files.should.have.members(['e.txt', join('folder', 'h.txt')]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), true], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), true], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDir() - exclude', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.emptyDir(target, { exclude: ['e.txt', join('folder', 'i.js')] }); + }).then>((files) => { + files.should.have.members(['f.js', join('folder', 'h.txt')]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), true], + [join(target, 'f.js'), false], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), true], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDirSync()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then>(() => { + const files = fs.emptyDirSync(target); + files.should.have.members([ + 'e.txt', + 'f.js', + join('folder', 'h.txt'), + join('folder', 'i.js') + ]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), false], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), false], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDirSync() - ignoreHidden off', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then>(() => { + const files = fs.emptyDirSync(target, { ignoreHidden: false }); + files.should.have.members([ + join('.hidden', 'a.txt'), + join('.hidden', 'b.js'), + join('.hidden', 'c', 'd'), + 'e.txt', + 'f.js', + '.g', + join('folder', 'h.txt'), + join('folder', 'i.js'), + join('folder', '.j') + ]); + + return [ + [join(target, '.hidden', 'a.txt'), false], + [join(target, '.hidden', 'b.js'), false], + [join(target, '.hidden', 'c', 'd'), false], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), false], + [join(target, '.g'), false], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), false], + [join(target, 'folder', '.j'), false] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDirSync() - ignorePattern', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then>(() => { + const files = fs.emptyDirSync(target, { ignorePattern: /\.js/ }); + files.should.have.members(['e.txt', join('folder', 'h.txt')]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), false], + [join(target, 'f.js'), true], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), true], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('emptyDirSync() - exclude', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then>(() => { + const files = fs.emptyDirSync(target, { exclude: ['e.txt', join('folder', 'i.js')] }); + files.should.have.members(['f.js', join('folder', 'h.txt')]); + + return [ + [join(target, '.hidden', 'a.txt'), true], + [join(target, '.hidden', 'b.js'), true], + [join(target, '.hidden', 'c', 'd'), true], + [join(target, 'e.txt'), true], + [join(target, 'f.js'), false], + [join(target, '.g'), true], + [join(target, 'folder', 'h.txt'), false], + [join(target, 'folder', 'i.js'), true], + [join(target, 'folder', '.j'), true] + ]; + }).map((data: [string, boolean]) => { + return fs.exists(data[0]).then((exist) => { + exist.should.eql(data[1]); + }); + }).then(() => { + return fs.rmdir(target); + }); +}); + +it('rmdir()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + return fs.rmdir(target); + }).then(() => { + return fs.exists(target); + }).then((exist) => { + exist.should.be.false; + }); +}); + +it('rmdir() - callback', (callback) => { + const target = join(tmpDir, 'test'); + + createDummyFolder(target).then(() => { + fs.rmdir(target, (err) => { + should.not.exist(err); + + fs.exists(target, (exist) => { + exist.should.be.false; + callback(); + }); + }); + }); +}); + +it('rmdirSync()', () => { + const target = join(tmpDir, 'test'); + + return createDummyFolder(target).then(() => { + fs.rmdirSync(target); + return fs.exists(target); + }).then((exist) => { + exist.should.be.false; + }); +}); + +import { FSWatcher } from 'chokidar'; + +it('watch()', () => { + let watcher: FSWatcher; + + return fs.watch(tmpDir).then((watcher_) => { + watcher = watcher_; + + return new Promise((resolve, reject) => { + const path = join(tmpDir, 'test.txt'); + + watcher.on('add', (path_) => { + path_.should.eql(path); + resolve(); + }); + + fs.writeFile(path, 'test').catch(reject); + }); + }).finally(() => { + if (watcher) watcher.close(); + }); +}); + +it('ensurePath() - file exists', () => { + const target = join(tmpDir, 'test'); + + return Promise.all([ + fs.writeFile(join(target, 'foo.txt'), ''), + fs.writeFile(join(target, 'foo-1.txt'), ''), + fs.writeFile(join(target, 'foo-2.md'), ''), + fs.writeFile(join(target, 'bar.txt'), '') + ]).then(() => { + return fs.ensurePath(join(target, 'foo.txt')); + }).then((path) => { + path.should.eql(join(target, 'foo-2.txt')); + return fs.rmdir(target); + }); +}); + +it('ensurePath() - file not exist', () => { + const target = join(tmpDir, 'foo.txt'); + + return fs.ensurePath(target).then((path) => { + path.should.eql(target); + }); +}); + +it('ensurePath() - callback', (callback) => { + const target = join(tmpDir, 'test'); + + Promise.all([ + fs.writeFile(join(target, 'foo.txt'), ''), + fs.writeFile(join(target, 'foo-1.txt'), ''), + fs.writeFile(join(target, 'foo-2.md'), ''), + fs.writeFile(join(target, 'bar.txt'), '') + ]).then(() => { + fs.ensurePath(join(target, 'foo.txt'), (err, path) => { + should.not.exist(err); + path!.should.eql(join(target, 'foo-2.txt')); + fs.rmdir(target, callback); + }); + }); +}); + +it('ensurePathSync() - file exists', () => { + const target = join(tmpDir, 'test'); + + return Promise.all([ + fs.writeFile(join(target, 'foo.txt'), ''), + fs.writeFile(join(target, 'foo-1.txt'), ''), + fs.writeFile(join(target, 'foo-2.md'), ''), + fs.writeFile(join(target, 'bar.txt'), '') + ]).then(() => { + const path = fs.ensurePathSync(join(target, 'foo.txt')); + path.should.eql(join(target, 'foo-2.txt')); + + return fs.rmdir(target); + }); +}); + +it('ensurePathSync() - file not exist', () => { + const target = join(tmpDir, 'foo.txt'); + const path = fs.ensurePathSync(target); + + path.should.eql(target); +}); + +it('ensureWriteStream()', () => { + const target = join(tmpDir, 'foo', 'bar.txt'); + + return fs.ensureWriteStream(target).then((stream) => { + stream.path.should.eql(target); + stream.on('finish', () => { + return fs.unlink(target); + }); + }); +}); + +it('ensureWriteStream() - callback', (callback) => { + const target = join(tmpDir, 'foo', 'bar.txt'); + + fs.ensureWriteStream(target, (err, stream) => { + should.not.exist(err); + stream!.path.should.eql(target); + callback(); + }); +}); + +it('ensureWriteStreamSync()', () => { + const target = join(tmpDir, 'foo', 'bar.txt'); + const stream = fs.ensureWriteStreamSync(target); + + stream.path.should.eql(target); + stream.on('finish', () => { + return fs.rmdir(path.dirname(target)); + }); +}); diff --git a/types/hexo-fs/index.d.ts b/types/hexo-fs/index.d.ts new file mode 100644 index 0000000000..896fbc24eb --- /dev/null +++ b/types/hexo-fs/index.d.ts @@ -0,0 +1,436 @@ +// Type definitions for hexo-fs 0.2 +// Project: http://hexo.io/ +// Definitions by: segayuu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import Promise = require('bluebird'); +import { + PathLike, + Stats, + ReadStream, + WriteStream, + // chmod, + chmodSync, + // fchmod, + fchmodSync, + // lchmod, + lchmodSync, + // chown, + chownSync, + // fchown, + fchownSync, + // lchown, + lchownSync, + // close, + closeSync, + createReadStream, + createWriteStream, + // fsync, + fsyncSync, + // link, + linkSync, + // mkdir, + mkdirSync, + // open, + openSync, + // symlink, + symlinkSync, + // read, + readSync, + // readdir, + readdirSync, + // readlink, + readlinkSync, + // realpath, + realpathSync, + // rename, + renameSync, + // stat, + statSync, + // fstat, + fstatSync, + // lstat, + lstatSync, + // truncate, + truncateSync, + // ftruncate, + ftruncateSync, + // unlink, + unlinkSync, + // utimes, + utimesSync, + // futimes, + futimesSync, + watchFile, + unwatchFile, + // write, + writeSync +} from 'graceful-fs'; + +export interface DirectoryOptions { + ignoreHidden?: boolean; + ignorePattern?: RegExp; +} + +export interface AppendFileOptions { + encoding?: string | null; + mode?: string | number; + flag?: string; +} + +// access +export let F_OK: number | undefined; +export let R_OK: number | undefined; +export let W_OK: number | undefined; +export let X_OK: number | undefined; + +export let access: ((path: PathLike, mode?: number) => Promise) | undefined; // promisify +export let accessSync: ((path: PathLike, mode?: number) => void) | undefined; // promisify + +// appendFile +/** + * Appends data to a file. + * @param path + * @param data + * @param callback + */ +export function appendFile(path: string, data: any, callback?: (err: any) => void): Promise; +/** + * Appends data to a file. + * @param path + * @param data + * @param options + * @param callback + */ +export function appendFile(path: string, data: any, options: string | AppendFileOptions, callback?: (err: any) => void): Promise; +/** + * Synchronous version of fs.appendFile. + * @param path + * @param data + * @param options + */ +export function appendFileSync(path: string, data: any, options?: string | AppendFileOptions): void; + +// chmod +export function chmod(path: PathLike, mode: string | number): Promise; // promisify +export function fchmod(fd: number, mode: string | number): Promise; // promisify +export function lchmod(path: PathLike, mode: string | number): Promise; // promisify +export { chmodSync, fchmodSync, lchmodSync }; + +// chown +export function chown(path: PathLike, uid: number, gid: number): Promise; // promisify +export function fchown(fd: number, uid: number, gid: number): Promise; // promisify +export function lchown(path: PathLike, uid: number, gid: number): Promise; // promisify +export { chownSync, fchownSync, lchownSync }; + +// close +export function close(fd: number): Promise; // promisify +export { closeSync }; + +// copy +/** + * Copies a directory from src to dest. It returns an array of copied files. + * @param src + * @param dest + * @param callback + */ +export function copyDir(src: string, dest: string, callback?: (err: any, value?: string[]) => void): Promise; +/** + * Copies a directory from src to dest. It returns an array of copied files. + * @param dest + * @param options + * @param callback + */ +export function copyDir(src: string, dest: string, options?: DirectoryOptions, callback?: (err: any, value?: string[]) => void): Promise; +/** + * Copies a file from src to dest. + * @param src + * @param dest + * @param callback + */ +export function copyFile(src: PathLike, dest: string, callback?: (err: any) => void): Promise; + +// createStream +export { createReadStream, createWriteStream }; + +// emptyDir +/** + * Deletes all files in a directory. It returns an array of deleted files. + * @param path + * @param callback + */ +export function emptyDir(path: string, callback?: (err: any, value?: string | string[]) => void): Promise; +export function emptyDir( + path: string, + options?: DirectoryOptions & { exclude?: string[] }, + callback?: (err: any, value?: string | string[]) => void +): Promise; +export function emptyDirSync(path: string, options?: DirectoryOptions & { exclude?: string[] }, parent?: string): string | string[]; + +// ensurePath +/** + * Ensures the given path is available to use or appends a number to the path. + * @param path + * @param callback + */ +export function ensurePath(path: string, callback?: (err: any, value?: string) => void): Promise; +/** + * Synchronous version of `fs.ensurePath`. + * @param path + */ +export function ensurePathSync(path: string): string; + +// ensureWriteStream +/** + * Creates the parent directories if they does not exist and returns a writable stream. + * @param path + * @param callback + */ +export function ensureWriteStream(path: string, callback?: (err: any, value?: WriteStream) => void): Promise; +/** + * Creates the parent directories if they does not exist and returns a writable stream. + * @param path + * @param options + * @param callback + */ +export function ensureWriteStream( + path: string, + options?: string | { + flags?: string; + defaultEncoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }, + callback?: (err: any, value?: WriteStream) => void +): Promise; +/** + * Synchronous version of fs.ensureWriteStream. + * @param path + * @param options + */ +export function ensureWriteStreamSync(path: string, options?: string | { + flags?: string; + defaultEncoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; +}): WriteStream; + +// exists +/** + * Test whether or not the given `path` exists by checking with the file system. + * @param path checking if exists. + * @param callback + */ +export function exists(path: PathLike, callback?: (exist: boolean) => void): Promise; +/** + * Synchronous version of `fs.exists`. + * @param path + */ +export function existsSync(path: PathLike): boolean; + +// fsync +export function fsync(fd: number): Promise; // promisify +export { fsyncSync }; + +// link +export function link(existingPath: PathLike, newPath: PathLike): Promise; // promisify +export { linkSync }; + +// listDir +/** + * Lists files in a directory. + * @param path + * @param callback + */ +export function listDir(path: string, callback?: (err: any, value?: string[]) => void): Promise; +/** + * Lists files in a directory. + * @param path + * @param options + * @param callback + */ +export function listDir(path: string, options?: DirectoryOptions, callback?: (err: any, value?: string[]) => void): Promise; +/** + * Synchronous version of `fs.listDir`. + * @param path + * @param options + * @param parent + */ +export function listDirSync(path: string, options?: DirectoryOptions, parent?: string): string | string[]; + +// mkdir +export function mkdir(path: PathLike, mode?: string | number): Promise; // promisify +export { mkdirSync }; + +// mkdirs +/** + * Creates a directory and its parent directories if they does not exist. + * @param path + * @param callback + */ +export function mkdirs(path: PathLike, callback?: (err: any) => void): Promise; +/** + * Synchronous version of `fs.mkdirs`. + * @param path + */ +export function mkdirsSync(path: string): void; + +// open +export function open(path: PathLike, flags: string | number, mode?: string | number | null): Promise; // promisify +export { openSync }; + +// symlink +export function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; // promisify +export { symlinkSync }; + +// read +export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null +): Promise<{ bytesRead: number, buffer: TBuffer }>; // promisify +export { readSync }; + +// readdir +export function readdir(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): Promise; // promisify +export function readdir(path: PathLike, options: "buffer" | { encoding: "buffer" }): Promise; // promisify +export function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise>; // promisify +export { readdirSync }; + +// readFile +/** + * Reads the entire contents of a file. + * @param path + * @param callback + */ +export function readFile(path: PathLike | number, callback?: (err: any, value?: string) => void): Promise; +/** + * Reads the entire contents of a file. + * @param path + * @param options + * @param callback + */ +export function readFile( + path: PathLike | number, + options?: { encoding?: string; flag?: string; escape?: boolean; }, + callback?: (err: any, value?: string) => void +): Promise; +/** + * Synchronous version of `fs.readFile`. + * @param path + * @param options + */ +export function readFileSync(path: PathLike | number, options?: { encoding?: string; flag?: string; escape?: boolean; }): string; + +// readlink +export function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; // promisify +export function readlink(path: PathLike, options: { encoding: 'buffer' } | 'buffer'): Promise; // promisify +export function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; // promisify +export { readlinkSync }; + +// realpath +export function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; // promisify +export function realpath(path: PathLike, options: { encoding: 'buffer' } | 'buffer'): Promise; // promisify +export function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; // promisify +export { realpathSync }; + +// rename +export function rename(oldPath: PathLike, newPath: PathLike): Promise; // promisify +export { renameSync }; + +// rmdir +export function rmdir(path: string, callback?: (err: any) => void): Promise; +export function rmdirSync(path: string): void; + +// stat +export function stat(path: PathLike): Promise; // promisify +export function fstat(fd: number): Promise; // promisify +export function lstat(path: PathLike): Promise; // promisify +export { statSync, fstatSync, lstatSync }; + +// truncate +export function truncate(path: PathLike, len?: number | null): Promise; // promisify +export function ftruncate(fd: number, len?: number | null): Promise; // promisify +export { truncateSync, ftruncateSync }; + +// unlink +export function unlink(path: PathLike): Promise; // promisify +export { unlinkSync }; + +// utimes +export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; // promisify +export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; // promisify +export { utimesSync, futimesSync }; + +// watch +import { FSWatcher, WatchOptions } from 'chokidar'; +/** + * Watches changes of a file or a directory. + * + * See Chokidar API for more info. + * @param path + * @param options + * @param callback + */ +export function watch(path: string | string[], options?: WatchOptions, callback?: (err: any, value?: FSWatcher) => void): Promise; +export { watchFile, unwatchFile }; + +// write +export function write( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null +): Promise<{ bytesWritten: number, buffer: TBuffer }>; // promisify +export function write( + fd: number, + string: any, + position?: number | null, + encoding?: string | null +): Promise<{ bytesWritten: number, buffer: string }>; // promisify +export { writeSync }; + +// writeFile +/** + * Writes data to a file. + * @param path + * @param data + * @param callback + */ +export function writeFile(path: string, data: any, callback?: (err: any) => void): Promise; +/** + * Writes data to a file. + * @param path + * @param data + * @param options + * @param callback + */ +export function writeFile( + path: string, + data: any, + options?: string | { encoding?: string | null; mode?: string | number; flag?: string }, + callback?: (err: any) => void +): Promise; +/** + * Synchronous version of `fs.writeFile`. + * @param path + * @param data + * @param options + */ +export function writeFileSync(path: string, data: any, options?: string | { encoding?: string | null; mode?: string | number; flag?: string }): void; + +// Static classes +export let Stats: Stats; +export let ReadStream: ReadStream; +export let WriteStream: WriteStream; + +// util +export function escapeEOL(str: string): string; +export function escapeBOM(str: string): string; diff --git a/types/hexo-fs/tsconfig.json b/types/hexo-fs/tsconfig.json new file mode 100644 index 0000000000..fe667f65e4 --- /dev/null +++ b/types/hexo-fs/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hexo-fs-tests.ts" + ] +} diff --git a/types/hexo-fs/tslint.json b/types/hexo-fs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hexo-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/highstock.d.ts b/types/highcharts/highstock.d.ts index 857587ba66..79103b3464 100644 --- a/types/highcharts/highstock.d.ts +++ b/types/highcharts/highstock.d.ts @@ -1,6 +1,8 @@ // Type definitions for Highstock 2.1.5 // Project: http://www.highcharts.com/ -// Definitions by: David Deutsch + +// Definitions by: David Deutsch +// Definitions by: Dave Baumann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Highcharts from "highcharts"; @@ -100,6 +102,7 @@ declare namespace Highstock { interface Static extends Highcharts.Static { StockChart: Chart; + stockChart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; } } diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index d8b67d5d1f..df5c6f4ca0 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -1,10 +1,11 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "unified-signatures": false, - "no-empty-interface": false, - "dt-header": false, - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "dt-header": false, + "no-object-literal-type-assertion": false, + "no-unnecessary-generics": false + } } diff --git a/types/i18n/tslint.json b/types/i18n/tslint.json index bd50eb1958..eb3e5cc86e 100644 --- a/types/i18n/tslint.json +++ b/types/i18n/tslint.json @@ -1,7 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { - "prefer-method-signature": false, - "no-single-declare-module": false + // TODOs + "no-any-union": false, + "no-single-declare-module": false, + "prefer-method-signature": false } } diff --git a/types/isomorphic-fetch/tslint.json b/types/isomorphic-fetch/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/isomorphic-fetch/tslint.json +++ b/types/isomorphic-fetch/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/jest/tslint.json b/types/jest/tslint.json index a839e8aa9f..86d51194e9 100644 --- a/types/jest/tslint.json +++ b/types/jest/tslint.json @@ -4,6 +4,7 @@ // TODOs "dt-header": false, "no-mergeable-namespace": false, - "no-void-expression": false + "no-void-expression": false, + "no-unnecessary-generics": false } } diff --git a/types/jfs/tslint.json b/types/jfs/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/jfs/tslint.json +++ b/types/jfs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 0772c82fbe..4ae81db885 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -519,6 +519,11 @@ export interface StringSchema extends AnySchema { * Requires the string value to be a valid GUID. */ guid(options?: GuidOptions): StringSchema; + + /** + * Alias for `guid` -- Requires the string value to be a valid GUID + */ + uuid(options?: GuidOptions): StringSchema; /** * Requires the string value to be a valid hexadecimal string. diff --git a/types/jpeg-js/index.d.ts b/types/jpeg-js/index.d.ts new file mode 100644 index 0000000000..b3525b5449 --- /dev/null +++ b/types/jpeg-js/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for jpeg-js 0.3 +// Project: https://github.com/eugeneware/jpeg-js#readme +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface RawImageData { + data: D; + width: number; + height: number; +} + +export function decode(jpegData: ArrayLike | Iterable | ArrayBuffer, useTypedArray: true): RawImageData; +export function decode(jpegData: ArrayLike | Iterable | ArrayBuffer, useTypedArray?: false): RawImageData; +export function decode(jpegData: ArrayLike | Iterable | ArrayBuffer, useTypedArray: boolean): RawImageData; + +export function encode(imgData: RawImageData, qu?: number): RawImageData; diff --git a/types/jpeg-js/jpeg-js-tests.ts b/types/jpeg-js/jpeg-js-tests.ts new file mode 100644 index 0000000000..17bbc4fd5f --- /dev/null +++ b/types/jpeg-js/jpeg-js-tests.ts @@ -0,0 +1,15 @@ +import jpeg = require("jpeg-js"); +import fs = require("fs"); + +const x = fs.readFileSync("hello.jpg"); +const decoded = jpeg.decode(x, true); + +const { width, height } = decoded; + +width; // $ExpectType number +height; // $ExpectType number +decoded.data; // $ExpectType Uint8Array + +fs.writeFileSync("re-encoded.jpg", jpeg.encode({ + width, height, data: decoded.data +}, 50)); diff --git a/types/jpeg-js/tsconfig.json b/types/jpeg-js/tsconfig.json new file mode 100644 index 0000000000..1e3c116f4f --- /dev/null +++ b/types/jpeg-js/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jpeg-js-tests.ts" + ] +} diff --git a/types/jpeg-js/tslint.json b/types/jpeg-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jpeg-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.tools/tslint.json b/types/jquery.tools/tslint.json index 26a0c302a8..9d0759ec89 100644 --- a/types/jquery.tools/tslint.json +++ b/types/jquery.tools/tslint.json @@ -1,7 +1,8 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-void-expression": false - } + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-void-expression": false, + "no-unnecessary-generics": false + } } diff --git a/types/js-quantities/index.d.ts b/types/js-quantities/index.d.ts index ab76433c0d..e90fe72d87 100644 --- a/types/js-quantities/index.d.ts +++ b/types/js-quantities/index.d.ts @@ -69,4 +69,4 @@ declare namespace Qty { type UnitSource = Qty | string; } -export default Qty; +export = Qty; diff --git a/types/js-quantities/js-quantities-tests.ts b/types/js-quantities/js-quantities-tests.ts index 786a9f1a3f..ae171f6da1 100644 --- a/types/js-quantities/js-quantities-tests.ts +++ b/types/js-quantities/js-quantities-tests.ts @@ -1,4 +1,4 @@ -import Qty from "js-quantities"; +import Qty = require("js-quantities"); declare function describe(desc: string, fn: () => void): void; declare function it(desc: string, fn: () => void): void; diff --git a/types/js-to-java/tslint.json b/types/js-to-java/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/js-to-java/tslint.json +++ b/types/js-to-java/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/jsforce/connection.d.ts b/types/jsforce/connection.d.ts index 612bf6fc84..aa32d43ff5 100644 --- a/types/jsforce/connection.d.ts +++ b/types/jsforce/connection.d.ts @@ -1,21 +1,26 @@ import { SObjectCreateOptions } from './create-options'; import { DescribeSObjectResult } from './describe-result'; -import { Query } from './query'; +import { Query, QueryResult } from './query'; import { RecordResult } from './record-result'; import { SObject } from './salesforce-object'; -export interface ConnectionOptions { +// These are pulled out because according to http://jsforce.github.io/jsforce/doc/connection.js.html#line49 +// the oauth options can either be in the `oauth2` proeprty OR spread across the main connection +export interface OAuth2Options { + clientId?: string; + clientSecret?: string; + loginUrl?: string; + redirectUri?: string; +} + +export interface ConnectionOptions extends OAuth2Options { accessToken?: string; callOptions?: Object; instanceUrl?: string; loginUrl?: string; logLevel?: string; maxRequest?: number; - oauth2?: { - clientId: string, - clientSecret: string, - redirectUri?: string, - }; + oauth2?: Partial; proxyUrl?: string; redirectUri?: string; refreshToken?: string; @@ -33,11 +38,33 @@ export interface UserInfo { export type ConnectionEvent = "refresh"; -export class Connection { - constructor(params: ConnectionOptions) +/** + * the methods exposed here are done so that a client can use 'declaration augmentation' to get intellisense on their own projects. + * for example, given a type + * + * interface Foo { + * thing: string; + * yes: boolean; + * } + * + * you can write + * + * declare module "jsforce" { + * interface Connection { + * sobject(type: 'Foo'): SObject + * } + * } + * + * to ensure that you have the correct data types for the various collection names. + */ +export interface Connection { + query(soql: string, callback?: (err: Error, result: QueryResult) => void): QueryResult; + sobject(resource: string): SObject; +} +export class Connection implements Connection { + constructor(params: ConnectionOptions) accessToken: string; - sobject(resource: string): SObject; login(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginByOAuth2(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginBySoap(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index fc7bd017b2..c7d39c9499 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Dolan Miu // Kamil Ejsymont // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as fs from 'fs'; import * as stream from 'stream'; diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index 3c1657711d..208dba8bc8 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -1,5 +1,11 @@ import * as sf from 'jsforce'; +export interface DummyRecord { + thing: boolean; + other: number; + person: string; +} + const salesforceConnection: sf.Connection = new sf.Connection({ instanceUrl: '', refreshToken: '', @@ -9,6 +15,11 @@ const salesforceConnection: sf.Connection = new sf.Connection({ }, }); +salesforceConnection.sobject("Dummy").select(["thing", "other"]); + +// note the following should never compile: +// salesforceConnection.sobject("Dummy").select(["lol"]); + salesforceConnection.sobject("Account").create({ Name: "Test Acc 2", BillingStreet: "Maplestory street", @@ -30,9 +41,9 @@ salesforceConnection.sobject("ContentVersion").create({ } }); -salesforceConnection.sobject("ContentVersion").retrieve("world", { +salesforceConnection.sobject("ContentVersion").retrieve("world", { test: "test" -}, (err: Error, ret: sf.Record) => { +}, (err: Error, ret) => { if (err) { return; } diff --git a/types/jsforce/query.d.ts b/types/jsforce/query.d.ts index 42d258a48d..00b90a9464 100644 --- a/types/jsforce/query.d.ts +++ b/types/jsforce/query.d.ts @@ -7,7 +7,14 @@ export interface ExecuteOptions { scanAll?: number; } -export class Query { +export interface QueryResult { + done: boolean; + nextRecordsUrl?: string; + totalSize: number; + records: T[]; +} + +export class Query extends Promise { end(): Query; filter(filter: Object): Query; include(include: string): Query; @@ -27,7 +34,6 @@ export class Query { map(callback: (currentValue: Object) => void): Promise; scanAll(value: boolean): Query; select(fields: Object | string[] | string): Query; - then(onSuccess?: Function, onRejected?: Function): Promise; thenCall(callback?: (err: Error, records: T) => void): Query; toSOQL(callback: (err: Error, soql: string) => void): Promise; update(mapping: any, type: string, callback: (err: Error, records: RecordResult[]) => void): Promise; diff --git a/types/jsforce/record-result.d.ts b/types/jsforce/record-result.d.ts index bf53a5bf98..df77ef26d3 100644 --- a/types/jsforce/record-result.d.ts +++ b/types/jsforce/record-result.d.ts @@ -1,7 +1,13 @@ import { SalesforceId } from './salesforce-id'; -export interface RecordResult { - id: SalesforceId; - success: boolean; - anys: Object[]; +interface ErrorResult { + errors: string[]; + success: false; } + +interface SuccessResult { + id: SalesforceId; + success: true; +} + +export type RecordResult = SuccessResult | ErrorResult; diff --git a/types/jsforce/record.d.ts b/types/jsforce/record.d.ts index 3bfec4c65b..3dd0bca1da 100644 --- a/types/jsforce/record.d.ts +++ b/types/jsforce/record.d.ts @@ -1,6 +1,16 @@ +import { RecordResult } from './record-result'; +import { Connection } from './connection'; import { SalesforceId } from './salesforce-id'; +import { Stream } from 'stream'; -export interface Record { - Id: SalesforceId; - attributes: Object[]; +export class RecordReference { + constructor(conn: Connection, type: string, id: SalesforceId); + blob(fieldName: string): Stream; + del(options?: Object, callback?: (err: Error, result: RecordResult) => void): Promise; + delete(options?: Object, callback?: (err: Error, result: RecordResult) => void): Promise; + destroy(options?: Object, callback?: (err: Error, result: RecordResult) => void): Promise; + retrieve(options?: Object, callback?: (err: Error, record: Record) => void): Promise>; + update(record: Partial, options?: Object, callback?: (err: Error, result: RecordResult) => void): Promise; } + +export type Record = {Id: SalesforceId } & T; diff --git a/types/jsforce/salesforce-object.d.ts b/types/jsforce/salesforce-object.d.ts index 31da3a2c92..2f1f1590bf 100644 --- a/types/jsforce/salesforce-object.d.ts +++ b/types/jsforce/salesforce-object.d.ts @@ -3,18 +3,20 @@ import * as stream from 'stream'; import { SObjectCreateOptions } from './create-options'; import { DescribeSObjectResult } from './describe-result'; import { Query } from './query'; -import { Record } from './record'; +import { Record, RecordReference } from './record'; import { RecordResult } from './record-result'; import { Connection } from './connection'; import { SalesforceId } from './salesforce-id'; -export class SObject { - record(options: any, callback?: (err: Error, ret: any) => void): void; - update(options: SObjectCreateOptions, callback?: (err: Error, ret: any) => void): void; - retrieve(ids: string | string[], callback?: (err: Error, ret: Record | Record[]) => void): Promise; - retrieve(ids: string | string[], options?: Object, callback?: (err: Error, ret: Record | Record[]) => void): Promise; - upsert(records: Record | Record[], extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult) => void): Promise; - upsertBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; +export class SObject { + record(id: SalesforceId): RecordReference; + retrieve(id: SalesforceId, options?: Object, callback?: (err: Error, record: Record) => void): Promise>; + retrieve(ids: SalesforceId[], options?: Object, callback?: (err: Error, ret: Array>) => void): Promise>>; + update(record: Partial, options?: Object, callback?: (err: Error, ret: RecordResult) => void): Promise; + update(records: Array>, options?: Object, callback?: (err: Error, ret: RecordResult[]) => void): Promise; + upsert(records: Record, extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult) => void): Promise; + upsert(records: Array>, extIdField: SalesforceId, options?: Object, callback?: (err: Error, ret: RecordResult[]) => void): Promise; + upsertBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult[] | BatchResultInfo[]) => void): Batch; describeGlobal(callback: (err: Error, res: any) => void): void; describe$(callback: (err: Error, ret: DescribeSObjectResult) => void): void; describeGlobal$(callback: (err: Error, res: any) => void): void; @@ -28,39 +30,37 @@ export class SObject { findOne(query?: any, fields?: Object | string[] | string, options?: Object, callback?: (err: Error, ret: T) => void): void; approvalLayouts(callback?: (layoutInfo: ApprovalLayoutInfo) => void): Promise; - bulkload(operation: string, options?: { extIdField?: string }, input?: Record[] | stream.Stream[] | string[], callback?: (err: Error, ret: RecordResult) => void): Batch; + bulkload(operation: string, options?: { extIdField?: string }, input?: Array> | stream.Stream[] | string[], callback?: (err: Error, ret: RecordResult) => void): Batch; compactLayouts(callback?: CompactLayoutInfo): Promise; count(conditions?: Object | string, callback?: (err: Error, num: number) => void): Promise; create(options: any | any[], callback?: (err: Error, ret: RecordResult | RecordResult[]) => void): Promise; - createBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + createBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; del(ids: string | string[], callback?: (err: Error, ret: any) => void): void; destroy(ids: string | string[], callback?: (err: Error, ret: any) => void): void; delete(ids: string | string[], callback?: (err: Error, ret: any) => void): void; - deleteBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; - destroyBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; - destroyHardBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + deleteBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + destroyBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + destroyHardBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; deleted(start: Date | string, end: Date | string, callback?: (info: DeletedRecordsInfo) => void): Promise; - deleteHardBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + deleteHardBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; describe(callback?: (err: Error, ret: DescribeSObjectResult) => void): Promise; insert(options: any | any[], callback?: (err: Error, ret: RecordResult | RecordResult[]) => void): Promise; - insertBulk(input?: Record[] | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; + insertBulk(input?: Array> | stream.Stream | string, callback?: (err: Error, ret: RecordResult) => void): Batch; layouts(layoutName?: string, callback?: (err: Error, info: LayoutInfo) => void): Promise; listview(id: string): ListView; listviews(callback?: (err: Error, info: ListViewsInfo) => void): Promise; quickAction(actionName: string): QuickAction; quickActions(callback?: (err: Error, info: any) => void): Promise; recent(callback?: (err: Error, ret: RecordResult) => void): Promise; - select(field?: Object | string[] | string, callback?: (err: Error, ret: T[]) => void): Query; + select(callback?: (err: Error, ret: T[]) => void): Promise; + // TODO:use a typed pluck to turn `fields` into a subset of T's fields so that the output is slimmed down appropriately + select(fields?: {[P in keyof T]: boolean} | Array<(keyof T)> | (keyof T), callback?: (err: Error, ret: Array>) => void): Promise>>; } export interface ApprovalLayoutInfo { approvalLayouts: Object[]; } -export class Record extends Object { - constructor(connection: Connection, type: SObject, id: SalesforceId) -} - export class Batch extends stream.Writable { } @@ -85,7 +85,20 @@ export interface LayoutInfo { } export class ListView { - constructor(connection: Connection, type: SObject, id: SalesforceId) + constructor(connection: Connection, type: string, id: SalesforceId) +} + +export interface BatchInfo { + id: string; + jobId: string; + state: string; + stateMessage: string; +} + +export interface BatchResultInfo { + id: string; + batchId: string; + jobId: string; } export class ListViewsInfo { } diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index a62d0d4e68..5fdd35f19c 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -1,6 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false + // TODOs + "ban-types": false, + "no-any-union": false, + "no-unnecessary-generics": false } } diff --git a/types/jsnox/tslint.json b/types/jsnox/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/jsnox/tslint.json +++ b/types/jsnox/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/json-rpc-ws/tslint.json b/types/json-rpc-ws/tslint.json index e60c15844f..3393f9dcca 100644 --- a/types/json-rpc-ws/tslint.json +++ b/types/json-rpc-ws/tslint.json @@ -1,3 +1,8 @@ { - "extends": "dtslint/dt.json" -} \ No newline at end of file + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/jsonrpc-serializer/tslint.json b/types/jsonrpc-serializer/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/jsonrpc-serializer/tslint.json +++ b/types/jsonrpc-serializer/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/jui-grid/tslint.json b/types/jui-grid/tslint.json index a62d0d4e68..e39908ae45 100644 --- a/types/jui-grid/tslint.json +++ b/types/jui-grid/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false + "ban-types": false, + "no-any-union": false } } diff --git a/types/jui/tslint.json b/types/jui/tslint.json index 3db14f85ea..c92fd86792 100644 --- a/types/jui/tslint.json +++ b/types/jui/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false + } +} diff --git a/types/jwt-decode/tslint.json b/types/jwt-decode/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/jwt-decode/tslint.json +++ b/types/jwt-decode/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/jwt-decode/v1/tslint.json b/types/jwt-decode/v1/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/jwt-decode/v1/tslint.json +++ b/types/jwt-decode/v1/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/kafka-node/tslint.json b/types/kafka-node/tslint.json index d88586e5bd..b1439230db 100644 --- a/types/kafka-node/tslint.json +++ b/types/kafka-node/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } } diff --git a/types/kefir/index.d.ts b/types/kefir/index.d.ts index 09917d7846..e892e1b291 100644 --- a/types/kefir/index.d.ts +++ b/types/kefir/index.d.ts @@ -1,10 +1,14 @@ -// Type definitions for Kefir 3.3.0 +// Type definitions for Kefir 3.7.3 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa +// Piotr Hitori Bosak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 /// +export type ValueOfAnObservable> = T['']; + export interface Subscription { unsubscribe(): void; closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 @@ -28,19 +32,25 @@ export interface Observer { } export interface Observable { + '': T; // TypeScript hack to enable value unwrapping for combine/flatMap + + toProperty(getCurrent?: () => T): Property; // Subscribe / add side effects - onValue(callback: (value: T) => void): void; - offValue(callback: (value: T) => void): void; - onError(callback: (error: S) => void): void; - offError(callback: (error: S) => void): void; - onEnd(callback: () => void): void; - offEnd(callback: () => void): void; - onAny(callback: (event: Event) => void): void; - offAny(callback: (event: Event) => void): void; - log(name?: string): void; - offLog(name?: string): void; + onValue(callback: (value: T) => void): this; + offValue(callback: (value: T) => void): this; + onError(callback: (error: S) => void): this; + offError(callback: (error: S) => void): this; + onEnd(callback: () => void): this; + offEnd(callback: () => void): this; + onAny(callback: (event: Event) => void): this; + offAny(callback: (event: Event) => void): this; + log(name?: string): this; + spy(name?: string): this; + offLog(name?: string): this; + offSpy(name?: string): this; flatten(transformer?: (value: T) => U[]): Stream; - toPromise(PromiseConstructor?: any): any; + toPromise(): Promise; + toPromise>(PromiseConstructor: () => W): W; toESObservable(): any; // This method is designed to replace all other methods for subscribing observe(params: Observer): Subscription; @@ -49,11 +59,11 @@ export interface Observable { onError?: (error: S) => void, onEnd?: () => void ): Subscription; + setName(source: Observable, selfName: string): this; + setName(selfName: string): this; } export interface Stream extends Observable { - toProperty(getCurrent?: () => T): Property; - // Modify an stream map(fn: (value: T) => U): Stream; filter(predicate?: (value: T) => boolean): Stream; @@ -64,7 +74,8 @@ export interface Stream extends Observable { skipWhile(predicate?: (value: T) => boolean): Stream; skipDuplicates(comparator?: (a: T, b: T) => boolean): Stream; diff(fn?: (prev: T, next: T) => T, seed?: T): Stream; - scan(fn: (prev: T, next: T) => T, seed?: T): Stream; + scan(fn: (prev: T | W, next: T) => W): Stream; + scan(fn: (prev: W, next: T) => W, seed: W): Stream; delay(wait: number): Stream; throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Stream; debounce(wait: number, options?: { immediate: boolean }): Stream; @@ -85,19 +96,21 @@ export interface Stream extends Observable { bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Stream; transduce(transducer: any): Stream; withHandler(handler: (emitter: Emitter, event: Event) => void): Stream; - // Combine streams combine(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; zip(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; merge(otherObs: Stream): Stream; concat(otherObs: Stream): Stream; flatMap(transform: (value: T) => Stream): Stream; + flatMap>(): Stream, any>; flatMapLatest(fn: (value: T) => Stream): Stream; + flatMapLatest>(): Stream, any>; flatMapFirst(fn: (value: T) => Stream): Stream; + flatMapFirst>(): Stream, any>; flatMapConcat(fn: (value: T) => Stream): Stream; + flatMapConcat>(): Stream, any>; flatMapConcurLimit(fn: (value: T) => Stream, limit: number): Stream; flatMapErrors(transform: (error: S) => Stream): Stream; - // Combine two streams filterBy(otherObs: Observable): Stream; sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Stream; @@ -110,7 +123,6 @@ export interface Stream extends Observable { export interface Property extends Observable { changes(): Stream; - // Modify an property map(fn: (value: T) => U): Property; filter(predicate?: (value: T) => boolean): Property; @@ -141,19 +153,20 @@ export interface Property extends Observable { bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Property; transduce(transducer: any): Property; withHandler(handler: (emitter: Emitter, event: Event) => void): Property; - // Combine properties combine(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; zip(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; merge(otherObs: Property): Property; concat(otherObs: Property): Property; flatMap(transform: (value: T) => Property): Property; + flatMap>(): Property, any>; flatMapLatest(fn: (value: T) => Property): Property; + flatMapLatest>(): Property, any>; flatMapFirst(fn: (value: T) => Property): Property; + flatMapFirst>(): Property, any>; flatMapConcat(fn: (value: T) => Property): Property; flatMapConcurLimit(fn: (value: T) => Property, limit: number): Property; flatMapErrors(transform: (error: S) => Property): Property; - // Combine two properties filterBy(otherObs: Observable): Property; sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Property; @@ -165,8 +178,8 @@ export interface Property extends Observable { } export interface ObservablePool extends Observable { - plug(obs: Observable): void; - unPlug(obs: Observable): void; + plug(obs: Observable): this; + unPlug(obs: Observable): this; } export interface Event { @@ -197,11 +210,21 @@ export declare function fromESObservable(observable: any): Stream // Create a property export declare function constant(value: T): Property; export declare function constantError(error: T): Property; -export declare function fromPromise(promise: any): Property; - +export declare function fromPromise(promise: Promise): Property; // Combine observables -export declare function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Observable; -export declare function combine(obss: Observable[], combinator?: (...values: T[]) => U): Observable; +export declare function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Stream; +export declare function combine(obss: Observable[], combinator: (...values: T[]) => U): Stream; +export declare function combine }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable }, any>; +export declare function combine], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; +export declare function combine]>(obss: T): Stream<[ValueOfAnObservable], any>; +export declare function combine(obss: T): Stream; export declare function zip(obss: Observable[], passiveObss?: Observable[], combinator?: (...values: T[]) => U): Observable; export declare function merge(obss: Observable[]): Observable; export declare function concat(obss: Observable[]): Observable; diff --git a/types/kii-cloud-sdk/tslint.json b/types/kii-cloud-sdk/tslint.json index 65c83fb1e3..c4fd1ce0bb 100644 --- a/types/kii-cloud-sdk/tslint.json +++ b/types/kii-cloud-sdk/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "dt-header": false + "dt-header": false, + "no-unnecessary-generics": false } } diff --git a/types/leaflet.fullscreen/index.d.ts b/types/leaflet.fullscreen/index.d.ts index bc5abc85d2..4e58ede10c 100644 --- a/types/leaflet.fullscreen/index.d.ts +++ b/types/leaflet.fullscreen/index.d.ts @@ -7,7 +7,7 @@ import * as L from 'leaflet'; declare module 'leaflet' { namespace Control { - class Fullscreen extends L.Control { + class Fullscreen extends Control { constructor(options?: FullscreenOptions); options: FullscreenOptions; } @@ -27,6 +27,6 @@ declare module 'leaflet' { /** * Creates a fullscreen control. */ - function fullscreen(options?: Control.FullscreenOptions): L.Control.Fullscreen; + function fullscreen(options?: Control.FullscreenOptions): Control.Fullscreen; } } diff --git a/types/linq4js/tslint.json b/types/linq4js/tslint.json index 3db14f85ea..3393f9dcca 100644 --- a/types/linq4js/tslint.json +++ b/types/linq4js/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/lodash/tslint.json b/types/lodash/tslint.json index 8c17ad248c..02254dbc60 100644 --- a/types/lodash/tslint.json +++ b/types/lodash/tslint.json @@ -13,9 +13,11 @@ "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, + "no-any-union": false, "no-empty-interface": false, "no-namespace": false, "no-mergeable-namespace": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-void-expression": false, diff --git a/types/loopback-boot/tslint.json b/types/loopback-boot/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/loopback-boot/tslint.json +++ b/types/loopback-boot/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/loopback/tslint.json b/types/loopback/tslint.json index 5d2ec41a29..90b290e422 100644 --- a/types/loopback/tslint.json +++ b/types/loopback/tslint.json @@ -3,6 +3,8 @@ "rules": { // TODOs "jsdoc-format": false, + "no-any-union": false, + "no-unnecessary-generics": false, "prefer-method-signature": false } } diff --git a/types/lru-cache/tslint.json b/types/lru-cache/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/lru-cache/tslint.json +++ b/types/lru-cache/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/map-obj/tslint.json b/types/map-obj/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/map-obj/tslint.json +++ b/types/map-obj/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 31605f32b3..5f5129e8b0 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -14,6 +14,7 @@ interface MarkdownItStatic { declare var MarkdownIt: MarkdownItStatic; export = MarkdownIt; +export as namespace markdownit; declare module MarkdownIt { interface MarkdownIt { diff --git a/types/marked/tslint.json b/types/marked/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/marked/tslint.json +++ b/types/marked/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/scripts/material-ui/README.md b/types/material-ui/scripts/README.md similarity index 100% rename from scripts/material-ui/README.md rename to types/material-ui/scripts/README.md diff --git a/types/material-ui/scripts/generate.ts b/types/material-ui/scripts/generate.ts new file mode 100644 index 0000000000..f8024d5805 --- /dev/null +++ b/types/material-ui/scripts/generate.ts @@ -0,0 +1,151 @@ +// Usage: ts-node generate.ts + +/// + +import {get} from 'https'; +import {readdir, readFile, writeFile} from 'fs'; +import {join, extname, basename, dirname, relative} from 'path'; + +const token = process.env.GITHUB_ACCESS_TOKEN || '' + +const toMixedCase = (name) => { + let dist = name[0].toUpperCase() + for (let i = 1; i < name.length; i++) { + const c = name[i] + if (c !== '-') { + dist += c + continue + } + i++ + dist += name[i].toUpperCase() + } + return dist +} + +const github = (path) => new Promise((resolve, reject) => { + get({ + headers: {'user-agent': 'DefinitelyTyped/material-ui/generate'}, + host: 'api.github.com', + path, + }, (res) => { + if ((res.statusCode / 100 >> 0) != 2) { + reject(`GitHub response: ${res.statusCode} ${res.statusMessage}`) + return + } + let data = ''; + res + .on('data', (chunk) => data += chunk) + .on('end', () => resolve(JSON.parse(data))) + }).on('error', reject) +}) + +const categories = () => github(`/repos/callemall/material-ui/contents/src/svg-icons?ref=master&access_token=${token}`) + +const contents = (path) => github(`/repos/callemall/material-ui/contents/${path}?ref=master&access_token=${token}`) + +const collator = new Intl.Collator() + +const resolvePath = (filename) => join(__dirname, '..', filename) + +const readText = (filename) => new Promise((resolve, reject) => { + readFile(resolvePath(filename), 'utf8', (err, data) => { + if (err != null) { + reject(err) + return + } + resolve(data) + }) +}) + +const writeText = (filename, text) => new Promise((resolve, reject) => { + writeFile(resolvePath(filename), text, 'utf8', (err) => { + if (err != null) { + reject(err) + return + } + resolve() + }) +}) + +const inject = (content) => { + content.category = this.name + return content +} + +const rMark = /(\/{2} \{{3})[\s\S]*?(\/{2} \}{3})/g + +main().catch((err) => console.error(err)); + +async function main() { + const cats = await categories(); + const contentsList = await Promise.all(Array.prototype.map.call(cats, (cat) => contents(cat.path) + .then((cons) => Array.prototype.map.call(cons, (con) => { + con.category = cat.name + return con + })) + )); + const { dts, test } = await Array.prototype.concat.apply([], contentsList) + .map((content) => { + const {path} = content + const name = basename(path, extname(path)) + content.id = join(relative('src', dirname(path)), name) + content.className = toMixedCase(content.category) + toMixedCase(name) + return content + }) + .sort((a, b) => collator.compare(a.id, b.id)) + .reduce((prev, content) => { + const {dts, test} = prev + dts.individuals.push(`declare module 'material-ui/${content.id}' { + export import ${content.className} = __MaterialUI.SvgIcon; + export default ${content.className}; +}`) + dts.summarizeds.push(` export import ${content.className} = __MaterialUI.SvgIcon; // require('material-ui/${content.id}');`) + + test.individuals.push(`import _${content.className} from 'material-ui/${content.id}';`) + test.summarizeds.push(` ${content.className},`) + return prev + }, { + dts: {individuals: [], summarizeds: []}, + test: {individuals: [], summarizeds: []}, + }); + + { + const {individuals, summarizeds} = dts + const file = 'index.d.ts' + let index = 0 + const script = await readText(file) + await writeText(file, script.replace(rMark, (_, p1, p2) => { + let text = '' + switch (index) { + case 0: + text = individuals.join('\n\n') + break + case 1: + text = summarizeds.join('\n') + break + } + index++ + return p1 + '\n' + text + '\n' + p2 + })) + } + + { + const {individuals, summarizeds} = test + const file = 'material-ui-tests.tsx' + let index = 0 + const script = await readText(file) + await writeText(file, script.replace(rMark, (_, p1, p2) => { + let text = '' + switch (index) { + case 0: + text = individuals.join('\n') + break + case 1: + text = summarizeds.join('\n') + break + } + index++ + return p1 + '\n' + text + '\n' + p2 + })) + } +} diff --git a/types/material-ui/scripts/tsconfig.json b/types/material-ui/scripts/tsconfig.json new file mode 100644 index 0000000000..a06b8ed24f --- /dev/null +++ b/types/material-ui/scripts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "es6", + "baseUrl": "../..", + "typeRoots": [ + "../../" + ], + "types": [] + } +} \ No newline at end of file diff --git a/types/material-ui/tslint.json b/types/material-ui/tslint.json index ac0584ff62..d462b76190 100644 --- a/types/material-ui/tslint.json +++ b/types/material-ui/tslint.json @@ -1,9 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO + // TODOs "ban-types": false, "dt-header": false, + "no-any-union": false, "no-duplicate-imports": false, "no-empty-interface": false, "no-mergeable-namespace": false, diff --git a/types/mem/tslint.json b/types/mem/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/mem/tslint.json +++ b/types/mem/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/meteor/ejson.d.ts b/types/meteor/ejson.d.ts index 45ae2627c0..a6294fb8be 100644 --- a/types/meteor/ejson.d.ts +++ b/types/meteor/ejson.d.ts @@ -5,10 +5,10 @@ interface EJSONableCustomType { typeName(): string; } interface EJSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType | undefined | null; } interface JSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | undefined | null; } interface EJSON extends EJSONable { } @@ -44,10 +44,10 @@ declare module "meteor/ejson" { typeName(): string; } interface EJSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType | undefined | null; } interface JSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | undefined | null; } interface EJSON extends EJSONable { } diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index af632bdab1..99f931ec28 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -214,7 +214,10 @@ declare module "meteor/mongo" { interface ObjectIDStatic { new (hexString?: string): ObjectID; } - interface ObjectID { } + interface ObjectID { + toHexString(): string; + equals(otherID: ObjectID): boolean; + } function setConnectionOptions(options: any): void; } diff --git a/types/moonjs/tslint.json b/types/moonjs/tslint.json index 2750cc0197..71ee04c4e1 100644 --- a/types/moonjs/tslint.json +++ b/types/moonjs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/msgpack-lite/tslint.json b/types/msgpack-lite/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/msgpack-lite/tslint.json +++ b/types/msgpack-lite/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/nano/index.d.ts b/types/nano/index.d.ts index ab80e563d4..b95eecd8ea 100644 --- a/types/nano/index.d.ts +++ b/types/nano/index.d.ts @@ -1,14 +1,17 @@ // Type definitions for nano 6.2 // Project: https://github.com/apache/couchdb-nano // Definitions by: Tim Jacobi +// Kovács Vince // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + import { EventEmitter } from "events"; -import { Request, CoreOptions } from "request"; +import { CoreOptions, Request } from "request"; declare function nano( config: nano.Configuration | string -): nano.ServerScope | nano.DocumentScope; +): nano.ServerScope | nano.DocumentScope; declare namespace nano { interface Configuration { @@ -19,169 +22,279 @@ declare namespace nano { request?(params: any): void; } - type Callback = (error: any, result: any, headers?: any) => void; + type Callback = (error: any, response: R, headers?: any) => void; interface ServerScope { readonly config: ServerConfig; db: DatabaseScope; - use(db: string): DocumentScope; - scope(db: string): DocumentScope; + use(db: string): DocumentScope; + scope(db: string): DocumentScope; request: RequestFunction; relax: RequestFunction; dinosaur: RequestFunction; - auth(username: string, userpass: string, callback?: Callback): Request; - session(callback?: Callback): Request; - updates(params?: UpdatesParams, callback?: Callback): Request; - followUpdates(params?: any, callback?: Callback): EventEmitter; - uuids(num: number, callback: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication + auth(username: string, userpass: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session + session(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + updates(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + updates(params: UpdatesParams, callback?: Callback): Request; + followUpdates(callback?: Callback): EventEmitter; + followUpdates(params: any, callback?: Callback): EventEmitter; + uuids(num: number, callback: Callback): Request; } interface DatabaseScope { - create(name: string, callback?: Callback): Request; - get(name: string, callback?: Callback): Request; - destroy(name: string, callback?: Callback): Request; - list(callback?: Callback): Request; - use(db: string): DocumentScope; - compact(name: string, designname?: string, callback?: Callback): Request; - replicate( - source: string | DocumentScope, - target: string | DocumentScope, - options?: any, - callback?: Callback + // http://docs.couchdb.org/en/latest/api/database/common.html#put--db + create(name: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/common.html#get--db + get(name: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/common.html#delete--db + destroy(name: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_all_dbs + list(callback?: Callback): Request; + use(db: string): DocumentScope; + compact(name: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact + compact(name: string, designname: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + replicate( + source: string | DocumentScope, + target: string | DocumentScope, + callback?: Callback ): Request; - changes(name: string, params?: any, callback?: Callback): Request; - follow( - source: string, - params?: DatabaseScopeFollowUpdatesParams, - callback?: Callback - ): EventEmitter; - followUpdates(params?: any, callback?: Callback): EventEmitter; - updates(params?: UpdatesParams, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + replicate( + source: string | DocumentScope, + target: string | DocumentScope, + options: DatabaseReplicateOptions, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + changes(name: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact + changes(name: string, params: DatabaseChangesParams, callback?: Callback): Request; + follow(source: string, callback?: Callback): EventEmitter; + follow(source: string, params: DatabaseScopeFollowUpdatesParams, callback?: Callback): EventEmitter; + followUpdates(params?: any, callback?: Callback): EventEmitter; + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + updates(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + updates(params: UpdatesParams, callback?: Callback): Request; } - interface DocumentScope { + interface DocumentScope { readonly config: ServerConfig; - info(callback?: Callback): Request; - replicate( - target: string | DocumentScope, - options?: any, - callback?: Callback + // http://docs.couchdb.org/en/latest/api/database/common.html#get--db + info(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + replicate( + target: string | DocumentScope, + callback?: Callback ): Request; - compact(callback?: Callback): Request; - changes(params?: any, callback?: Callback): Request; - follow( - params?: DocumentScopeFollowUpdatesParams, - callback?: Callback - ): EventEmitter; - auth(username: string, userpass: string, callback?: Callback): Request; - session(callback?: Callback): Request; - insert(document: any, params?: any, callback?: Callback): Request; - get(docname: string, params?: any, callback?: Callback): Request; - head(docname: string, callback: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + replicate( + target: string | DocumentScope, + options: any, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact + compact(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + changes(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + changes(params: DatabaseChangesParams, callback?: Callback): Request; + follow(callback?: Callback): EventEmitter; + follow(params: DocumentScopeFollowUpdatesParams, callback?: Callback): EventEmitter; + // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication + auth(username: string, userpass: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session + session(callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/common.html#post--db + // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid + insert(document: ViewDocument | D & MaybeDocument, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/common.html#post--db + // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid + insert( + document: ViewDocument | D & MaybeDocument, + params: DocumentInsertParams | string | null, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid + get(docname: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid + get(docname: string, params?: DocumentGetParams, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#head--db-docid + head(docname: string, callback: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid + copy(src_document: string, dst_document: string, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid copy( src_document: string, dst_document: string, - options: any, - callback?: Callback + options: DocumentCopyOptions, + callback?: Callback ): Request; - destroy(docname: string, rev: string, callback?: Callback): Request; - bulk( - docs: BulkModifyDocsWrapper, - params?: any, - callback?: Callback - ): Request; - list(params?: any, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#delete--db-docid + destroy(docname: string, rev: string, callback?: Callback): Request; + bulk(docs: BulkModifyDocsWrapper, callback?: Callback): Request; + bulk(docs: BulkModifyDocsWrapper, params: any, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs + list(callback?: Callback>): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs + list(params: DocumentListParams, callback?: Callback>): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs + fetch(docnames: BulkFetchDocsWrapper, callback?: Callback>): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs fetch( docnames: BulkFetchDocsWrapper, - params?: any, - callback?: Callback + params: DocumentFetchParams, + callback?: Callback> ): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs + fetchRevs(docnames: BulkFetchDocsWrapper, callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs fetchRevs( docnames: BulkFetchDocsWrapper, - params?: any, - callback?: Callback + params: DocumentFetchParams, + callback?: Callback ): Request; - multipart: Multipart; + multipart: Multipart; attachment: Attachment; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#get--db-_design-ddoc-_show-func show( designname: string, showname: string, doc_id: string, - params?: any, - callback?: Callback + callback?: Callback ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#get--db-_design-ddoc-_show-func + show( + designname: string, + showname: string, + doc_id: string, + params: any, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid atomic( designname: string, updatename: string, docname: string, - body?: any, - callback?: Callback + callback?: Callback ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid + atomic( + designname: string, + updatename: string, + docname: string, + body: any, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid updateWithHandler( designname: string, updatename: string, docname: string, - body?: any, - callback?: Callback + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid + updateWithHandler( + designname: string, + updatename: string, + docname: string, + body: any, + callback?: Callback ): Request; search( designname: string, searchname: string, - params?: any, - callback?: Callback + callback?: Callback + ): Request; + search( + designname: string, + searchname: string, + params: any, + callback?: Callback ): Request; spatial( ddoc: string, viewname: string, - params?: any, - callback?: Callback + callback?: Callback ): Request; - view( + spatial( + ddoc: string, + viewname: string, + params: any, + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#post--db-_design-ddoc-_view-view + view( designname: string, viewname: string, - params?: any, - callback?: Callback + callback?: Callback> ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#post--db-_design-ddoc-_view-view + view( + designname: string, + viewname: string, + params: DocumentViewParams, + callback?: Callback> + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#db-design-design-doc-list-list-name-view-name viewWithList( designname: string, viewname: string, listname: string, - params?: any, - callback?: Callback + callback?: Callback + ): Request; + // http://docs.couchdb.org/en/latest/api/ddoc/render.html#db-design-design-doc-list-list-name-view-name + viewWithList( + designname: string, + viewname: string, + listname: string, + params: DocumentViewParams, + callback?: Callback ): Request; server: ServerScope; } - interface Multipart { - insert( - doc: any, - attachments: any[], - params: string | any, - callback?: Callback - ): Request; - get(docname: string, params?: string | any, callback?: Callback): Request; + interface Multipart { + // http://docs.couchdb.org/en/latest/api/document/common.html#creating-multiple-attachments + insert(doc: D, attachments: any[], callback?: Callback): Request; + // http://docs.couchdb.org/en/latest/api/document/common.html#creating-multiple-attachments + insert(doc: D, attachments: any[], params: any, callback?: Callback): Request; + get(docname: string, callback?: Callback): Request; + get(docname: string, params: any, callback?: Callback): Request; } interface Attachment { + insert(docname: string, attname: string, att: null, contenttype: string, params?: any): NodeJS.WritableStream; + insert(docname: string, attname: string, att: any, contenttype: string, callback?: Callback): Request; insert( docname: string, attname: string, att: any, contenttype: string, - params?: any, - callback?: Callback + params: any, + callback?: Callback ): Request; + get(docname: string, attname: string, callback?: Callback): Request; get( docname: string, attname: string, - params?: any, - callback?: Callback + params: any, + callback?: Callback ): Request; + destroy(docname: string, attname: string, callback?: Callback): Request; destroy( docname: string, attname: string, - params?: any, - callback?: Callback + params: any, + callback?: Callback ): Request; } @@ -192,7 +305,7 @@ declare namespace nano { type RequestFunction = ( options?: RequestOptions | string, - callback?: Callback + callback?: Callback ) => void; interface RequestOptions { @@ -209,10 +322,12 @@ declare namespace nano { multipart?: any[]; } + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates interface UpdatesParams { feed: "longpoll" | "continuous" | "eventsource"; timeout: number; heartbeat: boolean; + since: string; } interface DocumentScopeFollowUpdatesParams { @@ -243,6 +358,677 @@ declare namespace nano { interface BulkFetchDocsWrapper { keys: string[]; } + + // ------------------------------------- + // Document + // ------------------------------------- + + interface MaybeIdentifiedDocument { + _id?: string; + } + + interface IdentifiedDocument { + _id: string; + } + + interface MaybeRevisionedDocument { + _rev?: string; + } + + interface RevisionedDocument { + _rev: string; + } + + interface MaybeDocument extends MaybeIdentifiedDocument, MaybeRevisionedDocument { + } + + interface Document extends IdentifiedDocument, RevisionedDocument { + } + + // ------------------------------------- + // View + // ------------------------------------- + + interface View { + map?(doc: D & Document): void; + reduce?(doc: D & Document): void; + } + + interface ViewDocument extends IdentifiedDocument { + views: { + [name: string]: View + }; + } + + // ------------------------------------- + // Database scope request and response + // ------------------------------------- + + // http://docs.couchdb.org/en/latest/api/database/common.html#put--db + interface DatabaseCreateResponse { + // Operation status. Available in case of success + ok?: boolean; + + // Error type. Available if response code is 4xx + error?: string; + + // Error description. Available if response code is 4xx + reason?: string; + } + + // http://docs.couchdb.org/en/latest/api/database/common.html#get--db + interface DatabaseGetResponse { + // Set to true if the database compaction routine is operating on this database. + compact_running: boolean; + + // The name of the database. + db_name: string; + + // The version of the physical format used for the data when it is stored on disk. + disk_format_version: number; + + // The number of bytes of live data inside the database file. + data_size: number; + + // The length of the database file on disk. Views indexes are not included in the calculation. + disk_size: number; + + // A count of the documents in the specified database. + doc_count: number; + + // Number of deleted documents + doc_del_count: number; + + // Timestamp of when the database was opened, expressed in microseconds since the epoch. + instance_start_time: string; + + // The number of purge operations on the database. + purge_seq: number; + + sizes: { + // The size of live data inside the database, in bytes. + active: number; + + // The uncompressed size of database contents in bytes. + external: number; + + // The size of the database file on disk in bytes. Views indexes + file: number; + }; + + // The current number of updates to the database. + update_seq: number; + } + + // http://docs.couchdb.org/en/latest/api/database/common.html#delete--db + // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact + interface OkResponse { + // Operation status + ok: boolean; + } + + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + interface DatabaseReplicateOptions { + // Cancels the replication + cancel?: boolean; + + // Configure the replication to be continuous + continuous?: boolean; + + // Creates the target database. Required administrator’s privileges on target server. + create_target?: boolean; + + // Array of document IDs to be synchronized + doc_ids?: string[]; + + // The name of a filter function. + filter ?: string; + + // Address of a proxy server through which replication should occur (protocol can be “http” or “socks5”) + proxy ?: string; + + // Source database name or URL + source?: string; + + // Target database name or URL + target?: string; + } + + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + interface DatabaseReplicationHistoryItem { + // Number of document write failures + doc_write_failures: number; + + // Number of documents read + docs_read: number; + + // Number of documents written to target + docs_written: number; + + // Last sequence number in changes stream + end_last_seq: number; + + // Date/Time replication operation completed in RFC 2822 format + end_time: string; + + // Number of missing documents checked + missing_checked: number; + + // Number of missing documents found + missing_found: number; + + // Last recorded sequence number + recorded_seq: number; + + // Session ID for this replication operation + session_id: string; + + // First sequence number in changes stream + start_last_seq: number; + + // Date/Time replication operation started in RFC 2822 format + start_time: string; + } + + // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate + interface DatabaseReplicateResponse { + // Replication history + history: DatabaseReplicationHistoryItem[]; + + // Replication status + ok: boolean; + + // Replication protocol version + replication_id_version: number; + + // Unique session ID + session_id: string; + + // Last sequence number read from source database + source_last_seq: number; + } + + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + interface DatabaseChangesParams { + // List of document IDs to filter the changes feed as valid JSON array. Used with _doc_ids filter. Since length of + // URL is limited, it is better to use POST /{db}/_changes instead. + doc_ids?: string[]; + + // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. + conflicts?: boolean; + + // Return the change results in descending sequence order (most recent change first). Default is false. + descending?: boolean; + + // - normal Specifies Normal Polling Mode. All past changes are returned immediately. Default. + // - longpoll Specifies Long Polling Mode. Waits until at least one change has occurred, sends the change, then + // closes the connection. Most commonly used in conjunction with since=now, to wait for the next change. + // - continuous Sets Continuous Mode. Sends a line of JSON per event. Keeps the socket open until timeout. + // - eventsource Sets Event Source Mode. Works the same as Continuous Mode, but sends the events in EventSource + // format. + feed?: "normal" | "longpoll" | "continuous" | "eventsource"; + + // Reference to a filter function from a design document that will filter whole stream emitting only filtered + // events. See the section Change Notifications in the book CouchDB The Definitive Guide for more information. + filter?: string; + + // Period in milliseconds after which an empty line is sent in the results. Only applicable for longpoll, + // continuous, and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. Default is 60000. + // May be true to use default value. + heartbeat?: number; + + // Include the associated document with each result. If there are conflicts, only the winning revision is returned. + // Default is false. + include_docs?: boolean; + + // Include the Base64-encoded content of attachments in the documents that are included if include_docs is true. + // Ignored if include_docs isn’t true. Default is false. + attachments?: boolean; + + // Include encoding information in attachment stubs if include_docs is true and the particular attachment is + // compressed. Ignored if include_docs isn’t true. Default is false. + att_encoding_info?: boolean; + + // Limit number of result rows to the specified value (note that using 0 here has the same effect as 1). + limit?: number; + + // Start the results from the change immediately after the given update sequence. Can be valid update sequence or + // now value. Default is 0. + since?: number; + + // Specifies how many revisions are returned in the changes array. The default, main_only, will only return the + // current “winning” revision; all_docs will return all leaf revisions (including conflicts and deleted former + // conflicts). + style?: string; + + // Maximum period in milliseconds to wait for a change before the response is sent, even if there are no results. + // Only applicable for longpoll or continuous feeds. Default value is specified by httpd/changes_timeout + // configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead + // connections. + timeout?: number; + + // Allows to use view functions as filters. Documents counted as “passed” for view filter in case if map function + // emits at least one record for them. See _view for more info. + view?: string; + } + + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + interface DatabaseChangesResultItem { + // List of document’s leaves with single field rev. + changes: Array<{ rev: string }>; + + // Document ID. + id: string; + + // Update sequence. + seq: any; + + // true if the document is deleted. + deleted: boolean; + } + + // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes + interface DatabaseChangesResponse { + // Last change update sequence + last_seq: any; + + // Count of remaining items in the feed + pending: number; + + // Changes made to a database + results: DatabaseChangesResultItem[]; + } + + // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication + interface DatabaseAuthResponse { + // Operation status + ok: boolean; + + // Username + name: string; + + // List of user roles + roles: string[]; + } + + // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session + interface DatabaseSessionResponse { + // Operation status + ok: boolean; + + // User context for the current user + userCtx: any; + + // Server authentication configuration + info: any; + } + + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + interface DatabaseUpdatesResultItem { + // Database name. + db_name: string; + + // A database event is one of created, updated, deleted. + type: string; + + // Update sequence of the event. + seq: any; + } + + // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates + interface DatabaseUpdatesResponse { + // An array of database events. For longpoll and continuous modes, the entire response is the contents of the + // results array. + results: DatabaseUpdatesResultItem[]; + + // The last sequence ID reported. + last_seq: string; + } + + // ------------------------------------- + // Document scope request and response + // ------------------------------------- + + interface DocumentResponseRowMeta { + id: string; + key: string; + value: { + rev: string; + }; + } + + interface DocumentResponseRow extends DocumentResponseRowMeta { + doc?: D & Document; + } + + // http://docs.couchdb.org/en/latest/api/database/common.html#post--db + // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid + interface DocumentInsertParams { + // Document’s revision if updating an existing document. Alternative to If-Match header or document key. + rev?: string; + + // Stores document in batch mode. + batch?: "ok"; + + // Prevents insertion of a conflicting document. Possible values: true (default) and false. If false, a + // well-formed _rev must be included in the document. new_edits=false is used by the replicator to insert + // documents into the target database even if that leads to the creation of conflicts. + new_edits?: boolean; + } + + // http://docs.couchdb.org/en/latest/api/database/common.html#post--db + // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid + interface DocumentInsertResponse { + // Document ID + id: string; + + // Operation status + ok: boolean; + + // Revision MVCC token + rev: string; + } + + // http://docs.couchdb.org/en/latest/api/document/common.html#delete--db-docid + interface DocumentDestroyResponse { + // Document ID + id: string; + + // Operation status + ok: boolean; + + // Revision MVCC token + rev: string; + } + + // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid + interface DocumentGetParams { + // Includes attachments bodies in response. Default is false. + attachments?: boolean; + + // Includes encoding information in attachment stubs if the particular attachment is compressed. Default is + // false. + att_encoding_info?: boolean; + + // Includes attachments only since specified revisions. Doesn’t includes attachments for specified revisions. + atts_since?: any[]; + + // Includes information about conflicts in document. Default is false. + conflicts?: boolean; + + // Includes information about deleted conflicted revisions. Default is false. + deleted_conflicts?: boolean; + + // Forces retrieving latest “leaf” revision, no matter what rev was requested. Default is false. + latest?: boolean; + + // Includes last update sequence for the document. Default is false. + local_seq?: boolean; + + // Acts same as specifying all conflicts, deleted_conflicts and revs_info query parameters. Default is false. + meta?: boolean; + + // Retrieves documents of specified leaf revisions. Additionally, it accepts value as all to return all leaf + // revisions. + open_revs?: any[]; + + // Retrieves document of specified revision. + rev?: string; + + // Includes list of all known document revisions. + revs?: boolean; + + // Includes detailed information for all known document revisions. Default is false. + revs_info?: boolean; + } + + // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid + interface DocumentGetResponse { + // Document ID. + _id: string; + + // Revision MVCC token. + _rev: string; + + // Deletion flag. Available if document was removed. + _deleted?: boolean; + + // Attachment’s stubs. Available if document has any attachments. + _attachments?: any; + + // List of conflicted revisions. Available if requested with conflicts=true query parameter. + _conflicts?: any[]; + + // List of deleted conflicted revisions. Available if requested with deleted_conflicts=true query parameter. + _deleted_conflicts?: any[]; + + // Document’s update sequence in current database. Available if requested with local_seq=true query parameter. + _local_seq?: string; + + // List of objects with information about local revisions and their status. Available if requested with + // open_revs query parameter. + _revs_info?: any[]; + + // List of local revision tokens without. Available if requested with revs=true query parameter. + _revisions?: any; + } + + interface DocumentCopyOptions { + overwrite?: boolean; + } + + // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid + interface DocumentCopyResponse { + // Document ID + id: string; + + // Operation status + ok: boolean; + + // Revision MVCC token + rev: string; + } + + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs + interface DocumentListParams { + // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. + conflicts?: boolean; + + // Return the documents in descending by key order. Default is false. + descending?: boolean; + + // Stop returning records when the specified key is reached. + end_key?: string; + + // Stop returning records when the specified document ID is reached. + end_key_doc_id?: string; + + // Include the full content of the documents in the return. Default is false. + include_docs?: boolean; + + // Specifies whether the specified end key should be included in the result. Default is true. + inclusive_end?: boolean; + + // Return only documents that match the specified key. + key?: string; + + // Return only documents that match the specified keys. + keys?: string; // This can be string[] too ??? + + // Limit the number of the returned documents to the specified number. + limit?: number; + + // Skip this number of records before starting to return the results. Default is 0. + skip?: number; + + // Allow the results from a stale view to be used, without triggering a rebuild of all views within the + // encompassing design doc. Supported values: ok and update_after. + stale?: string; + + // Return records starting with the specified key. + start_key?: string; + + // Return records starting with the specified document ID. + start_key_doc_id?: string; + + // Response includes an update_seq value indicating which sequence id of the underlying database the view + // reflects. Default is false. + update_seq?: boolean; + } + + // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs + interface DocumentListResponse { + // Offset where the document list started. + offset: number; + + // Array of view row objects. By default the information returned contains only the document ID and revision. + rows: Array>; + + // Number of documents in the database/view. Note that this is not the number of rows returned in the actual + // query. + total_rows: number; + + // Current update sequence for the database. + update_seq?: number; + } + + interface DocumentFetchParams { + conflicts?: boolean; + descending?: boolean; + end_key?: string; + end_key_doc_id?: string; + inclusive_end?: boolean; + key?: string; + keys?: string; // This can be string[] too ??? + limit?: number; + skip?: number; + stale?: string; + start_key?: string; + start_key_doc_id?: string; + update_seq?: boolean; + } + + interface DocumentFetchResponse { + offset: number; + rows: Array>; + total_rows: number; + update_seq?: number; + } + + interface DocumentFetchRevsResponse { + offset: number; + rows: DocumentResponseRowMeta[]; + total_rows: number; + update_seq?: number; + } + + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view + interface DocumentViewParams { + // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. + conflicts?: boolean; + + // Return the documents in descending by key order. Default is false. + descending?: boolean; + + // Stop returning records when the specified key is reached. + endkey?: any; + + // Alias for endkey param. + end_key?: any; + + // Stop returning records when the specified document ID is reached. Requires endkey to be specified for this + // to have any effect. + endkey_docid?: string; + + // Alias for endkey_docid param. + end_key_doc_id?: string; + + // Group the results using the reduce function to a group or single row. Default is false. + group?: boolean; + + // Specify the group level to be used. + group_level?: number; + + // Include the associated document with each row. Default is false. + include_docs?: boolean; + + // Include the Base64-encoded content of attachments in the documents that are included if include_docs is + // true. Ignored if include_docs isn’t true. Default is false. + attachments?: boolean; + + // Include encoding information in attachment stubs if include_docs is true and the particular attachment is + // compressed. Ignored if include_docs isn’t true. Default is false. + att_encoding_info?: boolean; + + // Specifies whether the specified end key should be included in the result. Default is true. + inclusive_end?: boolean; + + // Return only documents that match the specified key. + key?: any; + + // Return only documents where the key matches one of the keys specified in the array. + keys?: any[]; + + // Limit the number of the returned documents to the specified number. + limit?: number; + + // Use the reduction function. Default is true. + reduce?: boolean; + + // Skip this number of records before starting to return the results. Default is 0. + skip?: number; + + // Sort returned rows. Setting this to false offers a performance boost. The total_rows and offset fields are + // not available when this is set to false. Default is true. + sorted?: boolean; + + // Whether or not the view results should be returned from a stable set of shards. Default is false. + stable?: boolean; + // Allow the results from a stale view to be used. Supported values: ok, update_after and false. ok is + // equivalent to stable=true&update=false. update_after is equivalent to stable=true&update=lazy. false is + // equivalent to stable=false&update=true. + stale?: string; + + // Return records starting with the specified key. + startkey?: any; + + // Alias for startkey param + start_key?: any; + + // Return records starting with the specified document ID. Requires startkey to be specified for this to have + // any effect. + startkey_docid?: string; + + // Alias for startkey_docid param + start_key_doc_id?: string; + + // Whether or not the view in question should be updated prior to responding to the user. Supported values: + // true, false, lazy. Default is true. + update?: string; + + // Response includes an update_seq value indicating which sequence id of the database the view reflects. + // Default is false. + update_seq?: boolean; + } + + // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view + interface DocumentViewResponse { + // Offset where the document list started. + offset: number; + + // Array of view row objects. By default the information returned contains only the document ID and revision. + rows: Array<{ + id: string; + key: string; + value: V; + }>; + + // Number of documents in the database/view. + total_rows: number; + + // Current update sequence for the database + update_seq: any; + } } export = nano; diff --git a/types/nano/nano-tests.ts b/types/nano/nano-tests.ts index 33cfe4534d..2184ed822f 100644 --- a/types/nano/nano-tests.ts +++ b/types/nano/nano-tests.ts @@ -1,6 +1,5 @@ -import * as nano from "nano"; import * as fs from "fs"; -import * as path from "path"; +import * as nano from "nano"; /* * Instantiate with configuration object @@ -67,10 +66,15 @@ db.replicate("a", "b", (error: any) => {}); /* * Document Scope */ -const mydb: nano.DocumentScope = instance.use("mydb"); +interface SomeDocument { + name: string; +} -mydb.insert({ foo: "baz" }, null, (err, response) => {}); -mydb.insert({ foo: "baz" }, "foobar", (error, foo) => {}); +const mydb: nano.DocumentScope = instance.use("mydb"); + +mydb.insert({ name: "baz" }, null, (err, response) => {}); +mydb.insert({ name: "baz" }, "foobar", (error, foo) => {}); +mydb.insert({ name: "baz" }, { new_edits: true }, (error, foo) => {}); mydb.get("foobaz", { revs_info: true }, (error, foobaz) => {}); mydb.head("foobaz", (error, body, headers) => {}); mydb.copy( @@ -129,7 +133,7 @@ mydb.attachment.get("new_string", "att", (error: any, helloWorld: any) => {}); /* * Multipart */ -mydb.multipart.insert({ foo: "baz" }, [{}], "foobaz", (error, foo) => {}); +mydb.multipart.insert({ name: "baz" }, [{}], "foobaz", (error, foo) => {}); mydb.multipart.get("foobaz", (error: any, foobaz: any, headers: any) => {}); /* diff --git a/types/nano/tslint.json b/types/nano/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/nano/tslint.json +++ b/types/nano/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/navigation/index.d.ts b/types/navigation/index.d.ts index 6f05956a8a..fdc729f11c 100644 --- a/types/navigation/index.d.ts +++ b/types/navigation/index.d.ts @@ -347,6 +347,10 @@ export class StateContext { * Gets the NavigationData for the last displayed State */ oldData: any; + /** + * Gets the Url for the last displayed State + */ + oldUrl: string; /** * Gets the State of the last Crumb in the crumb trail */ @@ -355,6 +359,10 @@ export class StateContext { * Gets the NavigationData of the last Crumb in the crumb trail */ previousData: any; + /** + * Gets the Url of the last Crumb in the crumb trail + */ + previousUrl: string; /** * Gets the current State */ diff --git a/types/navigation/navigation-tests.ts b/types/navigation/navigation-tests.ts index f710670953..37e597f841 100644 --- a/types/navigation/navigation-tests.ts +++ b/types/navigation/navigation-tests.ts @@ -83,12 +83,14 @@ link = stateNavigator.fluent() // State Context let state: State = stateNavigator.stateContext.state; -const url: string = stateNavigator.stateContext.url; +let url: string = stateNavigator.stateContext.url; const title: string = stateNavigator.stateContext.title; let page: number = stateNavigator.stateContext.data.page; state = stateNavigator.stateContext.oldState; +url = stateNavigator.stateContext.oldUrl; page = stateNavigator.stateContext.oldData.page; state = stateNavigator.stateContext.previousState; +url = stateNavigator.stateContext.previousUrl; page = stateNavigator.stateContext.previousData.page; // Navigation Data diff --git a/types/nedb/tslint.json b/types/nedb/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/nedb/tslint.json +++ b/types/nedb/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index aab6827ed7..c5526049de 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -91,7 +91,7 @@ declare module nes { id: string; app: Object; auth: nes.SocketAuthObject; - disconect(callback?: () => void): void; + disconnect(callback?: () => void): void; send(message: any, callback?: (err?: any) => void): void; publish(path: string, message: any, callback?: (err?: any) => void): void; revoke(path: string, message: any, callback?: (err?: any) => void): void; diff --git a/types/nes/test/socket.ts b/types/nes/test/socket.ts new file mode 100644 index 0000000000..7f7617d462 --- /dev/null +++ b/types/nes/test/socket.ts @@ -0,0 +1,16 @@ +// from https://github.com/hapijs/nes/blob/v6.4.3/lib/socket.js + +import Nes = require('nes'); + +const socket: Nes.Socket = undefined; + +const cb = () => { }; +socket.disconnect(cb); +const s: string = socket.id; +const o: Object = socket.app; +const auth: Nes.SocketAuthObject = socket.auth; + +const cb2 = (err?: any) => { }; +socket.send('message', (err?: any) => { }); +socket.publish('path', 'message', cb2); +socket.revoke('path', 'message', cb2); diff --git a/types/nes/tsconfig.json b/types/nes/tsconfig.json index cb28129b71..c03d7c22ee 100644 --- a/types/nes/tsconfig.json +++ b/types/nes/tsconfig.json @@ -26,9 +26,10 @@ "test/route-authentication-server.ts", "test/route-invocation-client.ts", "test/route-invocation-server.ts", + "test/socket.ts", "test/subscription-filter-client.ts", "test/subscription-filter-server.ts", "test/subscriptions-client.ts", "test/subscriptions-server.ts" ] -} \ No newline at end of file +} diff --git a/types/next-redux-wrapper/tslint.json b/types/next-redux-wrapper/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/next-redux-wrapper/tslint.json +++ b/types/next-redux-wrapper/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/ngstorage/tslint.json b/types/ngstorage/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/ngstorage/tslint.json +++ b/types/ngstorage/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 1af05002d3..d40ffbd58c 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -5,7 +5,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 - +/// declare class Nightmare { constructor(options?: Nightmare.IConstructorOptions); @@ -95,7 +95,10 @@ declare class Nightmare { removeListener(event: 'prompt', cb: (msg: string, defaultValue?: string) => void): Nightmare; removeListener(event: 'error', cb: (msg: string, trace?: Nightmare.IStackTrace[]) => void): Nightmare; removeListener(event: 'timeout', cb: (msg: string) => void): Nightmare; - screenshot(path: string): Nightmare; + screenshot(done?: (err: any, buffer: Buffer) => void): Nightmare; + screenshot(path: string, done?: (err: any) => void): Nightmare; + screenshot(clip: { x: number, y: number, width: number, height: number }, done?: (err: any, buffer: Buffer) => void): Nightmare; + screenshot(path: string, clip?: { x: number, y: number, width: number, height: number }, done?: (err: any) => void): Nightmare; html(path: string, saveType: string): Nightmare; html(path: string, saveType: 'HTMLOnly'): Nightmare; html(path: string, saveType: 'HTMLComplete'): Nightmare; @@ -134,6 +137,9 @@ declare namespace Nightmare { cookiesFile?: string; phantomPath?: string; show?: boolean; + typeInterval?: number; + x?: number; + y?: number; } export interface IRequest { diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index 921e961538..434964bb20 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -1,9 +1,7 @@ - /// import Nightmare = require("nightmare"); - new Nightmare() .goto('http://yahoo.com') .type('input[title="Search"]', 'github nightmare') @@ -167,6 +165,25 @@ new Nightmare() .screenshot('test/test.png') .run(done); +new Nightmare() + .goto('http://yahoo.com') + .screenshot((err, buffer) => { + console.log(Buffer.isBuffer(buffer)); + }) + .run(done); + +new Nightmare() + .goto('http://yahoo.com') + .screenshot('test/test.png', { x: 10, y: 5, width: 10, height: 10}) + .run(done); + +new Nightmare() + .goto('http://yahoo.com') + .screenshot({ x: 10, y: 5, width: 10, height: 10}, (err, buffer) => { + console.log(Buffer.isBuffer(buffer)); + }) + .run(done); + new Nightmare() .goto('http://yahoo.com') .pdf('test/test.pdf') diff --git a/types/nightwatch/tslint.json b/types/nightwatch/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/nightwatch/tslint.json +++ b/types/nightwatch/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/node-cache/tslint.json b/types/node-cache/tslint.json index ad5a9e6918..6c1ac808bb 100644 --- a/types/node-cache/tslint.json +++ b/types/node-cache/tslint.json @@ -1,7 +1,8 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODO - "prefer-const": false - } -} \ No newline at end of file + "extends": "dtslint/dt.json", + "rules": { + // TODO + "prefer-const": false, + "no-unnecessary-generics": false + } +} diff --git a/types/node-ral/tslint.json b/types/node-ral/tslint.json index 96427e1ebe..5b248e6b6b 100644 --- a/types/node-ral/tslint.json +++ b/types/node-ral/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODOs "no-object-literal-type-assertion": false, - "only-arrow-functions": false - } -} \ No newline at end of file + "only-arrow-functions": false, + "no-unnecessary-generics": false + } +} diff --git a/types/node-rsa/tslint.json b/types/node-rsa/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/node-rsa/tslint.json +++ b/types/node-rsa/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 9c222b5350..cf79ab990f 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -23,6 +23,9 @@ * * ************************************************/ +/** inspector module types */ +/// + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: NodeJS.ConsoleConstructor; @@ -93,10 +96,17 @@ interface NodeRequireFunction { interface NodeRequire extends NodeRequireFunction { resolve(id: string): string; cache: any; - extensions: any; + extensions: NodeExtensions; main: NodeModule | undefined; } +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + declare var require: NodeRequire; interface NodeModule { @@ -1632,6 +1642,9 @@ declare module "repl" { export interface REPLServer extends readline.ReadLine { context: any; + inputStream: NodeJS.ReadableStream; + outputStream: NodeJS.WritableStream; + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; displayPrompt(preserveCursor?: boolean): void; @@ -1667,6 +1680,12 @@ declare module "repl" { } export function start(options?: string | ReplOptions): REPLServer; + + export class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } } declare module "readline" { @@ -5592,6 +5611,26 @@ declare module "constants" { export var ALPN_ENABLED: number; } +declare module "module" { + class Module implements NodeModule { + static runMain(): void; + static wrap(code: string): string; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + export = Module; +} + declare module "process" { export = process; } diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts new file mode 100644 index 0000000000..445f55410d --- /dev/null +++ b/types/node/inspector.d.ts @@ -0,0 +1,2479 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + export interface InspectorNotification { + method: string; + params: T; + } + + export namespace Schema { + /** + * Description of the protocol domain. + */ + export interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + export interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Schema.Domain[]; + } + } + + export namespace Runtime { + /** + * Unique script identifier. + */ + export type ScriptId = string; + + /** + * Unique object identifier. + */ + export type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. + */ + export type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + export interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: Runtime.UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: Runtime.RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: Runtime.ObjectPreview; + /** + * @experimental + */ + customPreview?: Runtime.CustomPreview; + } + + /** + * @experimental + */ + export interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: Runtime.RemoteObjectId; + bindRemoteObjectFunctionId: Runtime.RemoteObjectId; + configObjectId?: Runtime.RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + export interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: Runtime.PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: Runtime.EntryPreview[]; + } + + /** + * @experimental + */ + export interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: Runtime.ObjectPreview; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + export interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: Runtime.ObjectPreview; + /** + * Preview of the value. + */ + value: Runtime.ObjectPreview; + } + + /** + * Object property descriptor. + */ + export interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: Runtime.RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: Runtime.RemoteObject; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: Runtime.RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: Runtime.RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + export interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: Runtime.RemoteObject; + } + + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + export interface CallArgument { + /** + * Primitive value. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: Runtime.UnserializableValue; + /** + * Remote object handle. + */ + objectId?: Runtime.RemoteObjectId; + } + + /** + * Id of an execution context. + */ + export type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + export interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: Runtime.ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + export interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: Runtime.ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: Runtime.StackTrace; + /** + * Exception object if available. + */ + exception?: Runtime.RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: Runtime.ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + export type Timestamp = number; + + /** + * Stack entry for runtime errors and assertions. + */ + export interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + export interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: Runtime.CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: Runtime.StackTrace; + /** + * Creation frame of the Promise which produced the next synchronous trace when resolved, if available. + * @experimental + */ + promiseCreationFrame?: Runtime.CallFrame; + } + + export interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: Runtime.ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + * @experimental + */ + userGesture?: boolean; + /** + * Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error. + */ + awaitPromise?: boolean; + } + + export interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: Runtime.RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + export interface CallFunctionOnParameterType { + /** + * Identifier of the object to call function on. + */ + objectId: Runtime.RemoteObjectId; + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: Runtime.CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + * @experimental + */ + userGesture?: boolean; + /** + * Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error. + */ + awaitPromise?: boolean; + } + + export interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: Runtime.RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + export interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: Runtime.RemoteObjectId; + } + + export interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + export interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + export interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: Runtime.ExecutionContextId; + } + + export interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: Runtime.ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: Runtime.ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error. + */ + awaitPromise?: boolean; + } + + export interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: Runtime.RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: Runtime.PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: Runtime.InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: Runtime.ScriptId; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface RunScriptReturnType { + /** + * Run result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: Runtime.ExecutionContextDescription; + } + + export interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: Runtime.ExecutionContextId; + } + + export interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Runtime.Timestamp; + exceptionDetails: Runtime.ExceptionDetails; + } + + export interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionUnhandled. + */ + exceptionId: number; + } + + export interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: Runtime.RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Runtime.Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: Runtime.StackTrace; + } + + export interface InspectRequestedEventDataType { + object: Runtime.RemoteObject; + hints: {}; + } + } + + export namespace Debugger { + /** + * Breakpoint identifier. + */ + export type BreakpointId = string; + + /** + * Call frame identifier. + */ + export type CallFrameId = string; + + /** + * Location in the source code. + */ + export interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + export interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + export interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: Debugger.CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + * @experimental + */ + functionLocation?: Debugger.Location; + /** + * Location in the source code. + */ + location: Debugger.Location; + /** + * Scope chain for this call frame. + */ + scopeChain: Debugger.Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + export interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Debugger.Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Debugger.Location; + } + + /** + * Search match for resource. + * @experimental + */ + export interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + /** + * @experimental + */ + export interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + export interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + export interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + export interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + export interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Debugger.Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + export interface RemoveBreakpointParameterType { + breakpointId: Debugger.BreakpointId; + } + + export interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Debugger.Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Debugger.Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + export interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Debugger.Location; + /** + * @experimental + */ + targetCallFrames?: string; + } + + export interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + export interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean; + } + + export interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: Debugger.CallFrameId; + } + + export interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + export interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + export interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: Debugger.CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + } + + export interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: Debugger.CallFrameId; + } + + export interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + + export interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + export interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: Debugger.ScriptPosition[]; + } + + export interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: Debugger.BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Debugger.Location[]; + } + + export interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: Debugger.BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Debugger.Location; + } + + export interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: Debugger.BreakLocation[]; + } + + export interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: Debugger.SearchMatch[]; + } + + export interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: Debugger.CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: Debugger.CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + } + + export interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + export interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + export interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + * @experimental + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + * @experimental + */ + isModule?: boolean; + /** + * This script length. + * @experimental + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + export interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + * @experimental + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + * @experimental + */ + isModule?: boolean; + /** + * This script length. + * @experimental + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + export interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: Debugger.BreakpointId; + /** + * Actual breakpoint location. + */ + location: Debugger.Location; + } + + export interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: Debugger.CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + } + } + + export namespace Console { + /** + * Console message. + */ + export interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + export interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: Console.ConsoleMessage; + } + } + + export namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + export interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + * @experimental + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + * @experimental + */ + positionTicks?: Profiler.PositionTickInfo[]; + } + + /** + * Profile. + */ + export interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: Profiler.ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + * @experimental + */ + export interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + * @experimental + */ + export interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + * @experimental + */ + export interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: Profiler.CoverageRange[]; + } + + /** + * Coverage data for a JavaScript script. + * @experimental + */ + export interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: Profiler.FunctionCoverage[]; + } + + export interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + export interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + } + + export interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profiler.Profile; + } + + export interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: Profiler.ScriptCoverage[]; + } + + export interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: Profiler.ScriptCoverage[]; + } + + export interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + export interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profiler.Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + export namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + export type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + export interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: HeapProfiler.SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + export interface SamplingHeapProfile { + head: HeapProfiler.SamplingHeapProfileNode; + } + + export interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + export interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean; + } + + export interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + export interface GetObjectByHeapObjectIdParameterType { + objectId: HeapProfiler.HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + export interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapProfiler.HeapSnapshotObjectId; + } + + export interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + export interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number; + } + + export interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + export interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapProfiler.HeapSnapshotObjectId; + } + + export interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: HeapProfiler.SamplingHeapProfile; + } + + export interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + export interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + + export interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + export interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. An exception will be thrown if there is already a connected session established either through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + * @experimental + */ + post(method: "Debugger.getPossibleBreakpoints", params?: Debugger.GetPossibleBreakpointsParameterType, callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + * @experimental + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + * @experimental + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + * @experimental + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + * @experimental + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + * @experimental + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getObjectByHeapObjectId", params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + export function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + export function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + export function url(): string; +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 62ff37522d..2d341d6a92 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -28,6 +28,8 @@ import * as v8 from "v8"; import * as dns from "dns"; import * as async_hooks from "async_hooks"; import * as http2 from "http2"; +import * as inspector from "inspector"; +import Module = require("module"); // Specifically test buffer module regression. import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; @@ -2532,6 +2534,11 @@ namespace repl_tests { _server = _server.prependOnceListener("exit", () => { }); _server = _server.prependOnceListener("reset", () => { }); + + _server.outputStream.write("test"); + let line = _server.inputStream.read(); + + throw new repl.Recoverable(new Error("test")); } } @@ -3380,3 +3387,58 @@ namespace http2_tests { str = constants.HTTP2_METHOD_VERSION_CONTROL; } } + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +namespace inspector_tests { + { + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + 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'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails; + const resultClassName: string = params.result.className; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', (message: inspector.InspectorNotification) => {}); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + } +} + +//////////////////////////////////////////////////// +/// module tests : http://nodejs.org/api/modules.html +//////////////////////////////////////////////////// + +namespace module_tests { + require.extensions[".ts"] = () => ""; + + Module.runMain(); + Module.wrap("some code"); + + const m1 = new Module("moduleId"); +} diff --git a/types/node/scripts/generate-inspector/README.md b/types/node/scripts/generate-inspector/README.md new file mode 100644 index 0000000000..0c87321994 --- /dev/null +++ b/types/node/scripts/generate-inspector/README.md @@ -0,0 +1,14 @@ +The entry point to this script is `index.ts`. It takes a single, optional argument (a tag in node-core), using the current Node `process.version` in lieu of this argument. + +What this does is: +- Get the inspector protocol spec at the given tag +- Generate type definitions from it +- Write to `inspector.d.ts` + +For example, to bump `inspector.d.ts` to what's exposed in v8.4: +```sh +# cwd = types/node +ts-node scripts/generate-inspector v8.4.0 +``` + +Inspector type definitions should be updated every time the V8 version is bumped in a Node.js release. diff --git a/types/node/scripts/generate-inspector/devtools-protocol-schema.ts b/types/node/scripts/generate-inspector/devtools-protocol-schema.ts new file mode 100644 index 0000000000..aaa8c9712f --- /dev/null +++ b/types/node/scripts/generate-inspector/devtools-protocol-schema.ts @@ -0,0 +1,76 @@ +// This file reflects the known structure of the JSON data file that describes the v8 inspector protocol. +// https://github.com/nodejs/node/blob/master/deps/v8/src/inspector/js_protocol.json + +export interface Documentable { + description?: string; + deprecated?: boolean; + experimental?: boolean; +} + +export interface BaseType { + type: T; +} + +export interface StringType extends BaseType<"string"> { + enum?: string[]; +} + +export interface ArrayType extends BaseType<"array"> { + items: Field; + minItems?: number; + maxItems?: number; +} + +export interface ObjectDefinition extends BaseType<"object"> { + properties?: Parameter[]; +} + +export interface ObjectReference { + $ref: string; +} + +export type TypeDefinition = BaseType<"any"|"integer"|"number"|"boolean"> | + StringType | ArrayType | ObjectDefinition; + +export type Type = TypeDefinition & Documentable & { + id: string, +}; + +export type Field = TypeDefinition | ObjectReference; + +export type Parameter = Field & Documentable & { + name: string, + optional?: boolean, +}; + +export interface Command extends Documentable { + name: string; + description?: string; + handlers?: string[]; + parameters?: Parameter[]; + returns?: Parameter[]; + experimental?: boolean; + redirect?: string; +} + +export interface Event extends Documentable { + name: string; + parameters?: Parameter[]; + description?: string; +} + +// It should be safe to load a devtools-protocol/json file and cast it to +// this type. +export interface Schema { + version: { + major: string, + minor: string, + }; + domains: Array<{ + domain: string, + types?: Type[], + commands: Command[], + events?: Event[], + dependencies?: string[], + } & Documentable>; +} diff --git a/types/node/scripts/generate-inspector/event-emitter.ts b/types/node/scripts/generate-inspector/event-emitter.ts new file mode 100644 index 0000000000..658109d6b2 --- /dev/null +++ b/types/node/scripts/generate-inspector/event-emitter.ts @@ -0,0 +1,79 @@ +// This file describes helper functions to create definitions for EventEmitter +// prototype overloads. + +import { flattenArgs } from "./utils"; + +/** + * Information needed to generate definitions. + */ +export interface Event { + comment?: string[]; + name: string; + args: Array<{ + name: string, + type: string, + }>; +} + +const createEmitStatement = (event: Event): string[] => { + const argsStr = event.args.map(arg => `${arg.name}: ${arg.type}`).join(", "); + return [ + `emit(event: "${event.name}"${event.args.length > 0 ? ", " : ""}${argsStr}): boolean;`, + ]; +}; + +const createEmitBlock = (events: Event[]): string[] => { + return [ + `emit(event: string | symbol, ...args: any[]): boolean;`, + ...events.map(createEmitStatement).reduce(flattenArgs(), []), + ]; +}; + +const createListenerFn = (fnName: string) => (event: Event): string[] => { + const argsStr = event.args.map(arg => `${arg.name}: ${arg.type}`).join(", "); + return [ + ...event.comment && event.comment.length > 0 ? [""] : [], + ...event.comment || [], + `${fnName}(event: "${event.name}", listener: (${argsStr}) => void): this;`, + ...event.comment && event.comment.length > 0 ? [""] : [], + ]; +}; + +const createListenerBlockFn = (fnName: string) => (events: Event[]): string[] => { + return [ + `${fnName}(event: string, listener: (...args: any[]) => void): this;`, + ...events.map(createListenerFn(fnName)).reduce(flattenArgs(), []), + ]; +}; + +/** + * Given an array of Event objects, return a set of type definitions for + * overloads of addListener, emit, on, once, prependListener, and + * prependOnceListener as an array of lines. + * @param events The array of Event objects to transform into type definitions. + */ +export const createListeners = (events: Event[]): string[] => { + return [ + ...createListenerBlockFn("addListener")(events), + "", + ...createEmitBlock(events), + "", + ...createListenerBlockFn("on")(events), + "", + ...createListenerBlockFn("once")(events), + "", + ...createListenerBlockFn("prependListener")(events), + "", + ...createListenerBlockFn("prependOnceListener")(events), + ].reduce((acc, next, index, arr) => { + // removes trailing and consecutive empty lines + const isLast = index === arr.length - 1; + const followsEmptyLine = acc.length > 0 && acc[acc.length - 1] === ""; + if ((isLast || followsEmptyLine) && next === "") { + return acc; + } else { + acc.push(next); + return acc; + } + }, []); +}; diff --git a/types/node/scripts/generate-inspector/generate-substitute-args.ts b/types/node/scripts/generate-inspector/generate-substitute-args.ts new file mode 100644 index 0000000000..ab5fb15840 --- /dev/null +++ b/types/node/scripts/generate-inspector/generate-substitute-args.ts @@ -0,0 +1,164 @@ +import * as schema from "./devtools-protocol-schema"; +import { createListeners } from "./event-emitter"; +import { capitalize, createDocs, flattenArgs, hasElements, isObjectReference, resolveReference } from "./utils"; + +const INDENT = " "; + +// Converts DevTools type to TS type +const createTypeString = (type: schema.Field, domain?: string): string => { + return isObjectReference(type) ? resolveReference(type.$ref, domain) : + type.type === "any" ? "any" : + type.type === "integer" ? "number" : + type.type === "number" ? "number" : + type.type === "boolean" ? "boolean" : + type.type === "string" ? "string" : + type.type === "array" ? `${createTypeString(type.items, domain)}[]` : + type.type === "object" ? "{}" // this code path is likely never exercised + : "never"; +}; + +// Helper for createInterface -- constructs a list of interface fields +const createFieldsForInterface = (fields: schema.Parameter[] | null, domain: string): string[] => { + return fields ? [ + ...fields + .map(prop => [ + ...createDocs(prop), + `${prop.name}${prop.optional ? "?" : ""}: ${createTypeString(prop, domain)};`, + ]) + .reduce(flattenArgs(), []), + ] : []; +}; + +// Create an interface or type definition (the latter if the given type isn't an object) +const createTypeDefinition = (type: schema.Type, domain: string): string[] => { + return [ + ...createDocs(type), + ...(type.type === "object" ? [ + `export interface ${type.id} {`, + ...createFieldsForInterface(type.properties, domain) + .map(line => `${INDENT}${line}`), + "}", + ] : [`export type ${type.id} = ${createTypeString(type)};`]), + ]; +}; + +// Helper for for createPostFunctions -- returns the type of a callback +const createCallbackString = (commandName: string, returns: schema.Parameter[], domain: string): string => { + return hasElements(returns) ? + `(err: Error | null, params: ${domain}.${capitalize(commandName)}ReturnType) => void` : + `(err: Error | null) => void`; +}; + +// Create declarations for overloads of Session#post +const createPostFunctions = (command: schema.Command, domain: string): string[] => { + const fnName = "post"; + const callbackStr = createCallbackString(command.name, command.returns, domain); + const result = createDocs(command); + if (hasElements(command.parameters)) { + result.push([ + `${fnName}(`, + `method: "${domain}.${command.name}", `, + `params?: ${domain}.${capitalize(command.name)}ParameterType, `, + `callback?: ${callbackStr}`, + "): void;", + ].join("")); + } + result.push([ + `${fnName}(`, + `method: "${domain}.${command.name}", `, + `callback?: ${callbackStr}`, + "): void;", + ].join("")); + return result; +}; + +/** + * Given a parsed DevTools Protocol data file, generate an object that contains text values suitable for being + * substituted into ./inspector.d.ts.template. + * @param protocol The parsed contents of the JSON file from which the DevTools Protocol docs are generated. + */ +export const generateSubstituteArgs = (protocol: schema.Schema): { [propName: string]: string[] } => { + const interfaceDefinitions: string[] = protocol.domains + .map(item => { + const typePool = (item.types || []).concat([ + ...(item.commands || []).map(command => { + let result: schema.Type = null; + if (hasElements(command.parameters)) { + result = { + id: `${capitalize(command.name)}ParameterType`, + type: "object", + properties: command.parameters, + }; + } + return result; + }), + ...(item.commands || []).map(command => { + let result: schema.Type = null; + if (hasElements(command.returns)) { + result = { + id: `${capitalize(command.name)}ReturnType`, + type: "object", + properties: command.returns, + }; + } + return result; + }), + ...(item.events || []).map(event => { + let result: schema.Type = null; + if (hasElements(event.parameters)) { + result = { + id: `${capitalize(event.name)}EventDataType`, + type: "object", + properties: event.parameters, + }; + } + return result; + }), + ].filter(x => x)); + return typePool.length > 0 ? [ + `export namespace ${item.domain} {`, + ...typePool + .map(type => createTypeDefinition(type, item.domain)) + .reduce(flattenArgs("")) + .map(line => `${INDENT}${line}`), + "}", + ] : []; + }).reduce(flattenArgs(""), []); + + const postOverloads: string[] = protocol.domains + .map(item => item.commands + .map(command => createPostFunctions(command, item.domain)) + .reduce(flattenArgs(""), [])) + .reduce(flattenArgs(), []); + + const eventOverloads: string[] = createListeners(protocol.domains + .map(item => { + if (!item.events || item.events.length === 0) { + return []; + } + return item.events + .map(event => ({ + comment: createDocs(event), + name: `${item.domain}.${event.name}`, + args: hasElements(event.parameters) ? [{ + name: "message", + type: `InspectorNotification<${item.domain}.${capitalize(event.name)}EventDataType>`, + }] : [], + })); + }) + .reduce((acc, next) => acc.concat(next), [{ + comment: [ + "/**", + " * Emitted when any notification from the V8 Inspector is received.", + " */", + ], + name: "inspectorNotification", + args: [{ name: "message", type: "InspectorNotification<{}>" }], + }])); + + return { + interfaceDefinitions, + postOverloads, + eventOverloads, + }; +}; diff --git a/types/node/scripts/generate-inspector/index.ts b/types/node/scripts/generate-inspector/index.ts new file mode 100644 index 0000000000..eb5da5ef2e --- /dev/null +++ b/types/node/scripts/generate-inspector/index.ts @@ -0,0 +1,39 @@ +// Usage: node generate-inspector [tag] +// [tag] corresponds to a tag name in the node-core repository. + +import { execSync } from "child_process"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import * as https from "https"; +import * as schema from "./devtools-protocol-schema"; +import { generateSubstituteArgs } from "./generate-substitute-args"; +import { flattenArgs, substitute, trimRight } from "./utils"; + +// Input arguments +const tag = process.argv[2] || process.version; + +const PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; + +const devToolsPath = `${__dirname}/../../node_modules/devtools-protocol`; + +function writeProtocolToFile(json: string) { + const protocol: schema.Schema = JSON.parse(json); + + const template = readFileSync(`${__dirname}/inspector.d.ts.template`, "utf8"); + + const substituteArgs = generateSubstituteArgs(protocol); + const inspectorDts = substitute(template, substituteArgs).split("\n") + .map(line => trimRight(line)) + .join("\n"); + + writeFileSync("./inspector.d.ts", inspectorDts, "utf8"); +} + +https.get(PROTOCOL_URL, res => { + const frames: Buffer[] = []; + res.on("data", (data: Buffer) => { + frames.push(data); + }); + res.on("end", () => { + writeProtocolToFile(Buffer.concat(frames).toString("utf8")); + }); +}); diff --git a/types/node/scripts/generate-inspector/inspector.d.ts.template b/types/node/scripts/generate-inspector/inspector.d.ts.template new file mode 100644 index 0000000000..06ad692752 --- /dev/null +++ b/types/node/scripts/generate-inspector/inspector.d.ts.template @@ -0,0 +1,72 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + export interface InspectorNotification { + method: string; + params: T; + } + + // # interfaceDefinitions + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + export class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. An exception will be thrown if there is already a connected session established either through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. session.connect() will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + // # postOverloads + + // Events + + // # eventOverloads + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + export function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + export function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + export function url(): string; +} diff --git a/types/node/scripts/generate-inspector/utils.ts b/types/node/scripts/generate-inspector/utils.ts new file mode 100644 index 0000000000..9fd2f4a6b7 --- /dev/null +++ b/types/node/scripts/generate-inspector/utils.ts @@ -0,0 +1,111 @@ +// Utility functions + +import { Documentable, Field, ObjectReference } from "./devtools-protocol-schema"; + +/** + * Returns a function suitable for Array#reduce that flattens an array of + * arrays. + * @param inBetween A value to insert between groups of flattened values + */ +export function flattenArgs(inBetween?: T) { + if (inBetween != null) { + return (acc: T[], next: T[]) => { + if (acc.length > 0) { + return acc.concat([inBetween], next); + } else { + return acc.concat(next); + } + }; + } else { + return (acc: T[], next: T[]) => acc.concat(next); + } +} + +/** + * Returns whether an array exists and has elements. + * @param a The array to check. + */ +export const hasElements = (a: any[]): boolean => a && a.length > 0; + +/** + * Returns the capitalized form of a given string. + * @param s The string to capitalize + */ +export const capitalize = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1); + +/** + * Returns whether a given object is an ObjectReference. + * @param t An object whose type should be checked + */ +export function isObjectReference(t: Field): t is ObjectReference { + return "$ref" in t; +} + +/** + * Given a Documentable object, return a comment block generated from its + * contents, or an empty array if the object doesn't contain any information + * to populate a comment block. + * @param documentable A Documentable object. + */ +export const createDocs = (documentable: Documentable): string[] => { + const hasDocs = !!documentable.description || + documentable.deprecated || + documentable.experimental; + return hasDocs ? [ + "/**", + documentable.description && ` * ${documentable.description}`, + documentable.deprecated && " * @deprecated", + documentable.experimental && " * @experimental", + " */", + ].filter(l => l != null) : []; +}; + +/** + * Given a string, prepend a given domain string to it if applicable. + * @param ref The name of a class within a domain to reference. + * @param domain The domain string to prepend. + */ +export const resolveReference = (ref: string, domain?: string): string => { + if (!domain || ref.indexOf(".") !== -1) { + return ref; + } else { + return `${domain}.${ref}`; + } +}; + +/** + * Given a string, replace lines that match a known pattern (...// # propName) + * with args[propName] if it exists. + * @param str The input string. + * @param args An object mapping strings to arrays of strings. + */ +export const substitute = ( + str: string, + args: { [propName: string]: string[] }, +): string => { + return str.split("\n") + .map(line => { + const regex = /(\s*)\/\/ # (.*)/; + const matches = line.match(regex); + if (matches) { + const [_0, prefix, argName] = matches; + if (args[argName]) { + return args[argName].map(l => prefix + l); + } else { + return []; + } + } + return [line]; + }) + .reduce(flattenArgs(), []) + .join("\n"); +}; + +export const trimRight = (s: string): string => { + // TODO(kjin): This is terrible + const numTrailingSpaces: number = s.split("").reverse().findIndex(c => c !== " "); + if (numTrailingSpaces === -1) { + return ""; + } + return s.slice(0, s.length - numTrailingSpaces); +}; diff --git a/types/node/tslint.json b/types/node/tslint.json index 43f90d97f7..e60d5e7de9 100644 --- a/types/node/tslint.json +++ b/types/node/tslint.json @@ -5,12 +5,14 @@ "ban-types": false, "dt-header": false, "max-line-length": false, + "no-any-union": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-inferrable-types": false, "no-internal-module": false, "no-namespace": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-var-keyword": false, "prefer-const": false, diff --git a/types/node/v0/tslint.json b/types/node/v0/tslint.json index 3e842be21f..f4eb951ec6 100644 --- a/types/node/v0/tslint.json +++ b/types/node/v0/tslint.json @@ -23,6 +23,7 @@ "no-namespace": false, "no-padding": false, "no-string-throw": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-var-keyword": false, "object-literal-shorthand": false, diff --git a/types/node/v4/tslint.json b/types/node/v4/tslint.json index 421a4fe663..86acdea96f 100644 --- a/types/node/v4/tslint.json +++ b/types/node/v4/tslint.json @@ -13,6 +13,7 @@ "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, + "no-any-union": false, "no-consecutive-blank-lines": false, "no-duplicate-imports": false, "no-duplicate-variable": false, @@ -23,6 +24,7 @@ "no-namespace": false, "no-padding": false, "no-string-throw": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-var-keyword": false, "object-literal-shorthand": false, diff --git a/types/node/v6/tslint.json b/types/node/v6/tslint.json index 421a4fe663..86acdea96f 100644 --- a/types/node/v6/tslint.json +++ b/types/node/v6/tslint.json @@ -13,6 +13,7 @@ "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, + "no-any-union": false, "no-consecutive-blank-lines": false, "no-duplicate-imports": false, "no-duplicate-variable": false, @@ -23,6 +24,7 @@ "no-namespace": false, "no-padding": false, "no-string-throw": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-var-keyword": false, "object-literal-shorthand": false, diff --git a/types/node/v7/tslint.json b/types/node/v7/tslint.json index 421a4fe663..86acdea96f 100644 --- a/types/node/v7/tslint.json +++ b/types/node/v7/tslint.json @@ -13,6 +13,7 @@ "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, + "no-any-union": false, "no-consecutive-blank-lines": false, "no-duplicate-imports": false, "no-duplicate-variable": false, @@ -23,6 +24,7 @@ "no-namespace": false, "no-padding": false, "no-string-throw": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-var-keyword": false, "object-literal-shorthand": false, diff --git a/types/numjs/tslint.json b/types/numjs/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/numjs/tslint.json +++ b/types/numjs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/oauth2-server/tslint.json b/types/oauth2-server/tslint.json index f93cf8562a..b1439230db 100644 --- a/types/oauth2-server/tslint.json +++ b/types/oauth2-server/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } } diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 7a6ca787f7..d149ef18bc 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -12578,11 +12578,15 @@ declare module olx { /** - * @typedef {{duration: (number|undefined), + * @typedef {{constrainResolution: (boolean|undefined), + * duration: (number|undefined), + * timeout: (number|undefined), * useAnchor: (boolean|undefined)}} */ interface MouseWheelZoomOptions { + constrainResolution?: boolean; duration?: number; + timeout?: number; useAnchor?: boolean; } @@ -12598,9 +12602,11 @@ declare module olx { /** - * @typedef {{duration: (number|undefined)}} + * @typedef {{constrainResolution: (boolean|undefined) + * duration: (number|undefined)}} */ interface PinchZoomOptions { + constrainResolution?: boolean; duration?: number; } diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index f0abcf28ce..f35c0adc98 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -717,6 +717,17 @@ const select: ol.interaction.Select = new ol.interaction.Select({ layers: (layer: ol.layer.Layer) => true, }); +let pinchZoom: ol.interaction.PinchZoom = new ol.interaction.PinchZoom({ + constrainResolution: booleanValue, + duration: numberValue +}); + +let mouseWheelZoom: ol.interaction.MouseWheelZoom = new ol.interaction.MouseWheelZoom({ + constrainResolution: booleanValue, + duration: numberValue, + timeout: numberValue, + useAnchor: booleanValue +}); // // ol.style.RegularShape // diff --git a/types/orientjs/tslint.json b/types/orientjs/tslint.json index 3db14f85ea..3393f9dcca 100644 --- a/types/orientjs/tslint.json +++ b/types/orientjs/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false, + "no-unnecessary-generics": false + } +} diff --git a/types/p-defer/tslint.json b/types/p-defer/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/p-defer/tslint.json +++ b/types/p-defer/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/p-props/tslint.json b/types/p-props/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/p-props/tslint.json +++ b/types/p-props/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 1910899551..82194e65a2 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for parse 2.2 +// Type definitions for parse 2.4 // Project: https://parse.com/ // Definitions by: Ullisen Media Group // David Poetzsch-Heffter // Cedric Kemp +// Flavio Negrão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -96,7 +97,7 @@ 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; then(resolvedCallback: (...values: T[]) => U, @@ -189,7 +190,7 @@ declare namespace Parse { * this is omitted, the content type will be inferred from the name's * extension. */ - class File { + class File { constructor(name: string, data: any, type?: string); name(): string; @@ -331,8 +332,8 @@ declare namespace Parse { static extend(className: string, protoProps?: any, classProps?: any): any; static fromJSON(json: any, override: boolean): any; - static fetchAll(list: T[], options: SuccessFailureOptions): Promise; - static fetchAllIfNeeded(list: T[], options: SuccessFailureOptions): Promise; + static fetchAll(list: T[], options: Object.FetchAllOptions): Promise; + static fetchAllIfNeeded(list: T[], options: Object.FetchAllOptions): Promise; static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; static registerSubclass(className: string, clazz: new (options?: any) => T): void; @@ -375,6 +376,8 @@ declare namespace Parse { interface DestroyAllOptions extends SuccessFailureOptions, ScopeOptions { } + interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions { } + interface FetchOptions extends SuccessFailureOptions, ScopeOptions { } interface SaveOptions extends SuccessFailureOptions, SilentOption, ScopeOptions, WaitOption { } @@ -582,7 +585,7 @@ declare namespace Parse { className: string; constructor(objectClass: string); - constructor(objectClass: new(...args: any[]) => T); + constructor(objectClass: new (...args: any[]) => T); static or(...var_args: Query[]): Query; @@ -886,11 +889,17 @@ declare namespace Parse { object: Object; } - interface AfterSaveRequest extends TriggerRequest {} - interface AfterDeleteRequest extends TriggerRequest {} - interface BeforeDeleteRequest extends TriggerRequest {} - interface BeforeDeleteResponse extends FunctionResponse {} - interface BeforeSaveRequest extends TriggerRequest {} + interface BeforeFindTriggerRequest extends TriggerRequest { + query?: Query + count?: boolean + } + + interface AfterSaveRequest extends TriggerRequest { } + interface AfterDeleteRequest extends TriggerRequest { } + interface BeforeDeleteRequest extends TriggerRequest { } + interface BeforeDeleteResponse extends FunctionResponse { } + interface BeforeSaveRequest extends TriggerRequest { } + interface BeforeFindRequest extends BeforeFindTriggerRequest { } interface BeforeSaveResponse extends FunctionResponse { success: () => void; } @@ -970,56 +979,56 @@ declare namespace Parse { OTHER_CAUSE = -1, INTERNAL_SERVER_ERROR = 1, - CONNECTION_FAILED = 100, - OBJECT_NOT_FOUND = 101, - INVALID_QUERY = 102, - INVALID_CLASS_NAME = 103, - MISSING_OBJECT_ID = 104, - INVALID_KEY_NAME = 105, - INVALID_POINTER = 106, - INVALID_JSON = 107, - COMMAND_UNAVAILABLE = 108, - NOT_INITIALIZED = 109, - INCORRECT_TYPE = 111, - INVALID_CHANNEL_NAME = 112, - PUSH_MISCONFIGURED = 115, - OBJECT_TOO_LARGE = 116, - OPERATION_FORBIDDEN = 119, - CACHE_MISS = 120, - INVALID_NESTED_KEY = 121, - INVALID_FILE_NAME = 122, - INVALID_ACL = 123, - TIMEOUT = 124, - INVALID_EMAIL_ADDRESS = 125, - MISSING_CONTENT_TYPE = 126, - MISSING_CONTENT_LENGTH = 127, - INVALID_CONTENT_LENGTH = 128, - FILE_TOO_LARGE = 129, - FILE_SAVE_ERROR = 130, - DUPLICATE_VALUE = 137, - INVALID_ROLE_NAME = 139, - EXCEEDED_QUOTA = 140, - SCRIPT_FAILED = 141, - VALIDATION_ERROR = 142, - INVALID_IMAGE_DATA = 150, - UNSAVED_FILE_ERROR = 151, + CONNECTION_FAILED = 100, + OBJECT_NOT_FOUND = 101, + INVALID_QUERY = 102, + INVALID_CLASS_NAME = 103, + MISSING_OBJECT_ID = 104, + INVALID_KEY_NAME = 105, + INVALID_POINTER = 106, + INVALID_JSON = 107, + COMMAND_UNAVAILABLE = 108, + NOT_INITIALIZED = 109, + INCORRECT_TYPE = 111, + INVALID_CHANNEL_NAME = 112, + PUSH_MISCONFIGURED = 115, + OBJECT_TOO_LARGE = 116, + OPERATION_FORBIDDEN = 119, + CACHE_MISS = 120, + INVALID_NESTED_KEY = 121, + INVALID_FILE_NAME = 122, + INVALID_ACL = 123, + TIMEOUT = 124, + INVALID_EMAIL_ADDRESS = 125, + MISSING_CONTENT_TYPE = 126, + MISSING_CONTENT_LENGTH = 127, + INVALID_CONTENT_LENGTH = 128, + FILE_TOO_LARGE = 129, + FILE_SAVE_ERROR = 130, + DUPLICATE_VALUE = 137, + INVALID_ROLE_NAME = 139, + EXCEEDED_QUOTA = 140, + SCRIPT_FAILED = 141, + VALIDATION_ERROR = 142, + INVALID_IMAGE_DATA = 150, + UNSAVED_FILE_ERROR = 151, INVALID_PUSH_TIME_ERROR = 152, FILE_DELETE_ERROR = 153, REQUEST_LIMIT_EXCEEDED = 155, INVALID_EVENT_NAME = 160, - USERNAME_MISSING = 200, - PASSWORD_MISSING = 201, - USERNAME_TAKEN = 202, - EMAIL_TAKEN = 203, - EMAIL_MISSING = 204, - EMAIL_NOT_FOUND = 205, - SESSION_MISSING = 206, - MUST_CREATE_USER_THROUGH_SIGNUP = 207, - ACCOUNT_ALREADY_LINKED = 208, + USERNAME_MISSING = 200, + PASSWORD_MISSING = 201, + USERNAME_TAKEN = 202, + EMAIL_TAKEN = 203, + EMAIL_MISSING = 204, + EMAIL_NOT_FOUND = 205, + SESSION_MISSING = 206, + MUST_CREATE_USER_THROUGH_SIGNUP = 207, + ACCOUNT_ALREADY_LINKED = 208, INVALID_SESSION_TOKEN = 209, - LINKED_ID_MISSING = 250, - INVALID_LINKED_SESSION = 251, - UNSUPPORTED_SERVICE = 252, + LINKED_ID_MISSING = 250, + INVALID_LINKED_SESSION = 251, + UNSUPPORTED_SERVICE = 252, AGGREGATE_ERROR = 600, FILE_READ_ERROR = 601, X_DOMAIN_REQUEST = 602 diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index e380188f72..76440e46d3 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -38,10 +38,10 @@ function test_object() { var game = new Game(); game.fetch({ - success(g: Game) {} + success(g: Game) { } }); -// Create a new instance of that class. + // Create a new instance of that class. var gameScore = new GameScore(); gameScore.set("score", 1337); @@ -93,11 +93,11 @@ function test_query() { // Finds scores from any of Jonathan, Dario, or Shawn query.containedIn("playerName", - ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); + ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); // Finds scores from anyone who is neither Jonathan, Dario, nor Shawn query.notContainedIn("playerName", - ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); + ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); // Finds objects that have the score set query.exists("score"); @@ -154,9 +154,9 @@ function test_collections() { }; collection.add([ - {"name": "Duke"}, - {"name": "Scarlett"} - ]); + { "name": "Duke" }, + { "name": "Scarlett" } + ]); collection.fetch().then( (data) => { @@ -177,9 +177,9 @@ function test_collections() { // Completely replace all items in the collection. collection.reset([ - {"name": "Hawk"}, - {"name": "Jane"} - ]); + { "name": "Hawk" }, + { "name": "Jane" } + ]); } function test_file() { @@ -187,7 +187,7 @@ function test_file() { var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; var file = new Parse.File("myfile.txt", { base64: base64 }); - var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ]; + var bytes = [0xBE, 0xEF, 0xCA, 0xFE]; var file = new Parse.File("myfile.txt", bytes); var file = new Parse.File("myfile.zzz", {}, "image/png"); @@ -195,12 +195,12 @@ function test_file() { var src = file.url(); file.save().then( - () => { - // The file has been saved to Parse. - }, - (error) => { - // The file either could n ot be read, or could not be saved to Parse. - }); + () => { + // The file has been saved to Parse. + }, + (error) => { + // The file either could n ot be read, or could not be saved to Parse. + }); Parse.Cloud.httpRequest({ url: file.url() }).then((response: Parse.Cloud.HttpResponse) => { // result @@ -219,7 +219,7 @@ function test_analytics() { // Do searches happen more often on weekdays or weekends? dayType: 'weekday' }; - // Send the dimensions to Parse along with the 'search' event + // Send the dimensions to Parse along with the 'search' event Parse.Analytics.track('search', dimensions); var codeString = '404'; @@ -227,7 +227,7 @@ function test_analytics() { } function test_relation() { - new Parse.User().relation("games").query().find().then((g: Game[]) => {}); + new Parse.User().relation("games").query().find().then((g: Game[]) => { }); } function test_user_acl_roles() { @@ -237,7 +237,7 @@ function test_user_acl_roles() { user.set("password", "my pass"); user.set("email", "email@example.com"); -// other fields can be set just like with Parse.Object + // other fields can be set just like with Parse.Object user.set("phone", "415-392-0202"); var currentUser = Parse.User.current(); @@ -256,7 +256,7 @@ function test_user_acl_roles() { var game = new Game(); game.set("score", new GameScore()); game.setACL(new Parse.ACL(Parse.User.current())); - game.save().then((game: Game) => {}); + game.save().then((game: Game) => { }); game.save(null, { useMasterKey: true }); var groupACL = new Parse.ACL(); @@ -285,18 +285,18 @@ function test_user_acl_roles() { role.save(); Parse.User.logOut().then(function (data) { - // logged out + // logged out }); } function test_facebook_util() { Parse.FacebookUtils.init({ - appId : 'YOUR_APP_ID', // Facebook App ID - channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File - cookie : true, // enable cookies to allow Parse to access the session - xfbml : true // parse XFBML - }); + appId: 'YOUR_APP_ID', // Facebook App ID + channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File + cookie: true, // enable cookies to allow Parse to access the session + xfbml: true // parse XFBML + }); Parse.FacebookUtils.logIn(null, { success: (user: Parse.User) => { @@ -350,16 +350,23 @@ function test_cloud_functions() { }); Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest, - response: Parse.Cloud.BeforeDeleteResponse) => { + response: Parse.Cloud.BeforeDeleteResponse) => { // result }); + + Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + let query = request.query; // the Parse.Query + let user = request.user; // the user + let isMaster = request.master; // if the query is run with masterKey + let isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up) + }); } -class PlaceObject extends Parse.Object {} +class PlaceObject extends Parse.Object { } function test_geo_points() { - var point = new Parse.GeoPoint({latitude: 40.0, longitude: -30.0}); + var point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 }); var userObject = Parse.User.current()!; @@ -368,9 +375,9 @@ function test_geo_points() { // Create a query for places var query = new Parse.Query(Parse.User); -// Interested in locations near user. + // Interested in locations near user. query.near("location", userGeoPoint); - // Limit what could be a lot of points. + // Limit what could be a lot of points. query.limit(10); var southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); @@ -379,24 +386,24 @@ function test_geo_points() { var query2 = new Parse.Query(PlaceObject); query2.withinGeoBox("location", southwestOfSF, northeastOfSF); - var query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => {}); + var query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => { }); } function test_push() { Parse.Push.send({ - channels: [ "Gia nts", "Mets" ], + channels: ["Gia nts", "Mets"], data: { alert: "The Giants won against the Mets 2-3." } }, { - success: () => { - // Push was successful - }, - error: (error: any) => { - // Handle error - } - }); + success: () => { + // Push was successful + }, + error: (error: any) => { + // Handle error + } + }); var query = new Parse.Query(Parse.Installation); query.equalTo('injuryReports', true); @@ -407,13 +414,13 @@ function test_push() { alert: "Willie Hayes injured by own pop fly." } }, { - success: function() { - // Push was successful - }, - error: function(error: any) { - // Handle error - } - }); + success: function () { + // Push was successful + }, + error: function (error: any) { + // Handle error + } + }); } function test_view() { @@ -425,12 +432,31 @@ function test_view() { function test_promise() { let resolved = Parse.Promise.as(true); let rejected = Parse.Promise.error("an error object"); - Parse.Promise.when([resolved, rejected]).then(function() { + Parse.Promise.when([resolved, rejected]).then(function () { // success - }, function() { + }, function () { // failed }); // can check whether an object is a Parse.Promise object or not Parse.Promise.is(resolved); } + +function test_batch_operations() { + const game1 = new Game() + const game2 = new Game() + const games = [game1, game2] + + // Master key + Parse.Object.saveAll(games, { useMasterKey: true }) + Parse.Object.destroyAll(games, { useMasterKey: true }) + Parse.Object.fetchAll(games, { useMasterKey: true }) + Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true }) + + // Session token + Parse.Object.saveAll(games, { sessionToken: '' }) + Parse.Object.destroyAll(games, { sessionToken: '' }) + Parse.Object.fetchAll(games, { sessionToken: '' }) + Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' }) +} + diff --git a/types/parsimmon/tslint.json b/types/parsimmon/tslint.json index a2a1386037..e6f86832c0 100644 --- a/types/parsimmon/tslint.json +++ b/types/parsimmon/tslint.json @@ -1,8 +1,9 @@ { - "extends": "dtslint/dt.json", - "rules": { - // TODOs - "no-unnecessary-qualifier": false, - "no-boolean-literal-compare": false - } + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-unnecessary-qualifier": false, + "no-boolean-literal-compare": false, + "no-unnecessary-generics": false + } } diff --git a/types/pg-query-stream/pg-query-stream-tests.ts b/types/pg-query-stream/pg-query-stream-tests.ts index 6c4c034102..1df78ea648 100644 --- a/types/pg-query-stream/pg-query-stream-tests.ts +++ b/types/pg-query-stream/pg-query-stream-tests.ts @@ -8,7 +8,8 @@ const options: QueryStream.Options = { const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [1000000], options); -pg.connect('', (err, client, done) => { +const pool = new pg.Pool(); +pool.connect((err, client, done) => { const stream = client.query(query); stream.on('end', () => { client.end(); @@ -17,3 +18,4 @@ pg.connect('', (err, client, done) => { console.log(data); }); }); +pool.end(); diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index da6f4db575..f98f952884 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pg 6.1 +// Type definitions for pg 7.1 // Project: https://github.com/brianc/node-postgres -// Definitions by: Phips Peter +// Definitions by: Phips Peter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,16 +9,13 @@ import events = require("events"); import stream = require("stream"); import pgTypes = require("pg-types"); -export declare function connect(connection: string, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; -export declare function connect(config: ClientConfig, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; -export declare function end(): void; - export interface ConnectionConfig { user?: string; database?: string; password?: string; port?: number; host?: string; + connectionString?: string; } export interface Defaults extends ConnectionConfig { @@ -39,10 +36,9 @@ export interface PoolConfig extends ClientConfig { // properties from module 'node-pool' max?: number; min?: number; - refreshIdle?: boolean; + connectionTimeoutMillis?: number; idleTimeoutMillis?: number; - reapIntervalMillis?: number; - returnToHead?: boolean; + application_name?: string; Promise?: PromiseConstructorLike; } @@ -60,25 +56,35 @@ export interface QueryResult { rows: any[]; } +export interface Notification { + processId: number; + channel: string; + payload?: string; +} + export interface ResultBuilder extends QueryResult { addRow(row: any): void; } -export declare class Pool extends events.EventEmitter { +export class Pool extends events.EventEmitter { // `new Pool('pg://user@localhost/mydb')` is not allowed. // But it passes type check because of issue: // https://github.com/Microsoft/TypeScript/issues/7485 constructor(config?: PoolConfig); + readonly totalCount: number; + readonly idleCount: number; + readonly waitingCount: number; + connect(): Promise; connect(callback: (err: Error, client: Client, done: () => void) => void): void; - end(callback?: () => void): Promise; + end(): Promise; + end(callback: () => void): void; query(queryStream: QueryConfig & stream.Readable): stream.Readable; - query(queryTextOrConfig: string | QueryConfig): Promise; - query(queryText: string, values: any[]): Promise; - + query(queryConfig: QueryConfig): Promise; + query(queryText: string, values?: any[]): Promise; query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): Query; query(queryText: string, values: any[], callback: (err: Error, result: QueryResult) => void): Query; @@ -86,18 +92,20 @@ export declare class Pool extends events.EventEmitter { on(event: "connect" | "acquire", listener: (client: Client) => void): this; } -export declare class Client extends events.EventEmitter { - constructor(connection: string); +export class Client extends events.EventEmitter { constructor(config: ClientConfig); - connect(callback?: (err: Error) => void): void; - end(callback?: (err: Error) => void): void; + connect(): Promise; + connect(callback: (err: Error) => void): void; + + end(): Promise; + end(callback: (err: Error) => void): void; + release(err?: Error): void; query(queryStream: QueryConfig & stream.Readable): stream.Readable; - query(queryTextOrConfig: string | QueryConfig): Promise; - query(queryText: string, values: any[]): Promise; - + query(queryConfig: QueryConfig): Promise; + query(queryText: string, values?: any[]): Promise; query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): Query; query(queryText: string, values: any[], callback: (err: Error, result: QueryResult) => void): Query; @@ -109,20 +117,25 @@ export declare class Client extends events.EventEmitter { on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; - on(event: "notification" | "notice", listener: (message: any) => void): this; + on(event: "notification" | "notice", listener: (message: Notification) => void): this; + // tslint:disable-next-line unified-signatures on(event: "end", listener: () => void): this; } -export declare class Query extends events.EventEmitter { +export class Query extends events.EventEmitter { on(event: "row", listener: (row: any, result?: ResultBuilder) => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "end", listener: (result: ResultBuilder) => void): this; } -export declare class Events extends events.EventEmitter { +export class Events extends events.EventEmitter { on(event: "error", listener: (err: Error, client: Client) => void): this; } export const types: typeof pgTypes; export const defaults: Defaults & ClientConfig; + +import * as Pg from 'pg'; + +export const native: typeof Pg | null; diff --git a/types/pg/pg-tests.ts b/types/pg/pg-tests.ts index 4b4cfba7ec..1f1e312544 100644 --- a/types/pg/pg-tests.ts +++ b/types/pg/pg-tests.ts @@ -1,39 +1,24 @@ import * as pg from "pg"; -var conString = "postgres://username:password@localhost/database"; - // https://github.com/brianc/node-pg-types +// tslint:disable-next-line no-unnecessary-callback-wrapper pg.types.setTypeParser(20, val => Number(val)); -// Client pooling -pg.defaults.ssl = true; -pg.connect(conString, (err, client, done) => { - if (err) { - return console.error("Error fetching client from pool", err); - } - client.query("SELECT $1::int AS number", ["1"], (err, result) => { - if (err) { - done(err); - return console.error("Error running query", err); - } - else { - done(); - } - console.log(result.rows[0]["number"]); - return null; - }); - return null; +const client = new pg.Client({ + host: 'my.database-server.com', + port: 5334, + user: 'database-user', + password: 'secretpassword!!', }); - -// Simple -var client = new pg.Client(conString); client.connect(err => { if (err) { - return console.error("Could not connect to postgres", err); + console.error("Could not connect to postgres", err); + return; } client.query("SELECT NOW() AS 'theTime'", (err, result) => { if (err) { - return console.error("Error running query", err); + console.error("Error running query", err); + return; } console.log(result.rowCount); console.log(result.rows[0]["theTime"]); @@ -44,38 +29,108 @@ client.connect(err => { }); client.on('end', () => console.log("Client was disconnected.")); -// client pooling +client.connect() + .then(() => console.log('connected')) + .catch(e => console.error('connection error', e.stack)); -var config = { - user: 'foo', //env var: PGUSER - database: 'my_db', //env var: PGDATABASE - password: 'secret', //env var: PGPASSWORD - port: 5432, //env var: PGPORT - max: 10, // max number of clients in the pool - idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed - Promise, +client.query('SELECT NOW()', (err, res) => { + if (err) throw err; + console.log(res); + client.end(); +}); + +client.query('SELECT $1::text as name', ['brianc'], (err, res) => { + if (err) throw err; + console.log(res); + client.end(); +}); + +const query = { + name: 'get-name', + text: 'SELECT $1::text', + values: ['brianc'], + rowMode: 'array' }; -var pool = new pg.Pool(config); +client.query(query, (err, res) => { + if (err) { + console.error(err.stack); + } else { + console.log(res.rows); + } +}); +client.query(query) + .then(res => { + console.log(res.rows); + }) + .catch(e => { + console.error(e.stack); + }); +client.end((err) => { + console.log('client has disconnected'); + if (err) { + console.log('error during disconnection', err.stack); + } +}); + +client.end() + .then(() => console.log('client has disconnected')) + .catch(err => console.error('error during disconnection', err.stack)); + +const poolOne = new pg.Pool({ + connectionString: 'postgresql://dbuser:secretpassword@database.server.com:3211/mydb' +}); + +const pool = new pg.Pool({ + host: 'localhost', + port: 5432, + user: 'database-user', + database: 'my_db', + max: 20, + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 2000, +}); +console.log(pool.totalCount); pool.connect((err, client, done) => { - if(err) { - return console.error('error fetching client from pool', err); + if (err) { + console.error('error fetching client from pool', err); + return; } client.query('SELECT $1::int AS number', ['1'], (err, result) => { done(); - if(err) { - return console.error('error running query', err); + if (err) { + console.error('error running query', err); + return; } console.log(result.rows[0].number); }); }); pool.on('error', (err, client) => { - console.error('idle client error', err.message, err.stack) -}) - -pool.end(); -pool.end(() => { - console.log("pool is closed"); + console.error('idle client error', err.message, err.stack); }); + +pool.query('SELECT $1::text as name', ['brianc'], (err, result) => { + if (err) { + console.error('Error executing query', err.stack); + return; + } + console.log(result.rows[0].name); +}); + +pool.query('SELECT $1::text as name', ['brianc']) + .then((res) => console.log(res.rows[0].name)) + .catch(err => console.error('Error executing query', err.stack)); + +pool.end(() => { + console.log('pool has ended'); +}); + +pool.end().then(() => console.log('pool has ended')); + +(async () => { + const client = await pool.connect(); + await client.query('SELECT NOW()'); + client.release(); +})(); diff --git a/types/pg/tsconfig.json b/types/pg/tsconfig.json index 3535f4d43f..caa997a916 100644 --- a/types/pg/tsconfig.json +++ b/types/pg/tsconfig.json @@ -4,9 +4,10 @@ "lib": [ "es6" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +20,4 @@ "index.d.ts", "pg-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/pg/tslint.json b/types/pg/tslint.json new file mode 100644 index 0000000000..495d29983d --- /dev/null +++ b/types/pg/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} diff --git a/types/pg/v6/index.d.ts b/types/pg/v6/index.d.ts new file mode 100644 index 0000000000..5624989ac7 --- /dev/null +++ b/types/pg/v6/index.d.ts @@ -0,0 +1,128 @@ +// Type definitions for pg 6.1 +// Project: https://github.com/brianc/node-postgres +// Definitions by: Phips Peter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import events = require("events"); +import stream = require("stream"); +import pgTypes = require("pg-types"); + +export declare function connect(connection: string, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; +export declare function connect(config: ClientConfig, callback: (err: Error, client: Client, done: (err?: any) => void) => void): void; +export declare function end(): void; + +export interface ConnectionConfig { + user?: string; + database?: string; + password?: string; + port?: number; + host?: string; +} + +export interface Defaults extends ConnectionConfig { + poolSize?: number; + poolIdleTimeout?: number; + reapIntervalMillis?: number; + binary?: boolean; + parseInt8?: boolean; +} + +import { TlsOptions } from "tls"; + +export interface ClientConfig extends ConnectionConfig { + ssl?: boolean | TlsOptions; +} + +export interface PoolConfig extends ClientConfig { + // properties from module 'node-pool' + max?: number; + min?: number; + refreshIdle?: boolean; + idleTimeoutMillis?: number; + reapIntervalMillis?: number; + returnToHead?: boolean; + application_name?: string; + Promise?: PromiseConstructorLike; +} + +export interface QueryConfig { + name?: string; + text: string; + values?: any[]; +} + +export interface QueryResult { + command: string; + rowCount: number; + oid: number; + rows: any[]; +} + +export interface ResultBuilder extends QueryResult { + addRow(row: any): void; +} + +export declare class Pool extends events.EventEmitter { + // `new Pool('pg://user@localhost/mydb')` is not allowed. + // But it passes type check because of issue: + // https://github.com/Microsoft/TypeScript/issues/7485 + constructor(config?: PoolConfig); + + connect(): Promise; + connect(callback: (err: Error, client: Client, done: () => void) => void): void; + + end(callback?: () => void): Promise; + + query(queryStream: QueryConfig & stream.Readable): stream.Readable; + query(queryTextOrConfig: string | QueryConfig): Promise; + query(queryText: string, values: any[]): Promise; + + query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): Query; + query(queryText: string, values: any[], callback: (err: Error, result: QueryResult) => void): Query; + + on(event: "error", listener: (err: Error, client: Client) => void): this; + on(event: "connect" | "acquire", listener: (client: Client) => void): this; +} + +export declare class Client extends events.EventEmitter { + constructor(connection: string); + constructor(config: ClientConfig); + + connect(callback?: (err: Error) => void): void; + end(callback?: (err: Error) => void): void; + release(err?: Error): void; + + query(queryStream: QueryConfig & stream.Readable): stream.Readable; + query(queryTextOrConfig: string | QueryConfig): Promise; + query(queryText: string, values: any[]): Promise; + + query(queryTextOrConfig: string | QueryConfig, callback: (err: Error, result: QueryResult) => void): Query; + query(queryText: string, values: any[], callback: (err: Error, result: QueryResult) => void): Query; + + copyFrom(queryText: string): stream.Writable; + copyTo(queryText: string): stream.Readable; + + pauseDrain(): void; + resumeDrain(): void; + + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "notification" | "notice", listener: (message: any) => void): this; + on(event: "end", listener: () => void): this; +} + +export declare class Query extends events.EventEmitter { + on(event: "row", listener: (row: any, result?: ResultBuilder) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "end", listener: (result: ResultBuilder) => void): this; +} + +export declare class Events extends events.EventEmitter { + on(event: "error", listener: (err: Error, client: Client) => void): this; +} + +export const types: typeof pgTypes; + +export const defaults: Defaults & ClientConfig; diff --git a/types/pg/v6/pg-tests.ts b/types/pg/v6/pg-tests.ts new file mode 100644 index 0000000000..4b4cfba7ec --- /dev/null +++ b/types/pg/v6/pg-tests.ts @@ -0,0 +1,81 @@ +import * as pg from "pg"; + +var conString = "postgres://username:password@localhost/database"; + +// https://github.com/brianc/node-pg-types +pg.types.setTypeParser(20, val => Number(val)); + +// Client pooling +pg.defaults.ssl = true; +pg.connect(conString, (err, client, done) => { + if (err) { + return console.error("Error fetching client from pool", err); + } + client.query("SELECT $1::int AS number", ["1"], (err, result) => { + if (err) { + done(err); + return console.error("Error running query", err); + } + else { + done(); + } + console.log(result.rows[0]["number"]); + return null; + }); + return null; +}); + +// Simple +var client = new pg.Client(conString); +client.connect(err => { + if (err) { + return console.error("Could not connect to postgres", err); + } + client.query("SELECT NOW() AS 'theTime'", (err, result) => { + if (err) { + return console.error("Error running query", err); + } + console.log(result.rowCount); + console.log(result.rows[0]["theTime"]); + client.end(); + return null; + }); + return null; +}); +client.on('end', () => console.log("Client was disconnected.")); + +// client pooling + +var config = { + user: 'foo', //env var: PGUSER + database: 'my_db', //env var: PGDATABASE + password: 'secret', //env var: PGPASSWORD + port: 5432, //env var: PGPORT + max: 10, // max number of clients in the pool + idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed + Promise, +}; +var pool = new pg.Pool(config); + +pool.connect((err, client, done) => { + if(err) { + return console.error('error fetching client from pool', err); + } + client.query('SELECT $1::int AS number', ['1'], (err, result) => { + done(); + + if(err) { + return console.error('error running query', err); + } + console.log(result.rows[0].number); + }); +}); + +pool.on('error', (err, client) => { + console.error('idle client error', err.message, err.stack) +}) + +pool.end(); +pool.end(() => { + console.log("pool is closed"); +}); diff --git a/types/pg/v6/tsconfig.json b/types/pg/v6/tsconfig.json new file mode 100644 index 0000000000..2c44f5862b --- /dev/null +++ b/types/pg/v6/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "pg": [ "pg/v6" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pg-tests.ts" + ] +} diff --git a/types/pixi.js/tslint.json b/types/pixi.js/tslint.json index 1b39c5314f..fb2df83ec9 100644 --- a/types/pixi.js/tslint.json +++ b/types/pixi.js/tslint.json @@ -5,10 +5,12 @@ "ban-types": false, "dt-header": false, "interface-name": false, + "no-any-union": false, "no-empty-interface": false, "no-inferrable-types": false, "no-mergeable-namespace": false, "no-single-declare-module": false, + "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "one-line": false, "prefer-conditional-expression": false, diff --git a/types/postmark/tslint.json b/types/postmark/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/postmark/tslint.json +++ b/types/postmark/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-fruitdown/tslint.json b/types/pouchdb-adapter-fruitdown/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-fruitdown/tslint.json +++ b/types/pouchdb-adapter-fruitdown/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-http/tslint.json b/types/pouchdb-adapter-http/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-http/tslint.json +++ b/types/pouchdb-adapter-http/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-idb/tslint.json b/types/pouchdb-adapter-idb/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-idb/tslint.json +++ b/types/pouchdb-adapter-idb/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-leveldb/tslint.json b/types/pouchdb-adapter-leveldb/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-leveldb/tslint.json +++ b/types/pouchdb-adapter-leveldb/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-localstorage/tslint.json b/types/pouchdb-adapter-localstorage/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-localstorage/tslint.json +++ b/types/pouchdb-adapter-localstorage/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-memory/tslint.json b/types/pouchdb-adapter-memory/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-memory/tslint.json +++ b/types/pouchdb-adapter-memory/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-adapter-websql/tslint.json b/types/pouchdb-adapter-websql/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-adapter-websql/tslint.json +++ b/types/pouchdb-adapter-websql/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-core/tslint.json b/types/pouchdb-core/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-core/tslint.json +++ b/types/pouchdb-core/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/pouchdb-find/tslint.json b/types/pouchdb-find/tslint.json index 3db14f85ea..d9d49e375e 100644 --- a/types/pouchdb-find/tslint.json +++ b/types/pouchdb-find/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-any-union": false + } +} diff --git a/types/pouchdb-mapreduce/tslint.json b/types/pouchdb-mapreduce/tslint.json index 3db14f85ea..c92fd86792 100644 --- a/types/pouchdb-mapreduce/tslint.json +++ b/types/pouchdb-mapreduce/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "no-any-union": false + } +} diff --git a/types/pouchdb-upsert/tslint.json b/types/pouchdb-upsert/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/pouchdb-upsert/tslint.json +++ b/types/pouchdb-upsert/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 48c89a5c57..317a514912 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -115,6 +115,9 @@ export interface ResolveConfigOptions { * The promise will be rejected if there was an error parsing the configuration file. */ export function resolveConfig(filePath?: string, options?: ResolveConfigOptions): Promise; +export namespace resolveConfig { + function sync(filePath?: string, options?: ResolveConfigOptions): null | Options; +} /** * As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache. diff --git a/types/prettier/prettier-tests.ts b/types/prettier/prettier-tests.ts index a51e8902c4..8d95196101 100644 --- a/types/prettier/prettier-tests.ts +++ b/types/prettier/prettier-tests.ts @@ -24,4 +24,9 @@ prettier.resolveConfig('path/to/somewhere').then(options => { } }); +const options = prettier.resolveConfig.sync('path/to/somewhere'); +if (options !== null) { + const formatted = prettier.format('hello world', options); +} + prettier.clearConfigCache(); diff --git a/types/prosemirror-collab/tslint.json b/types/prosemirror-collab/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/prosemirror-collab/tslint.json +++ b/types/prosemirror-collab/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/prosemirror-history/tslint.json b/types/prosemirror-history/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/prosemirror-history/tslint.json +++ b/types/prosemirror-history/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/prosemirror-keymap/tslint.json b/types/prosemirror-keymap/tslint.json index f93cf8562a..71ee04c4e1 100644 --- a/types/prosemirror-keymap/tslint.json +++ b/types/prosemirror-keymap/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/prosemirror-model/tslint.json b/types/prosemirror-model/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/prosemirror-model/tslint.json +++ b/types/prosemirror-model/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/prosemirror-state/tslint.json b/types/prosemirror-state/tslint.json index 9e23990c45..0aca9484b9 100644 --- a/types/prosemirror-state/tslint.json +++ b/types/prosemirror-state/tslint.json @@ -2,6 +2,8 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-object-literal-type-assertion": false + "no-object-literal-type-assertion": false, + "no-any-union": false, + "no-unnecessary-generics": false } } diff --git a/types/python-shell/tslint.json b/types/python-shell/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/python-shell/tslint.json +++ b/types/python-shell/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/q/tslint.json b/types/q/tslint.json index f88914f166..0bded8e292 100644 --- a/types/q/tslint.json +++ b/types/q/tslint.json @@ -2,6 +2,8 @@ "extends": "dtslint/dt.json", "rules": { // TODOs + "no-any-union": false, + "no-unnecessary-generics": false, "no-unnecessary-type-assertion": false, "prefer-declare-function": false, "strict-export-declare-modifiers": false, diff --git a/types/qlik-visualizationextensions/tslint.json b/types/qlik-visualizationextensions/tslint.json index 9a48ae7955..c1a4e40cca 100644 --- a/types/qlik-visualizationextensions/tslint.json +++ b/types/qlik-visualizationextensions/tslint.json @@ -2,7 +2,9 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, + "no-any-union": false, "no-empty-interface": false, + "no-unnecessary-generics": false, "interface-name": false } } diff --git a/types/quill/tslint.json b/types/quill/tslint.json index d88586e5bd..b1439230db 100644 --- a/types/quill/tslint.json +++ b/types/quill/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } } diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index f437464da3..4d37cccf10 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1917,7 +1917,7 @@ declare namespace R { * Note that the order of the output array is not guaranteed across * different JS platforms. */ - values(obj: { [index: string]: T } | any): T[]; + values(obj: T): Array; /** * Returns a list of all the properties, including prototype properties, of the supplied diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 38806fb3b4..eae917d93e 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1567,7 +1567,19 @@ class Rectangle { }; () => { - const a = R.values({a: 1, b: 2, c: 3}); // => [1, 2, 3] + interface A { + a: string; + b: string; + } + const a1: A = { a: 'something', b: 'else' }; + const v1 = R.values(a1); + + const a = R.values({a: 1, b: 2, c: 3}); // => [1, 2, 3] (number[]) + const addition = a[0] + a[1]; + + const b = R.values({a: 1, b: 'something'}); // b = (string|number)[] + const c = R.values({1: 3}); + // const d = R.values('something'); }; () => { diff --git a/types/raven/tslint.json b/types/raven/tslint.json index adaee1b55f..466bd50dd0 100644 --- a/types/raven/tslint.json +++ b/types/raven/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "export-just-namespace": false + // TODOs + "export-just-namespace": false, + "no-any-union": false } } diff --git a/types/rc-slider/tslint.json b/types/rc-slider/tslint.json index d88586e5bd..b1439230db 100644 --- a/types/rc-slider/tslint.json +++ b/types/rc-slider/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } } diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index c24f0018fd..20f65e3059 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -5,9 +5,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// +import * as React from 'react'; -declare namespace Tooltip { +export as namespace RCTooltip; + +declare namespace RCTooltip { export type Trigger = "hover" | "click" | "focus"; export type Placement = "left" | "right" | "top" | "bottom" | @@ -34,8 +36,4 @@ declare namespace Tooltip { } } -declare class Tooltip extends React.Component {} - -declare module "rc-tooltip" { - export = Tooltip -} +export default class Tooltip extends React.Component {} diff --git a/types/rc-tooltip/rc-tooltip-tests.tsx b/types/rc-tooltip/rc-tooltip-tests.tsx index 832a292e97..06b230a55b 100644 --- a/types/rc-tooltip/rc-tooltip-tests.tsx +++ b/types/rc-tooltip/rc-tooltip-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import * as Tooltip from 'rc-tooltip'; +import Tooltip, {RCTooltip} from 'rc-tooltip'; ReactDOM.render( tooltip}> @@ -50,3 +50,9 @@ ReactDOM.render( , document.querySelector('.another-app') ); + +const props: RCTooltip.Props = { + placement: "bottomRight", + trigger: ['click', 'focus'], + overlay: () => tooltip, +}; diff --git a/types/react-bootstrap-table/index.d.ts b/types/react-bootstrap-table/index.d.ts index 1b80e670fa..a31d860775 100644 --- a/types/react-bootstrap-table/index.d.ts +++ b/types/react-bootstrap-table/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-bootstrap-table v2.6.0 // Project: https://github.com/AllenFang/react-bootstrap-table -// Definitions by: Frank Laub , Aleksander Lode +// Definitions by: Frank Laub , Aleksander Lode , Josué Us // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -12,48 +12,115 @@ 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 + * + * @interface RemoteObjSpec + */ +export interface RemoteObjSpec { + /** + * If set, cell edits will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + cellEdit?: boolean; + /** + * If set insertions will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + insertRow?: boolean; + /** + * If set deletion will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + dropRow?: boolean; + /** + * If set filters will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + filter?: boolean; + /** + * If set search will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + search?: boolean; + /** + * If set, exporting CSV will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + exportCSV?: boolean; + /** + * If set sorting will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + sort?: boolean; + /** + * If set pagination will be handled remotely + * + * @type {boolean} + * @memberof RemoteObjSpec + */ + pagination?: boolean; +} + export interface BootstrapTableProps extends Props { /** Use data to specify the data that you want to display on table. */ - data: any[]; + data: any[]; /** If set, data is remote (use also fetchInfo) */ - remote?: boolean, + 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; + keyField?: string; /** Use height to set the height of table, default is 100%. */ - height?: string; + height?: string; /** Set the max column width (pixels) */ - maxHeight?: string; + maxHeight?: string; /** Enable striped by setting striped to true. Same as Bootstrap table class .table-striped, default is false. */ - striped?: boolean; + striped?: boolean; /** Enable hover by setting hover to true. Same as Bootstrap table class .table-hover, default is false. */ - hover?: boolean; + hover?: boolean; /** Enable condensed by setting condensed to true. Same as Bootstrap table class .table-condensed, default is false. */ - condensed?: boolean; + condensed?: boolean; /** Become a borderless table by setting bordered to false, default is true. */ - bordered?: boolean; + bordered?: boolean; /** Enable pagination by setting pagination to true, default is false. */ - pagination?: boolean; + 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. @@ -63,65 +130,65 @@ export interface BootstrapTableProps extends Props { return rowIndex%2==0?"tr-odd":"tr-even"; //return a class name. } */ - trClassName?: string | ((rowData: any, rowIndex: number) => string); + 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; + 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; + 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; + 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; + search?: boolean; /** Set searchPlaceholder to change the placeholder in search field, default is Search. */ - searchPlaceholder?: string; + searchPlaceholder?: string; /** 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; + 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; + exportCSV?: boolean; /** Set CSV filename (e.g. items.csv). Default is spreadsheet.csv */ - csvFileName?: string; + csvFileName?: string; /** Enable row selection on table. selectRow accept an object which have the following properties */ - selectRow?: SelectRow; + selectRow?: SelectRow; /** Enable cell editing on table. cellEdit accept an object which have the following properties */ - cellEdit?: CellEdit; + 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; + options?: Options; + fetchInfo?: FetchInfo; printable?: boolean; - tableStyle?: any; - containerStyle?: any; - headerStyle?: any; - bodyStyle?: any; - ignoreSinglePage?: boolean; + tableStyle?: any; + containerStyle?: any; + headerStyle?: any; + bodyStyle?: any; + ignoreSinglePage?: boolean; containerClass?: string; tableContainerClass?: string headerContainerClass?: string; @@ -136,37 +203,37 @@ export interface SelectRow { /** For specifing the selection is single(radio) or multiple(checkbox). */ - mode: SelectRowMode; + mode: SelectRowMode; /** Click the row will trigger selection on that row if enable clickToSelect, default is false. */ - clickToSelect?: boolean; + 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; + clickToSelectAndEditCell?: boolean; /** You can assign the background color of row which be selected. */ - bgColor?: string; + bgColor?: string; /** You can assign the class name of row which be selected. */ - className?: string; + 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[]; + 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; + hideSelectColumn?: boolean; /** Default is false, if enabled, there will be a button on top of table for toggling selected rows only. */ - showOnlySelected?: boolean; + 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: @@ -175,7 +242,7 @@ export interface SelectRow { `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; + 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: @@ -183,7 +250,7 @@ export interface SelectRow { `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; + onSelectAll?: (isSelected: boolean, currentSelectedAndDisplayData: any) => boolean; /** * Provide a list of unselectable row keys. @@ -197,23 +264,23 @@ export interface CellEdit { /** To spectify which condition will trigger cell editing.(click or dbclick) */ - mode: CellEditClickMode; + 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; + 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; + 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; + afterSaveCell?: (row: any, cellName: string, cellValue: any) => void; } export type SortOrder = 'asc' | 'desc'; @@ -222,137 +289,137 @@ export interface Options { /** Manage sort field by yourself */ - sortName?: string; + sortName?: string; /** Manage sort order by yourself */ - sortOrder?: SortOrder; + sortOrder?: SortOrder; /** Assign a default sort field. */ - defaultSortName?: string; + defaultSortName?: string; /** Assign a default sort ordering. */ - defaultSortOrder?: SortOrder; + defaultSortOrder?: SortOrder; /** False to disable sort indicator on header column, default is true. */ - sortIndicator?: boolean; + sortIndicator?: boolean; /** Change the displaying text on table if data is empty. */ - noDataText?: string | ReactElement; + noDataText?: string | ReactElement; /** A delay for trigger search after a keyup (millisecond) */ - searchDelayTime?: number; + searchDelayTime?: number; /** A custom text on export csv button */ - exportCSVText?: string; + exportCSVText?: string; /** Default is false, if true means you want to ignore any editable configuration when row insert. */ - ignoreEditable?: boolean; + 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; + clearSearch?: boolean; /** Assign a callback function which will be called after table update. */ - afterTableComplete?: Function; + 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; + 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; + afterInsertRow?: (row: any) => void; /** Customize the text of previouse page button */ - prePage?: string; + prePage?: string; /** Customize the text of next page button */ - nextPage?: string; + nextPage?: string; /** Customize the text of first page button */ - firstPage?: string; + firstPage?: string; /** Customize the text of last page button */ - lastPage?: string; + lastPage?: string; /** Accept a number, which means the page you want to show as default. */ - page?: number; + page?: number; /** You can change the dropdown list for size per page if you enable pagination. */ - sizePerPageList?: number[]; + sizePerPageList?: number[]; /** Means the size per page you want to locate as default. */ - sizePerPage?: number; + sizePerPage?: number; /** To define the pagination bar length, default is 5. */ - paginationSize?: number; + paginationSize?: number; /** To define where to start counting the pages. */ - pageStartIndex?: number; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + onRowDoubleClick?: (row: any) => void; /** Background color on expanded rows. */ @@ -360,21 +427,21 @@ export interface Options { /** Assign a callback function which will be called when mouse enter into the table. */ - onMouseEnter?: Function; + onMouseEnter?: Function; /** Assign a callback function which will be called when mouse leave from the table. */ - onMouseLeave?: Function; + 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; + 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; + onRowMouseOut?: Function; /** Assign a callback function which will be called when row dropping. @@ -385,60 +452,93 @@ export interface Options { `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 | ReactElement; - onSearchChange?: Function; - onAddRow?: Function; - onExportToCSV?: Function; + handleConfirmDeleteRow?: (next: Function, rowKeys: any[]) => void; + paginationShowsTotal?: boolean | ReactElement; + onSearchChange?: Function; + onAddRow?: Function; + onExportToCSV?: Function; - insertText?: string; - deleteText?: string; - saveText?: string; - closeText?: string; + 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 + * + * @memberof BootstrapTableProps + */ + 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 + * + * @memberof BootstrapTableProps + */ + 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 + * + * @memberof BootstrapTableProps + */ + onDeleteRow?: (rows: any[] | 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 + * + * @memberof BootstrapTableProps + */ + onpageChange?: (page: any, sizePerPage: number) => any; } interface FetchInfo { - dataTotalSize?: number; + dataTotalSize?: number; } export interface BootstrapTable extends ComponentClass { /** * Call this function to insert an new row to table. */ - handleAddRow(row: any): void; + handleAddRow(row: any): void; /** * Call this function to insert an new row as first row on table. */ - handleAddRowAtBegin(row: any): void; + handleAddRowAtBegin(row: any): void; /** * Call this function to drop rows in table. */ - handleDropRow(rowKeys: any[]): void; + handleDropRow(rowKeys: any[]): void; /** * Call this function to do column filtering on table. */ - handleFilterData(filter: any): void; + handleFilterData(filter: any): void; /** * Call this function with search text for fully searching. */ - handleSearch(search: string): void; + handleSearch(search: string): void; /** * Call this function to sort table. */ - handleSort(order: SortOrder, field: string): void; + handleSort(order: SortOrder, field: string): void; /** * Call this function to get the page by a rowkey */ - getPageByRowKey(rowKey: string): any; + getPageByRowKey(rowKey: string): any; /** * Call this function to export table as csv. */ - handleExportCSV(): void; + handleExportCSV(): void; /** * Clean all the selection state on table. */ - cleanSelected(): void; + cleanSelected(): void; } interface BootstrapTable extends ComponentClass { } declare const BootstrapTable: BootstrapTable; @@ -448,20 +548,20 @@ export interface TableHeaderColumnProps extends Props { /** The field of data you want to show on column. */ - dataField?: string; + 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; + isKey?: boolean; /** Set the column width. ex: 150, it's means 150px */ - width?: string; + width?: string; /** Set align in column, value is left, center, right, start and end. */ - dataAlign?: DataAlignType; + dataAlign?: DataAlignType; /** * Alignment of text in the column header. @@ -470,7 +570,7 @@ export interface TableHeaderColumnProps extends Props { /** True to enable table sorting. Default is disabled. */ - dataSort?: boolean; + dataSort?: boolean; /** Default search string. */ @@ -479,27 +579,27 @@ export interface TableHeaderColumnProps extends Props { 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} ; + 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; + dataFormat?: (cell: any, row: any, formatExtraData?: any) => string | ReactElement; /** To to enable search or filter data on formatting. Default is false */ - filterFormatted?: boolean; + filterFormatted?: boolean; /** True to hide column. */ - hidden?: boolean; + hidden?: boolean; /** True to hide the dropdown for sizePerPage. */ @@ -507,28 +607,28 @@ export interface TableHeaderColumnProps extends Props { /** False to disable search functionality on column, default is true. */ - searchable?: boolean; + 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; + 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; + 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); + 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); + 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: @@ -541,29 +641,29 @@ export interface TableHeaderColumnProps extends Props { } } */ - editable?: boolean | Editable; + 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; + 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; + filter?: Filter; - onSort?: Function; + onSort?: Function; /** * Header for column in generated CSV file */ csvHeader?: string; - csvFormat?: Function; - columnTitle?: boolean; - sort?: SortOrder; - formatExtraData?: any; + csvFormat?: Function; + columnTitle?: boolean; + sort?: SortOrder; + formatExtraData?: any; /** * Row in the header on which this header column present. @@ -581,26 +681,32 @@ export interface TableHeaderColumnProps extends Props { * 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; } export interface Editable { - type?: string;//edit type, avaiable value is textarea, select, checkbox + 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; + validator?: (cell: any) => boolean; /** { values: //values means data in select or checkbox.If checkbox, use ':'(colon) to separate value, ex: Y:N } */ - options?: any; + options?: any; /** Configuration for the textarea editable type */ - cols?: number; - rows?: number; + cols?: number; + rows?: number; } export type SetFilterCallback = (targetValue: any) => boolean; export interface ApplyFilterParameter { @@ -612,51 +718,51 @@ export interface Filter { /** "TextFilter"||"SelectFilter"||"NumberFilter"||"DateFilter"||"RegexFilter"||"YOUR_CUSTOM_FILTER" */ - type?: FilterType; + type?: FilterType; /** * Default value on filter. If type is NumberFilter or DateFilter, this value will like { number||date: xxx, comparator: '>' } */ - defaultValue?: any; + defaultValue?: any; /** * Assign a millisecond for delay when trigger filtering, default is 500. */ - delay?: number; + delay?: number; /** * Only work on TextFilter. Assign the placeholder text on text and regex filter */ - placeholder?: string | RegExp; + placeholder?: string | RegExp; /** * Only work on NumberFilter. Accept an array which conatin the filter condition, like: ['<','>','='] */ - numberComparators?: string[]; + numberComparators?: string[]; /** * Options for the filter. */ - options?: any; + options?: any; /** * Comparison condition for the NumberFilter */ - condition?: string; + condition?: string; /** * Get element which represent filter. */ - getElement?: (filterHandler: (parameters?: ApplyFilterParameter) => void, filterParameters: any) => JSX.Element; + getElement?: (filterHandler: (parameters?: ApplyFilterParameter) => void, filterParameters: any) => JSX.Element; /** * Parameters for custom filter */ - customFilterParameters?: any; + 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; + constructor(data: any); + setData(data: any): void; + clear(): void; + getData(): any; } diff --git a/types/react-bootstrap-table/react-bootstrap-table-tests.tsx b/types/react-bootstrap-table/react-bootstrap-table-tests.tsx index e501d8de14..76e5bb79b7 100644 --- a/types/react-bootstrap-table/react-bootstrap-table-tests.tsx +++ b/types/react-bootstrap-table/react-bootstrap-table-tests.tsx @@ -21,10 +21,10 @@ function priceFormatter(cell: any, row: any) { render( - Product ID - Product Name - Product Price - , + Product ID + Product Name + Product Price + , document.getElementById("app") ); @@ -41,11 +41,11 @@ function enumFormatter(cell: any, row: any, enumObject: any) { class SelectFilterWithDefaultValue extends React.Component { render() { return ( - - Product ID - Product Name - Product Quality + + Product ID + Product Name + Product Quality ); } @@ -54,9 +54,9 @@ class SelectFilterWithDefaultValue extends React.Component { class TextFilterWithCondition extends React.Component { render() { return ( - + Product ID - Product Name + Product Name Product Price ); @@ -72,15 +72,35 @@ function getCustomFilter(filterHandler: (parameters?: ApplyFilterParameter) => v class CustomFilter extends React.Component { render() { return ( - + Product ID Product Name - Product Is In Stock + Product Is In Stock ); } } +class RemoteProps extends React.Component { + render() { + 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 + + ); + } +} // 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() { @@ -94,15 +114,15 @@ export default class ColumnHeaderSpanComplex extends React.Component { blurToSave: true }; return ( - - ID + ID Product name price Coupon In stock - Customer + Customer name order diff --git a/types/react-bootstrap/lib/ToggleButton.d.ts b/types/react-bootstrap/lib/ToggleButton.d.ts new file mode 100644 index 0000000000..ef231bf288 --- /dev/null +++ b/types/react-bootstrap/lib/ToggleButton.d.ts @@ -0,0 +1,11 @@ +import * as React from 'react'; + +declare namespace ToggleButton { + export interface ToggleButtonProps extends React.HTMLProps { + checked?: boolean; + name?: string; + value: number|string; + } +} +declare class ToggleButton extends React.Component { } +export = ToggleButton; diff --git a/types/react-bootstrap/lib/ToggleButtonGroup.d.ts b/types/react-bootstrap/lib/ToggleButtonGroup.d.ts new file mode 100644 index 0000000000..bca9544d70 --- /dev/null +++ b/types/react-bootstrap/lib/ToggleButtonGroup.d.ts @@ -0,0 +1,35 @@ +import * as React from 'react'; +import { Omit } from "../index"; + +declare namespace ToggleButtonGroup { + interface BaseProps { + /** + * You'll usually want to use string|number|string[]|number[] here, + * but you can technically use any|any[]. + */ + defaultValue?: any; + /** + * You'll usually want to use string|number|string[]|number[] here, + * but you can technically use any|any[]. + */ + value?: any; + } + + interface RadioProps { + /** Required if `type` is set to "radio" */ + name: string; + type: "radio"; + } + + interface CheckboxProps { + name?: string; + type: "checkbox"; + } + + export type ToggleButtonGroupProps = BaseProps + & (RadioProps | CheckboxProps) + & Omit, "defaultValue" | "type" | "value">; + +} +declare class ToggleButtonGroup extends React.Component { } +export = ToggleButtonGroup; diff --git a/types/react-bootstrap/lib/index.d.ts b/types/react-bootstrap/lib/index.d.ts index ed2ba6bccf..85fc3eed70 100644 --- a/types/react-bootstrap/lib/index.d.ts +++ b/types/react-bootstrap/lib/index.d.ts @@ -166,10 +166,15 @@ import Tabs = require('./Tabs'); import { TabsProps } from './Tabs'; import Thumbnail = require('./Thumbnail'); import { ThumbnailProps } from './Thumbnail'; +import ToggleButton = require('./ToggleButton'); +import { ToggleButtonProps } from './ToggleButton'; +import ToggleButtonGroup = require('./ToggleButtonGroup'); +import { ToggleButtonGroupProps } from './ToggleButtonGroup'; import Tooltip = require('./Tooltip'); import { TooltipProps } from './Tooltip'; import Well = require('./Well'); import { WellProps } from './Well'; + import * as utils from './utils'; export { @@ -341,6 +346,10 @@ export { TabsProps, Thumbnail, ThumbnailProps, + ToggleButton, + ToggleButtonProps, + ToggleButtonGroup, + ToggleButtonGroupProps, Tooltip, TooltipProps, Well, diff --git a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx index 00f3920224..78579dc953 100644 --- a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx +++ b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx @@ -83,6 +83,8 @@ import * as TabPane from 'react-bootstrap/lib/TabPane'; import * as Table from 'react-bootstrap/lib/Table'; import * as Tabs from 'react-bootstrap/lib/Tabs'; import * as Thumbnail from 'react-bootstrap/lib/Thumbnail'; +import * as ToggleButton from 'react-bootstrap/lib/ToggleButton'; +import * as ToggleButtonGroup from 'react-bootstrap/lib/ToggleButtonGroup'; import * as Tooltip from 'react-bootstrap/lib/Tooltip'; import * as Well from 'react-bootstrap/lib/Well'; @@ -185,6 +187,9 @@ export class ReactBootstrapIndividualComponentsTest extends React.Component { + + + diff --git a/types/react-bootstrap/test/react-bootstrap-tests.tsx b/types/react-bootstrap/test/react-bootstrap-tests.tsx index 873132e64b..445e65dc12 100644 --- a/types/react-bootstrap/test/react-bootstrap-tests.tsx +++ b/types/react-bootstrap/test/react-bootstrap-tests.tsx @@ -12,7 +12,8 @@ import { Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Form, FormGroup, ControlLabel, FormControl, HelpBlock, - Radio, Checkbox, Media, InputGroup + Radio, Checkbox, Media, InputGroup, ToggleButtonGroup, + ToggleButton } from 'react-bootstrap'; export class ReactBootstrapTest extends Component { @@ -1270,6 +1271,26 @@ export class ReactBootstrapTest extends Component { + +
+ + + Checkbox 1 (pre-checked) + Checkbox 2 + Checkbox 3 (pre-checked) + + + + + + + Radio 1 (pre-checked) + + Radio 2 + Radio 3 + + +
); } diff --git a/types/react-chartjs-2/test/mix.tsx b/types/react-chartjs-2/test/mix.tsx index 208023b62d..614e61723e 100755 --- a/types/react-chartjs-2/test/mix.tsx +++ b/types/react-chartjs-2/test/mix.tsx @@ -1,7 +1,8 @@ import * as React from 'react'; import { Bar } from 'react-chartjs-2'; +import { ChartData, ChartOptions } from 'chart.js'; -const data = { +const data: ChartData = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [{ label: 'Sales', @@ -22,13 +23,11 @@ const data = { fill: false, backgroundColor: '#71B37C', borderColor: '#71B37C', - hoverBackgroundColor: '#71B37C', - hoverBorderColor: '#71B37C', yAxisID: 'y-axis-1' }] }; -const options = { +const options: ChartOptions = { responsive: true, tooltips: { mode: 'label' @@ -44,9 +43,6 @@ const options = { display: true, gridLines: { display: false - }, - labels: { - show: true } } ], @@ -58,9 +54,6 @@ const options = { id: 'y-axis-1', gridLines: { display: false - }, - labels: { - show: true } }, { @@ -70,9 +63,6 @@ const options = { id: 'y-axis-2', gridLines: { display: false - }, - labels: { - show: true } } ] diff --git a/types/react-faux-dom/tslint.json b/types/react-faux-dom/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/react-faux-dom/tslint.json +++ b/types/react-faux-dom/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/react-ga/tslint.json b/types/react-ga/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/react-ga/tslint.json +++ b/types/react-ga/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/react-loadable/tslint.json b/types/react-loadable/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/react-loadable/tslint.json +++ b/types/react-loadable/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/react-measure/tslint.json b/types/react-measure/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/react-measure/tslint.json +++ b/types/react-measure/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/react-native-collapsible/tslint.json b/types/react-native-collapsible/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/react-native-collapsible/tslint.json +++ b/types/react-native-collapsible/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/react-native-fetch-blob/tslint.json b/types/react-native-fetch-blob/tslint.json index 3db14f85ea..b1439230db 100644 --- a/types/react-native-fetch-blob/tslint.json +++ b/types/react-native-fetch-blob/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-any-union": false + } +} diff --git a/types/react-native-google-analytics-bridge/tslint.json b/types/react-native-google-analytics-bridge/tslint.json index d88586e5bd..71ee04c4e1 100644 --- a/types/react-native-google-analytics-bridge/tslint.json +++ b/types/react-native-google-analytics-bridge/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/react-native-material-kit/index.d.ts b/types/react-native-material-kit/index.d.ts index 5556bd4282..d9564be179 100644 --- a/types/react-native-material-kit/index.d.ts +++ b/types/react-native-material-kit/index.d.ts @@ -305,6 +305,11 @@ export interface MKProgressProperties extends ViewProperties { bufferAniDuration?: number; } +export interface IndeterminateProgressProperties extends ViewProperties { + progressColor?: string; + progressAniDuration?: number; +} + export interface BaseSlider extends ViewProperties { min?: number; max?: number; @@ -382,6 +387,10 @@ export class MKRipple extends React.Component {} export class MKProgress extends React.Component {} +export namespace MKProgress { + class Indeterminate extends React.Component {} +} + export class MKSlider extends React.Component {} export class MKRangeSlider extends diff --git a/types/react-native-material-kit/react-native-material-kit-tests.tsx b/types/react-native-material-kit/react-native-material-kit-tests.tsx index 3a3efa11c0..4cb415d791 100644 --- a/types/react-native-material-kit/react-native-material-kit-tests.tsx +++ b/types/react-native-material-kit/react-native-material-kit-tests.tsx @@ -78,6 +78,7 @@ const MKIconToggleTest = () => //// PROGRESS const MKProgressTest = () => ; +const MKIndeterminateProgressTest = () => ; //// SLIDER interface MKSliderTestState { diff --git a/types/react-native-vector-icons/Icon.d.ts b/types/react-native-vector-icons/Icon.d.ts index bb56a01794..07fd38f91b 100644 --- a/types/react-native-vector-icons/Icon.d.ts +++ b/types/react-native-vector-icons/Icon.d.ts @@ -197,6 +197,7 @@ export class Icon extends React.Component { export namespace Icon { class ToolbarAndroid extends React.Component {} + class TabBarItem extends React.Component {} class TabBarItemIOS extends React.Component {} class Button extends React.Component {} } diff --git a/types/react-native-vector-icons/index.d.ts b/types/react-native-vector-icons/index.d.ts index 3e9af9e042..b9dfc622c3 100644 --- a/types/react-native-vector-icons/index.d.ts +++ b/types/react-native-vector-icons/index.d.ts @@ -24,7 +24,7 @@ export function createIconSet( glyphMap: {}, fontFamily: string, fontFile?: string -): Icon; +): typeof Icon; /** * Convenience method to create a custom font based on a fontello config file. @@ -41,7 +41,7 @@ export function createIconSet( * @param {{}} config * @returns {Icon} */ -export function createIconSetFromFontello(config: {}): Icon; +export function createIconSetFromFontello(config: {}): typeof Icon; /** * Convenience method to create a custom font from IcoMoon @@ -59,4 +59,4 @@ export function createIconSetFromFontello(config: {}): Icon; * @param {{}} config * @returns {Icon} */ -export function createIconSetFromIcoMoon(config: {}): Icon; +export function createIconSetFromIcoMoon(config: {}): typeof Icon; diff --git a/types/react-native-vector-icons/react-native-vector-icons-tests.tsx b/types/react-native-vector-icons/react-native-vector-icons-tests.tsx index 99a2b3ac8b..b6adf8d8c6 100644 --- a/types/react-native-vector-icons/react-native-vector-icons-tests.tsx +++ b/types/react-native-vector-icons/react-native-vector-icons-tests.tsx @@ -1,9 +1,22 @@ import * as React from 'react'; import { View, Text, TabBarIOS } from 'react-native'; +import { createIconSet } from 'react-native-vector-icons'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'; import Ionicon from 'react-native-vector-icons/Ionicons'; +const glyphMap = { + custom: 58918 +}; + +const CustomIcon = createIconSet(glyphMap, 'FontCustom', 'FontCustom.ttf'); + +const CustomIconButton = CustomIcon.Button; +const CustomIconTabBarItem = CustomIcon.TabBarItem; +const CustomIconTabBarItemIOS = CustomIcon.TabBarItemIOS; +const CustomIconToolbarAndroid = CustomIcon.ToolbarAndroid; +const CustomIcongetImageSource = CustomIcon.getImageSource; + class Example extends React.Component { handleButton() { console.log('You pressed me'); @@ -30,7 +43,7 @@ class Example extends React.Component { } } -class TabTest extends React.Component { +class TabTest extends React.Component { constructor() { super(); @@ -49,7 +62,7 @@ class TabTest extends React.Component { selectedIconColor="pink" renderAsOriginal selected={this.state.selectedTab === 'tab1'} - onPress={() => this.setState({selectedTab: 'tab1'})} + onPress={() => this.setState({ selectedTab: 'tab1' })} > @@ -61,7 +74,7 @@ class TabTest extends React.Component { selectedIconColor='pink' renderAsOriginal selected={this.state.selectedTab === 'tab2'} - onPress={() => this.setState({selectedTab: 'tab2'})} + onPress={() => this.setState({ selectedTab: 'tab2' })} > @@ -69,3 +82,33 @@ class TabTest extends React.Component { ); } } + +class TestCustomIcon extends React.Component { + constructor() { + super(); + } + + handleButton() { + console.log('You pressed me'); + } + + render() { + return ( + + {/* Custom Icon */} + + + {/* Custom Icon button */} + this.handleButton()} + > + + Hello CustomIcon! + + + + ); + } +} diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 8b31bfed0d..b264df6d64 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for react-native-video 1.0 +// Type definitions for react-native-video 2.0 // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming +// abrahambotros // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -48,7 +49,10 @@ export interface VideoProperties extends ViewProperties { onLoad?(): void; onBuffer?(): void; onError?(): void; - onProgress?(): void; + onProgress?(data: { + currentTime: number, + playableDuration: number, + }): void; onSeek?(): void; onEnd?(): void; onFullscreenPlayerWillPresent?(): void; diff --git a/types/react-native-video/react-native-video-tests.tsx b/types/react-native-video/react-native-video-tests.tsx index e0ec0bad73..5b61336e80 100644 --- a/types/react-native-video/react-native-video-tests.tsx +++ b/types/react-native-video/react-native-video-tests.tsx @@ -7,16 +7,26 @@ import { } from 'react-native'; import Video from 'react-native-video'; -class SwiperTest extends React.Component { +class VideoTest extends React.Component { constructor(props: {}) { super(props); } render(): React.ReactElement { return ( -