diff --git a/types/adone/test/glosses/system/process.ts b/types/adone/test/glosses/system/process.ts index 9ffd3c33a5..9aed20b696 100644 --- a/types/adone/test/glosses/system/process.ts +++ b/types/adone/test/glosses/system/process.ts @@ -223,7 +223,7 @@ namespace adoneTests.system.process { }); ret.on("message", () => {}); - ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + ret.stdout!.pipe(adone.fs.createWriteStream(__filename)); } } @@ -811,7 +811,7 @@ namespace adoneTests.system.process { }); ret.on("message", () => {}); - ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + ret.stdout!.pipe(adone.fs.createWriteStream(__filename)); } } diff --git a/types/autoprefixer/index.d.ts b/types/autoprefixer/index.d.ts index faf11371db..1681c5d838 100644 --- a/types/autoprefixer/index.d.ts +++ b/types/autoprefixer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for autoprefixer 9.1 +// Type definitions for autoprefixer 9.4 // Project: https://github.com/postcss/autoprefixer // Definitions by: Armando Meziat , murt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace autoprefixer { remove?: boolean; supports?: boolean; flexbox?: boolean | 'no-2009'; - grid?: boolean; + grid?: boolean | 'autoplace' | 'no-autoplace'; stats?: any; ignoreUnknownVersions?: boolean; } diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 82fc32a7d3..891361627f 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -878,7 +878,7 @@ export class Buy implements Resource { /** * Associated transaction (e.g. a bank, fiat account) */ - transaction: ResourceRef; + transaction: ResourceRef | null; /** * Amount in bitcoin, litecoin or ethereum @@ -896,7 +896,7 @@ export class Buy implements Resource { subtotal: MoneyHash; /** - * Fee associated to this buy + * Fees associated to this buy */ fees: Fee[]; @@ -935,6 +935,26 @@ export class Buy implements Resource { */ requires_completion_step: boolean; + /** + * Transfer identifier + */ + id: string; + + /** + * Reference code shown in user's dashboard. + */ + user_reference: string; + + /** + * ISO timestamp + */ + created_at: string; + + /** + * ISO timestamp + */ + updated_at: string; + /** * Completes a buy that is created in commit: false state. * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you @@ -995,7 +1015,7 @@ export class Sell implements Resource { /** * Associated transaction (e.g. a bank, fiat account) */ - transaction: ResourceRef; + transaction: ResourceRef | null; /** * Amount in bitcoin, litecoin or ethereum @@ -1013,9 +1033,9 @@ export class Sell implements Resource { subtotal: MoneyHash; /** - * Fee associated to this sell + * Fees associated to this sell */ - fee: MoneyHash; + fees: MoneyHash[]; /** * Has this sell been committed? @@ -1032,6 +1052,26 @@ export class Sell implements Resource { */ payout_at?: string; + /** + * Transfer identifier + */ + id: string; + + /** + * Reference code shown in user's dashboard. + */ + user_reference: string; + + /** + * ISO timestamp + */ + created_at: string; + + /** + * ISO timestamp + */ + updated_at: string; + /** * Completes a sell that is created in commit: false state. * If the exchange rate has changed since the sell was created, this call will fail with the error “The exchange rate updated while you diff --git a/types/consul/consul-tests.ts b/types/consul/consul-tests.ts index 988890766d..263b5beff5 100644 --- a/types/consul/consul-tests.ts +++ b/types/consul/consul-tests.ts @@ -511,6 +511,7 @@ consul = new Consul(); // Consul.Health { let health: Consul.Health = consul.health; + let name: string; health = new HealthStatic(consul); consul = health.consul; diff --git a/types/cross-spawn/cross-spawn-tests.ts b/types/cross-spawn/cross-spawn-tests.ts index 6cb36510d8..f6dac4ea72 100644 --- a/types/cross-spawn/cross-spawn-tests.ts +++ b/types/cross-spawn/cross-spawn-tests.ts @@ -8,7 +8,7 @@ pw.on('error', (err: Error) => { console.log(err); }); -const r1: Error = spawn.sync('foo').error; +const r1: Error | undefined = spawn.sync('foo').error; const r2: string[] = spawn.sync('foo').output; const r3: Buffer = spawn.sync('foo').stdout; const r4: Buffer = spawn.sync('foo').stderr; diff --git a/types/execa/execa-tests.ts b/types/execa/execa-tests.ts index ecc966d3d5..632388106e 100644 --- a/types/execa/execa-tests.ts +++ b/types/execa/execa-tests.ts @@ -43,8 +43,8 @@ execa.shell('echo unicorns').then(result => result.stdout.toLocaleLowerCase()); result = execa.shellSync('noop foo').stdout; } -execa('echo', ['unicorns']).stdout.pipe(process.stdout); -execa('echo', ['unicorns']).stderr.pipe(process.stderr); +execa('echo', ['unicorns']).stdout!.pipe(process.stdout); +execa('echo', ['unicorns']).stderr!.pipe(process.stderr); execa('forever', { extendEnv: false }).pid; execa('forever', { argv0: 'hi' }).pid; @@ -85,7 +85,7 @@ async () => { async () => { const child = execa('stdin'); - child.stdin.end('unicorns'); + child.stdin!.end('unicorns'); const { stdout } = await child; assert(stdout === 'unicorns'); }; @@ -104,7 +104,7 @@ async () => { stdio: [null, 'ignore', null] }); - child.stdout.setEncoding('utf8'); + child.stdout!.setEncoding('utf8'); assert(child.pid === 0); child.kill(); diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index b2a4c0066d..8e973de1ab 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3815,9 +3815,10 @@ export class Text extends Object { /** * measure a text line measuring all characters. * @param {Number} lineIndex line number - * @return {Number} Line width + * @return {Object} object.width total width of characters + * @return {Object} object.numOfSpaces length of chars that match this._reSpacesAndTabs */ - measureLine(lineIndex: number): number; + measureLine(lineIndex: number): { width: number, numOfSpaces: number }; /** * Calculate height of line at 'lineIndex' * @param {Number} lineIndex index of line to calculate diff --git a/types/giphy-api/giphy-api-tests.ts b/types/giphy-api/giphy-api-tests.ts index c5fc86870e..da286ed612 100644 --- a/types/giphy-api/giphy-api-tests.ts +++ b/types/giphy-api/giphy-api-tests.ts @@ -11,26 +11,26 @@ giphyApi({ apiKey: 'API KEY' }); const searchOptions: giphyApi.SearchOptions = { q: 'pokemon', rating: 'g' }; const giphy: giphyApi.Giphy = giphyApi(); giphy.search('pokemon', cb); -giphy.search('pokemon').then(res => {}); +giphy.search('pokemon').then(res => res.data[0]); giphy.search(searchOptions, cb); -giphy.search({ q: 'pokemon', rating: 'g' }).then(res => {}); +giphy.search({ q: 'pokemon', rating: 'g' }).then(res => res.data[0]); giphy.id('feqkVgjJpYtjy', cb); -giphy.id('feqkVgjJpYtjy').then(res => {}); +giphy.id('feqkVgjJpYtjy').then(res => res.data[0]); giphy.id(['feqkVgjJpYtjy'], cb); -giphy.id(['feqkVgjJpYtjy']).then(res => {}); +giphy.id(['feqkVgjJpYtjy']).then(res => res.data[0]); giphy.translate('superman', cb); -giphy.translate('superman').then(res => {}); +giphy.translate('superman').then(res => res.data.id); giphy.translate({ s: 'superman', rating: 'g', fmt: 'html' }, cb); -giphy.translate({ s: 'superman', rating: 'g' }).then(res => {}); +giphy.translate({ s: 'superman', rating: 'g' }).then(res => res.data.id); giphy.random('superman', cb); -giphy.random('superman').then(res => {}); +giphy.random('superman').then(res => res.data.id); giphy.random({ tag: 'superman', rating: 'g' }, cb); -giphy.random({ tag: 'superman', rating: 'g' }).then(res => {}); +giphy.random({ tag: 'superman', rating: 'g' }).then(res => res.data.id); giphy.trending(cb); -giphy.trending().then(res => {}); +giphy.trending().then(res => res.data[0]); giphy.trending({ limit: 2, rating: 'g' }); -giphy.trending({ limit: 2, rating: 'g' }).then(res => {}); +giphy.trending({ limit: 2, rating: 'g' }).then(res => res.data[0]); diff --git a/types/giphy-api/index.d.ts b/types/giphy-api/index.d.ts index d121eff979..1b9b58b324 100644 --- a/types/giphy-api/index.d.ts +++ b/types/giphy-api/index.d.ts @@ -30,7 +30,16 @@ interface BaseImage { height: string; } -type Callback = (err: Error, res: giphyApi.Result) => void; +interface BaseResponse { + pagination: { total_count: number; count: number; offset: number }; + meta: { + status: number; + msg: string; + response_id: string; + }; +} + +type Callback = (err: Error, res: TResponse) => void; declare function giphyApi(apiKeyOrOptions?: string | giphyApi.GiphyOptions): giphyApi.Giphy; @@ -48,131 +57,131 @@ declare namespace giphyApi { } interface Giphy { - search(queryOrOptions: string | SearchOptions, cb: Callback): void; - search(queryOrOptions: string | SearchOptions): Promise; - id(ids: string | string[], cb: Callback): void; - id(ids: string | string[]): Promise; - translate(termOrOptions: string | TranslateOptions, cb: Callback): void; - translate(termOrOptions: string | TranslateOptions): Promise; - random(tagOrOptions: string | RandomOptions, cb: Callback): void; - random(tagOrOptions: string | RandomOptions): Promise; - trending(options: TrendingOptions, cb: Callback): void; - trending(cb: Callback): void; - trending(options?: TrendingOptions): Promise; + search(queryOrOptions: string | SearchOptions, cb: Callback): void; + search(queryOrOptions: string | SearchOptions): Promise; + id(ids: string | string[], cb: Callback): void; + id(ids: string | string[]): Promise; + translate(termOrOptions: string | TranslateOptions, cb: Callback): void; + translate(termOrOptions: string | TranslateOptions): Promise; + random(tagOrOptions: string | RandomOptions, cb: Callback): void; + random(tagOrOptions: string | RandomOptions): Promise; + trending(options: TrendingOptions, cb: Callback): void; + trending(cb: Callback): void; + trending(options?: TrendingOptions): Promise; } - interface Result { - data: [ - { - type: string; - id: string; - slug: string; - url: string; - bitly_url: string; - embed_url: string; - username: string; - source: string; - rating: Rating; - content_url: string; - user?: { - avatar_url: string; - banner_url: string; - profile_url: string; - username: string; - display_name: string; - twitter: string; - }, - source_tld: string; - source_post_url: string; - update_datetime: string; - create_datetime: string; - import_datetime: string; - trending_datetime: string; - title: string; - images: { - fixed_height: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_height_still: BaseImage; - fixed_height_downsampled: BaseImage & { - size: string; - webp: string; - webp_size: string; - }; - fixed_width: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - original_still: BaseImage; - fixed_width_still: BaseImage; - fixed_width_downsampled: BaseImage & { - size: string; - webp: string; - webp_size: string; - }; - fixed_height_small: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_height_small_still: BaseImage; - fixed_width_small: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - fixed_width_small_still: BaseImage; - downsized: BaseImage & { - size: string; - }; - downsized_still: BaseImage; - downsized_large: BaseImage & { - size: string; - }; - downsized_medium: BaseImage & { - size: string; - }; - downsized_small: BaseImage & { - size: string; - }; - original: BaseImage & { - size: string; - frames: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - looping: { mp4: string; }; - preview: { - width: string; - height: string; - mp4: string; - mp4_size: string; - }; - preview_gif: BaseImage & { - size: string; - }; - }; - } - ]; - pagination: { total_count: number; count: number; offset: number }; - meta: { - status: number; - msg: string; - response_id: string; + interface Images { + fixed_height: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; }; + fixed_height_still: BaseImage; + fixed_height_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_width: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + original_still: BaseImage; + fixed_width_still: BaseImage; + fixed_width_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_height_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_height_small_still: BaseImage; + fixed_width_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_width_small_still: BaseImage; + downsized: BaseImage & { + size: string; + }; + downsized_still: BaseImage; + downsized_large: BaseImage & { + size: string; + }; + downsized_medium: BaseImage & { + size: string; + }; + downsized_small: BaseImage & { + size: string; + }; + original: BaseImage & { + size: string; + frames: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + looping: { mp4: string; }; + preview: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + preview_gif: BaseImage & { + size: string; + }; + } + + interface GIFObject { + type: string; + id: string; + slug: string; + url: string; + bitly_url: string; + embed_url: string; + username: string; + source: string; + rating: Rating; + content_url: string; + user?: { + avatar_url: string; + banner_url: string; + profile_url: string; + username: string; + display_name: string; + twitter: string; + }; + source_tld: string; + source_post_url: string; + update_datetime: string; + create_datetime: string; + import_datetime: string; + trending_datetime: string; + title: string; + images: Images; + } + + interface MultiResponse extends BaseResponse { + data: GIFObject[]; + } + + interface SingleResponse extends BaseResponse { + data: GIFObject; } } diff --git a/types/gl-vec3/add.d.ts b/types/gl-vec3/add.d.ts new file mode 100644 index 0000000000..a26dfc655c --- /dev/null +++ b/types/gl-vec3/add.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two number's. + */ +declare function add(out: number[], a: number[], b: number[]): number[]; + +export default add; diff --git a/types/gl-vec3/angle.d.ts b/types/gl-vec3/angle.d.ts new file mode 100644 index 0000000000..366b1cb4b7 --- /dev/null +++ b/types/gl-vec3/angle.d.ts @@ -0,0 +1,6 @@ +/** + * Get the angle between two 3D vectors. + */ +declare function angle(a: number[], b: number[]): number; + +export default angle; diff --git a/types/gl-vec3/clone.d.ts b/types/gl-vec3/clone.d.ts new file mode 100644 index 0000000000..7b56113caa --- /dev/null +++ b/types/gl-vec3/clone.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new number initialized with values from an existing vector. + */ +declare function clone(a: number[]): number[]; + +export default clone; diff --git a/types/gl-vec3/copy.d.ts b/types/gl-vec3/copy.d.ts new file mode 100644 index 0000000000..821f2493a7 --- /dev/null +++ b/types/gl-vec3/copy.d.ts @@ -0,0 +1,6 @@ +/** + * Copy the values from one number to another. + */ +declare function copy(out: number[], a: number[]): number[]; + +export default copy; diff --git a/types/gl-vec3/create.d.ts b/types/gl-vec3/create.d.ts new file mode 100644 index 0000000000..5577d59d7d --- /dev/null +++ b/types/gl-vec3/create.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new, empty number. + */ +declare function create(): number[]; + +export default create; diff --git a/types/gl-vec3/dist.d.ts b/types/gl-vec3/dist.d.ts new file mode 100644 index 0000000000..bb4df7b83f --- /dev/null +++ b/types/gl-vec3/dist.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the euclidian distance between two number's. Aliased as dist. + */ +declare function dist(a: number[], b: number[]): number; + +export default dist; diff --git a/types/gl-vec3/div.d.ts b/types/gl-vec3/div.d.ts new file mode 100644 index 0000000000..be3bcf68a0 --- /dev/null +++ b/types/gl-vec3/div.d.ts @@ -0,0 +1,6 @@ +/** + * Divides two number's. Aliased as div. + */ +declare function div(out: number[], a: number[], b: number[]): number[]; + +export default div; diff --git a/types/gl-vec3/dot.d.ts b/types/gl-vec3/dot.d.ts new file mode 100644 index 0000000000..efe2caf624 --- /dev/null +++ b/types/gl-vec3/dot.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the dot product of two number's. + */ +declare function dot(a: number[], b: number[]): number; + +export default dot; diff --git a/types/gl-vec3/equals.d.ts b/types/gl-vec3/equals.d.ts new file mode 100644 index 0000000000..91aeaa3bbd --- /dev/null +++ b/types/gl-vec3/equals.d.ts @@ -0,0 +1,6 @@ +/** + * Returns whether or not the vectors have approximately the same elements in the same position.. + */ +declare function equals(a: number[], b: number[]): boolean; + +export default equals; diff --git a/types/gl-vec3/exactEquals.d.ts b/types/gl-vec3/exactEquals.d.ts new file mode 100644 index 0000000000..c68b328f69 --- /dev/null +++ b/types/gl-vec3/exactEquals.d.ts @@ -0,0 +1,6 @@ +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===). + */ +declare function exactEquals(a: number[], b: number[]): boolean; + +export default exactEquals; diff --git a/types/gl-vec3/forEach.d.ts b/types/gl-vec3/forEach.d.ts new file mode 100644 index 0000000000..8805286fb0 --- /dev/null +++ b/types/gl-vec3/forEach.d.ts @@ -0,0 +1,6 @@ +/** + * Perform some operation over an array of numbers. + */ +declare function forEach(a: number[], stride: number, offset: number, count: number, fn: (a: number[], b: number[], arg: object) => number[], arg: object): number[]; + +export default forEach; diff --git a/types/gl-vec3/fromValues.d.ts b/types/gl-vec3/fromValues.d.ts new file mode 100644 index 0000000000..8fd52fbcee --- /dev/null +++ b/types/gl-vec3/fromValues.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new number initialized with the given values. + */ +declare function fromValues(x: number, y: number, z: number): number[]; + +export default fromValues; diff --git a/types/gl-vec3/gl-vec3-tests.ts b/types/gl-vec3/gl-vec3-tests.ts new file mode 100644 index 0000000000..67be9102a9 --- /dev/null +++ b/types/gl-vec3/gl-vec3-tests.ts @@ -0,0 +1,121 @@ +import * as GlVec3 from "gl-vec3"; +import GLVec3Add from "gl-vec3/add"; +import GLVec3Angle from "gl-vec3/angle"; +import GLVec3Clone from "gl-vec3/clone"; +import GLVec3Copy from "gl-vec3/copy"; +import GLVec3Create from "gl-vec3/create"; +import GLVec3Dist from "gl-vec3/dist"; +import GLVec3Div from "gl-vec3/div"; +import GLVec3Dot from "gl-vec3/dot"; +import GLVec3Equals from "gl-vec3/equals"; +import GLVec3exactEquals from "gl-vec3/exactEquals"; +import GLVec3forEach from "gl-vec3/forEach"; +import GLVec3fromValues from "gl-vec3/fromValues"; +import GLVec3Inverse from "gl-vec3/inverse"; +import GLVec3Len from "gl-vec3/len"; +import GLVec3Lerp from "gl-vec3/lerp"; +import GLVec3Max from "gl-vec3/max"; +import GLVec3Min from "gl-vec3/min"; +import GLVec3Mul from "gl-vec3/mul"; +import GLVec3Negate from "gl-vec3/negate"; +import GLVec3Normalize from "gl-vec3/normalize"; +import GLVec3Random from "gl-vec3/random"; +import GLVec3Scale from "gl-vec3/scale"; +import GLVec3ScaleAndAdd from "gl-vec3/scaleAndAdd"; +import GLVec3Set from "gl-vec3/set"; +import GLVec3SqrDist from "gl-vec3/sqrDist"; +import GLVec3SqrLen from "gl-vec3/sqrLen"; +import GLVec3Sub from "gl-vec3/sub"; +import GLVec3TransformMat3 from "gl-vec3/transformMat3"; +import GLVec3TransformMat4 from "gl-vec3/transformMat4"; +import GLVec3TransformQuat from "gl-vec3/transformQuat"; + +GlVec3.add([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Add([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.angle([1, 2, 3], [1, 2, 3]); +GLVec3Angle([1, 2, 3], [1, 2, 3]); + +GlVec3.clone([1, 2, 3]); +GLVec3Clone([1, 2, 3]); + +GlVec3.copy([1, 2, 3], [1, 2, 3]); +GLVec3Copy([1, 2, 3], [1, 2, 3]); + +GlVec3.create(); +GLVec3Create(); + +GlVec3.dist([1, 2, 3], [1, 2, 3]); +GLVec3Dist([1, 2, 3], [1, 2, 3]); + +GlVec3.div([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Div([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.dot([1, 2, 3], [1, 2, 3]); +GLVec3Dot([1, 2, 3], [1, 2, 3]); + +GlVec3.forEach([1, 2, 3], 5, 6, 1, () => [3], {}); +GLVec3forEach([1, 2, 3], 5, 6, 1, () => [3], {}); + +GlVec3.fromValues(1, 2, 3); +GLVec3fromValues(1, 2, 3); + +GlVec3.equals([1, 2, 3], [1, 2, 3]); +GLVec3Equals([1, 2, 3], [1, 2, 3]); + +GlVec3.exactEquals([1, 2, 3], [1, 2, 3]); +GLVec3exactEquals([1, 2, 3], [1, 2, 3]); + +GlVec3.inverse([1, 2, 3], [1, 2, 3]); +GLVec3Inverse([1, 2, 3], [1, 2, 3]); + +GlVec3.len([1, 2, 3]); +GLVec3Len([1, 2, 3]); + +GlVec3.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +GLVec3Lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +GlVec3.max([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Max([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.min([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Min([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.mul([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Mul([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.negate([1, 2, 3], [1, 2, 3]); +GLVec3Negate([1, 2, 3], [1, 2, 3]); + +GlVec3.normalize([1, 2, 3], [1, 2, 3]); +GLVec3Normalize([1, 2, 3], [1, 2, 3]); + +GlVec3.random([1, 2, 3], 6); +GLVec3Random([1, 2, 3], 6); + +GlVec3.scale([1, 2, 3], [1, 2, 3], 6); +GLVec3Scale([1, 2, 3], [1, 2, 3], 6); + +GlVec3.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +GLVec3ScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +GlVec3.set([1, 2, 3], 1, 2, 6); +GLVec3Set([1, 2, 3], 1, 2, 6); + +GlVec3.sqrDist([1, 2, 3], [1, 2, 3]); +GLVec3SqrDist([1, 2, 3], [1, 2, 3]); + +GlVec3.sqrLen([1, 2, 3]); +GLVec3SqrLen([1, 2, 3]); + +GlVec3.sub([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3Sub([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformMat3([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +GlVec3.transformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); +GLVec3TransformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); diff --git a/types/gl-vec3/index.d.ts b/types/gl-vec3/index.d.ts new file mode 100644 index 0000000000..0d90cfe981 --- /dev/null +++ b/types/gl-vec3/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for gl-vec3 1.1 +// Project: https://github.com/stackgl/gl-vec3 +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +/** + * Adds two number's. + */ +export function add(out: number[], a: number[], b: number[]): number[]; + +/** + * Get the angle between two 3D vectors. + */ +export function angle(a: number[], b: number[]): number; + +/** + * Creates a new number initialized with values from an existing vector. + */ +export function clone(a: number[]): number[]; + +/** + * Math.ceil the components of a number. + */ +export function ceil(out: number[], a: number[]): number[]; + +/** + * Copy the values from one number to another. + */ +export function copy(out: number[], a: number[]): number[]; + +/** + * Creates a new, empty number. + */ +export function create(): number[]; + +/** + * Computes the cross product of two number's. + */ +export function cross(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the euclidian distance between two number's. Aliased as dist. + */ +export function dist(a: number[], b: number[]): number; + +/** + * Divides two number's. Aliased as div. + */ +export function div(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the dot product of two number's. + */ +export function dot(a: number[], b: number[]): number; + +/** + * Returns whether or not the vectors have approximately the same elements in the same position.. + */ +export function equals(a: number[], b: number[]): boolean; + +/** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===). + */ +export function exactEquals(a: number[], b: number[]): boolean; + +/** + * Math.floor the components of a number. + */ +export function floor(out: number[], a: number[]): number[]; + +/** + * Perform some operation over an array of numbers. + */ +export function forEach(a: number[], stride: number, offset: number, count: number, fn: (a: number[], b: number[], arg: object) => number[], arg: object): number[]; + +/** + * Creates a new number initialized with the given values. + */ +export function fromValues(x: number, y: number, z: number): number[]; + +/** + * Returns the inverse of the components of a number. + */ +export function inverse(out: number[], a: number[]): number[]; + +/** + * Calculates the length of a number. Aliased as len. + */ +export function len(a: number[]): number; + +/** + * Performs a linear interpolation between two number]'s. + */ +export function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +/** + * Returns the maximum of two number's. + */ +export function max(out: number[], a: number[], b: number[]): number[]; + +/** + * Returns the minimum of two number's. + */ +export function min(out: number[], a: number[], b: number[]): number[]; + +/** + * Multiplies two number's. Aliased as mul. + */ +export function mul(out: number[], a: number[], b: number[]): number[]; + +/** + * Negates the components of a number. + */ +export function negate(out: number[], a: number[]): number[]; + +/** + * Normalize a number + */ +export function normalize(out: number[], a: number[]): number[]; + +/** + * Generates a random vector with the given scale. + */ +export function random(out: number[], scale: number): number[]; + +/** + * Rotate a 3D vector around the x-axis. + */ +export function rotateX(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Rotate a 3D vector around the y-axis. + */ +export function rotateY(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Rotate a 3D vector around the z-axis. + */ +export function rotateZ(out: number[], a: number[], b: number[], c: number): number[]; + +/** + * Math.round the components of a number. + */ +export function round(out: number[], a: number[]): number[]; + +/** + * Scales a number by a scalar number. + */ +export function scale(out: number[], a: number[], b: number): number[]; + +/** + * Adds two numbers after scaling the second operand by a scalar value. + */ +export function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +/** + * Set the components of a number to the given values. + */ +export function set(out: number[], x: number, y: number, z: number): number[]; + +/** + * Calculates the squared euclidian distance between two number's. Aliased as sqrDist. + */ +export function sqrDist(a: number[], b: number[]): number[]; + +/** + * Calculates the squared length of a number. Aliased as sqrLen. + */ +export function sqrLen(a: number[]): number[]; + +/** + * Subtracts vector b from vector a. Aliased as sub. + */ +export function sub(out: number[], a: number[], b: number[]): number[]; + +/** + * Transforms the number with a mat3. + */ +export function transformMat3(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the number with a mat4. 4th vector component is implicitly '1'. + */ +export function transformMat4(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the number with a quat. + */ +export function transformQuat(out: number[], a: number[], q: number[]): number[]; diff --git a/types/gl-vec3/inverse.d.ts b/types/gl-vec3/inverse.d.ts new file mode 100644 index 0000000000..bbe2345665 --- /dev/null +++ b/types/gl-vec3/inverse.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the inverse of the components of a number. + */ +declare function inverse(out: number[], a: number[]): number[]; + +export default inverse; diff --git a/types/gl-vec3/len.d.ts b/types/gl-vec3/len.d.ts new file mode 100644 index 0000000000..0bd0473614 --- /dev/null +++ b/types/gl-vec3/len.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the length of a number. Aliased as len. + */ +declare function len(a: number[]): number; + +export default len; diff --git a/types/gl-vec3/lerp.d.ts b/types/gl-vec3/lerp.d.ts new file mode 100644 index 0000000000..a595db2bf8 --- /dev/null +++ b/types/gl-vec3/lerp.d.ts @@ -0,0 +1,6 @@ +/** + * Performs a linear interpolation between two number]'s. + */ +declare function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +export default lerp; diff --git a/types/gl-vec3/max.d.ts b/types/gl-vec3/max.d.ts new file mode 100644 index 0000000000..37458f7eb9 --- /dev/null +++ b/types/gl-vec3/max.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the maximum of two number's. + */ +declare function max(out: number[], a: number[], b: number[]): number[]; + +export default max; diff --git a/types/gl-vec3/min.d.ts b/types/gl-vec3/min.d.ts new file mode 100644 index 0000000000..6c8cdc6600 --- /dev/null +++ b/types/gl-vec3/min.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the minimum of two number's. + */ +declare function min(out: number[], a: number[], b: number[]): number[]; + +export default min; diff --git a/types/gl-vec3/mul.d.ts b/types/gl-vec3/mul.d.ts new file mode 100644 index 0000000000..76559d847a --- /dev/null +++ b/types/gl-vec3/mul.d.ts @@ -0,0 +1,6 @@ +/** + * Multiplies two number's. Aliased as mul. + */ +declare function mul(out: number[], a: number[], b: number[]): number[]; + +export default mul; diff --git a/types/gl-vec3/negate.d.ts b/types/gl-vec3/negate.d.ts new file mode 100644 index 0000000000..84b6443e30 --- /dev/null +++ b/types/gl-vec3/negate.d.ts @@ -0,0 +1,6 @@ +/** + * Negates the components of a number. + */ +declare function negate(out: number[], a: number[]): number[]; + +export default negate; diff --git a/types/gl-vec3/normalize.d.ts b/types/gl-vec3/normalize.d.ts new file mode 100644 index 0000000000..f060e59f73 --- /dev/null +++ b/types/gl-vec3/normalize.d.ts @@ -0,0 +1,6 @@ +/** + * Normalize a number + */ +declare function normalize(out: number[], a: number[]): number[]; + +export default normalize; diff --git a/types/gl-vec3/random.d.ts b/types/gl-vec3/random.d.ts new file mode 100644 index 0000000000..94fd5f57e4 --- /dev/null +++ b/types/gl-vec3/random.d.ts @@ -0,0 +1,6 @@ +/** + * Generates a random vector with the given scale. + */ +declare function random(out: number[], scale: number): number[]; + +export default random; diff --git a/types/gl-vec3/scale.d.ts b/types/gl-vec3/scale.d.ts new file mode 100644 index 0000000000..b5f8b63e9f --- /dev/null +++ b/types/gl-vec3/scale.d.ts @@ -0,0 +1,6 @@ +/** + * Scales a number by a scalar number. + */ +declare function scale(out: number[], a: number[], b: number): number[]; + +export default scale; diff --git a/types/gl-vec3/scaleAndAdd.d.ts b/types/gl-vec3/scaleAndAdd.d.ts new file mode 100644 index 0000000000..a6eea747bd --- /dev/null +++ b/types/gl-vec3/scaleAndAdd.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two numbers after scaling the second operand by a scalar value. + */ +declare function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +export default scaleAndAdd; diff --git a/types/gl-vec3/set.d.ts b/types/gl-vec3/set.d.ts new file mode 100644 index 0000000000..02d24eda97 --- /dev/null +++ b/types/gl-vec3/set.d.ts @@ -0,0 +1,6 @@ +/** + * Set the components of a number to the given values. + */ +declare function set(out: number[], x: number, y: number, z: number): number[]; + +export default set; diff --git a/types/gl-vec3/sqrDist.d.ts b/types/gl-vec3/sqrDist.d.ts new file mode 100644 index 0000000000..9488750632 --- /dev/null +++ b/types/gl-vec3/sqrDist.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared euclidian distance between two number's. Aliased as sqrDist. + */ +declare function sqrDist(a: number[], b: number[]): number[]; + +export default sqrDist; diff --git a/types/gl-vec3/sqrLen.d.ts b/types/gl-vec3/sqrLen.d.ts new file mode 100644 index 0000000000..99e072fa44 --- /dev/null +++ b/types/gl-vec3/sqrLen.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared length of a number. Aliased as sqrLen. + */ +declare function sqrLen(a: number[]): number[]; + +export default sqrLen; diff --git a/types/gl-vec3/sub.d.ts b/types/gl-vec3/sub.d.ts new file mode 100644 index 0000000000..10bcab9eca --- /dev/null +++ b/types/gl-vec3/sub.d.ts @@ -0,0 +1,6 @@ +/** + * Subtracts vector b from vector a. Aliased as sub. + */ +declare function sub(out: number[], a: number[], b: number[]): number[]; + +export default sub; diff --git a/types/gl-vec3/transformMat3.d.ts b/types/gl-vec3/transformMat3.d.ts new file mode 100644 index 0000000000..bab8234194 --- /dev/null +++ b/types/gl-vec3/transformMat3.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a mat3. + */ +declare function transformMat3(out: number[], a: number[], m: number[]): number[]; + +export default transformMat3; diff --git a/types/gl-vec3/transformMat4.d.ts b/types/gl-vec3/transformMat4.d.ts new file mode 100644 index 0000000000..35c6424380 --- /dev/null +++ b/types/gl-vec3/transformMat4.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a mat4. 4th vector component is implicitly '1'. + */ +declare function transformMat4(out: number[], a: number[], m: number[]): number[]; + +export default transformMat4; diff --git a/types/gl-vec3/transformQuat.d.ts b/types/gl-vec3/transformQuat.d.ts new file mode 100644 index 0000000000..2cba13bfc8 --- /dev/null +++ b/types/gl-vec3/transformQuat.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the number with a quat. + */ +declare function transformQuat(out: number[], a: number[], q: number[]): number[]; + +export default transformQuat; diff --git a/types/gl-vec3/tsconfig.json b/types/gl-vec3/tsconfig.json new file mode 100644 index 0000000000..5382911c1a --- /dev/null +++ b/types/gl-vec3/tsconfig.json @@ -0,0 +1,55 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angle.d.ts", + "add.d.ts", + "clone.d.ts", + "copy.d.ts", + "create.d.ts", + "dist.d.ts", + "div.d.ts", + "dot.d.ts", + "equals.d.ts", + "exactEquals.d.ts", + "forEach.d.ts", + "fromValues.d.ts", + "inverse.d.ts", + "len.d.ts", + "lerp.d.ts", + "max.d.ts", + "min.d.ts", + "mul.d.ts", + "negate.d.ts", + "normalize.d.ts", + "random.d.ts", + "scale.d.ts", + "scaleAndAdd.d.ts", + "set.d.ts", + "sqrDist.d.ts", + "sqrLen.d.ts", + "sub.d.ts", + "transformMat3.d.ts", + "transformMat4.d.ts", + "transformQuat.d.ts", + "gl-vec3-tests.ts" + ] +} diff --git a/types/gl-vec3/tslint.json b/types/gl-vec3/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gl-vec3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/gl-vec4/add.d.ts b/types/gl-vec4/add.d.ts new file mode 100644 index 0000000000..8d7cb4e851 --- /dev/null +++ b/types/gl-vec4/add.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two vec4's. + */ +declare function add(out: number[], a: number[], b: number[]): number[]; + +export default add; diff --git a/types/gl-vec4/clone.d.ts b/types/gl-vec4/clone.d.ts new file mode 100644 index 0000000000..e2b7777cd2 --- /dev/null +++ b/types/gl-vec4/clone.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new vec4 initialized with values from an existing vector. + */ +declare function clone(a: number[]): number[]; + +export default clone; diff --git a/types/gl-vec4/copy.d.ts b/types/gl-vec4/copy.d.ts new file mode 100644 index 0000000000..76e60c5cf6 --- /dev/null +++ b/types/gl-vec4/copy.d.ts @@ -0,0 +1,6 @@ +/** + * Copy the values from one vec4 to another. + */ +declare function copy(out: number[], a: number[]): number[]; + +export default copy; diff --git a/types/gl-vec4/create.d.ts b/types/gl-vec4/create.d.ts new file mode 100644 index 0000000000..93216fe4b0 --- /dev/null +++ b/types/gl-vec4/create.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new, empty vec4. + */ +declare function create(): number[]; + +export default create; diff --git a/types/gl-vec4/distance.d.ts b/types/gl-vec4/distance.d.ts new file mode 100644 index 0000000000..201b734b17 --- /dev/null +++ b/types/gl-vec4/distance.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the euclidian distance between two vec4's. + */ +declare function distance(a: number[], b: number[]): number; + +export default distance; diff --git a/types/gl-vec4/divide.d.ts b/types/gl-vec4/divide.d.ts new file mode 100644 index 0000000000..847dd7ce73 --- /dev/null +++ b/types/gl-vec4/divide.d.ts @@ -0,0 +1,6 @@ +/** + * Divides two vec4's. + */ +declare function divide(out: number[], a: number[], b: number[]): number[]; + +export default divide; diff --git a/types/gl-vec4/dot.d.ts b/types/gl-vec4/dot.d.ts new file mode 100644 index 0000000000..218d2bfe91 --- /dev/null +++ b/types/gl-vec4/dot.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the dot product of two vec4's. + */ +declare function dot(a: number[], b: number[]): number; + +export default dot; diff --git a/types/gl-vec4/fromValues.d.ts b/types/gl-vec4/fromValues.d.ts new file mode 100644 index 0000000000..84d60a9c10 --- /dev/null +++ b/types/gl-vec4/fromValues.d.ts @@ -0,0 +1,6 @@ +/** + * Creates a new vec4 initialized with the given values. + */ +declare function fromValues(x: number, y: number, z: number, w: number): number[]; + +export default fromValues; diff --git a/types/gl-vec4/gl-vec4-tests.ts b/types/gl-vec4/gl-vec4-tests.ts new file mode 100644 index 0000000000..302596450a --- /dev/null +++ b/types/gl-vec4/gl-vec4-tests.ts @@ -0,0 +1,102 @@ +import * as glVec from "gl-vec4"; + +import glVecAdd from "gl-vec4/add"; +import glVecClone from "gl-vec4/clone"; +import glVecCopy from "gl-vec4/copy"; +import glVecCreate from "gl-vec4/create"; +import glVecDistance from "gl-vec4/distance"; +import glVecDivide from "gl-vec4/divide"; +import glVecDot from "gl-vec4/dot"; +import glVecFromValues from "gl-vec4/fromValues"; +import glVecInverse from "gl-vec4/inverse"; +import glVecLength from "gl-vec4/length"; +import glVecLerp from "gl-vec4/lerp"; +import glVecMax from "gl-vec4/max"; +import glVecMin from "gl-vec4/min"; +import glVecMultiply from "gl-vec4/multiply"; +import glVecNegate from "gl-vec4/negate"; +import glVecNormalize from "gl-vec4/normalize"; +import glVecRandom from "gl-vec4/random"; +import glVecScale from "gl-vec4/scale"; +import glVecScaleAndAdd from "gl-vec4/scaleAndAdd"; +import glVecSet from "gl-vec4/set"; +import glVecSqrdDistance from "gl-vec4/squaredDistance"; +import glVecSqrdLength from "gl-vec4/squaredLength"; +import glVecSubtract from "gl-vec4/subtract"; +import glVecTransformMat4 from "gl-vec4/transformMat4"; +import glVecTransformQuat from "gl-vec4/transformQuat"; + +glVec.add([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecAdd([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.clone([1, 2, 3]); +glVecClone([1, 2, 3]); + +glVec.copy([1, 2, 3], [1, 2, 3]); +glVecCopy([1, 2, 3], [1, 2, 3]); + +glVec.create(); +glVecCreate(); + +glVec.distance([1, 2, 3], [1, 2, 3]); +glVecDistance([1, 2, 3], [1, 2, 3]); + +glVec.divide([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecDivide([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.dot([1, 2, 3], [1, 2, 3]); +glVecDot([1, 2, 3], [1, 2, 3]); + +glVec.fromValues(1, 2, 4, 5); +glVecFromValues(1, 2, 4, 5); + +glVec.inverse([1, 2, 3], [1, 2, 3]); +glVecInverse([1, 2, 3], [1, 2, 3]); + +glVec.length([1, 2, 3]); +glVecLength([1, 2, 3]); + +glVec.lerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +glVecLerp([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +glVec.max([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMax([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.min([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMin([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.multiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecMultiply([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.negate([1, 2, 3], [1, 2, 3]); +glVecNegate([1, 2, 3], [1, 2, 3]); + +glVec.normalize([1, 2, 3], [1, 2, 3]); +glVecNormalize([1, 2, 3], [1, 2, 3]); + +glVec.random([1, 2, 3], 6); +glVecRandom([1, 2, 3], 6); + +glVec.scale([1, 2, 3], [1, 2, 3], 6); +glVecScale([1, 2, 3], [1, 2, 3], 6); + +glVec.scaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); +glVecScaleAndAdd([1, 2, 3], [1, 2, 3], [1, 2, 3], 6); + +glVec.set([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); +glVecSet([1, 2, 3], [1, 2, 3], [1, 2, 3], 6, 6); + +glVec.squaredDistance([1, 2, 3], [1, 2, 3]); +glVecSqrdDistance([1, 2, 3], [1, 2, 3]); + +glVec.squaredLength([1, 2, 3]); +glVecSqrdLength([1, 2, 3]); + +glVec.subtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecSubtract([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.transformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecTransformMat4([1, 2, 3], [1, 2, 3], [1, 2, 3]); + +glVec.transformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); +glVecTransformQuat([1, 2, 3], [1, 2, 3], [1, 2, 3]); diff --git a/types/gl-vec4/index.d.ts b/types/gl-vec4/index.d.ts new file mode 100644 index 0000000000..3d5e54e562 --- /dev/null +++ b/types/gl-vec4/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for gl-vec4 1.0 +// Project: https://github.com/stackgl/gl-vec4 +// Definitions by: Adam Zerella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Adds two vec4's. + */ +export function add(out: number[], a: number[], b: number[]): number[]; + +/** + * Creates a new vec4 initialized with values from an existing vector. + */ +export function clone(a: number[]): number[]; + +/** + * Copy the values from one vec4 to another. + */ +export function copy(out: number[], a: number[]): number[]; + +/** + * Creates a new, empty vec4. + */ +export function create(): number[]; + +/** + * Calculates the euclidian distance between two vec4's. + */ +export function distance(a: number[], b: number[]): number; + +/** + * Divides two vec4's. + */ +export function divide(out: number[], a: number[], b: number[]): number[]; + +/** + * Calculates the dot product of two vec4's. + */ +export function dot(a: number[], b: number[]): number; + +/** + * Creates a new vec4 initialized with the given values. + */ +export function fromValues(x: number, y: number, z: number, w: number): number[]; + +/** + * Returns the inverse of the components of a vec4. + */ +export function inverse(out: number[], a: number[]): number[]; + +/** + * Calculates the length of a vec4. + */ +export function length(a: number[]): number; + +/** + * Performs a linear interpolation between two vec4's. + */ +export function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +/** + * Returns the maximum of two vec4's. + */ +export function max(out: number[], a: number[], b: number[]): number[]; + +/** + * Returns the minimum of two vec4's. + */ +export function min(out: number[], a: number[], b: number[]): number[]; + +/** + * Multiplies two vec4's. + */ +export function multiply(out: number[], a: number[], b: number[]): number[]; + +/** + * Negates the components of a vec4. + */ +export function negate(out: number[], a: number[]): number[]; + +/** + * Normalize a vec4. + */ +export function normalize(out: number[], a: number[]): number[]; + +/** + * Generates a random vector with the given scale. + */ +export function random(out: number[], scale: number): number[]; + +/** + * Scales a vec4 by a scalar number. + */ +export function scale(out: number[], a: number[], b: number): number[]; + +/** + * Adds two vec4's after scaling the second operand by a scalar value. + */ +export function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +/** + * Set the components of a vec4 to the given values. + */ +export function set(out: number[], x: number[], y: number[], z: number, w: number): number[]; + +/** + * Calculates the squared euclidian distance between two vec4's. + */ +export function squaredDistance(a: number[], b: number[]): number; + +/** + * Calculates the squared length of a vec4. + */ +export function squaredLength(a: number[]): number; + +/** + * Subtracts vector b from vector a. + */ +export function subtract(out: number[], a: number[], b: number[]): number[]; + +/** + * Transforms the vec4 with a mat4.. + */ +export function transformMat4(out: number[], a: number[], m: number[]): number[]; + +/** + * Transforms the vec4 with a quat. + */ +export function transformQuat(out: number[], a: number[], q: number[]): number[]; diff --git a/types/gl-vec4/inverse.d.ts b/types/gl-vec4/inverse.d.ts new file mode 100644 index 0000000000..4df5cb7491 --- /dev/null +++ b/types/gl-vec4/inverse.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the inverse of the components of a vec4. + */ +declare function inverse(out: number[], a: number[]): number[]; + +export default inverse; diff --git a/types/gl-vec4/length.d.ts b/types/gl-vec4/length.d.ts new file mode 100644 index 0000000000..229b629c89 --- /dev/null +++ b/types/gl-vec4/length.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the length of a vec4. + */ +declare function length(a: number[]): number; + +export default length; diff --git a/types/gl-vec4/lerp.d.ts b/types/gl-vec4/lerp.d.ts new file mode 100644 index 0000000000..c56471ecf1 --- /dev/null +++ b/types/gl-vec4/lerp.d.ts @@ -0,0 +1,6 @@ +/** + * Performs a linear interpolation between two vec4's. + */ +declare function lerp(out: number[], a: number[], b: number[], t: number): number[]; + +export default lerp; diff --git a/types/gl-vec4/max.d.ts b/types/gl-vec4/max.d.ts new file mode 100644 index 0000000000..ca179a75ab --- /dev/null +++ b/types/gl-vec4/max.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the maximum of two vec4's. + */ +declare function max(out: number[], a: number[], b: number[]): number[]; + +export default max; diff --git a/types/gl-vec4/min.d.ts b/types/gl-vec4/min.d.ts new file mode 100644 index 0000000000..48544195a5 --- /dev/null +++ b/types/gl-vec4/min.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the minimum of two vec4's. + */ +declare function min(out: number[], a: number[], b: number[]): number[]; + +export default min; diff --git a/types/gl-vec4/multiply.d.ts b/types/gl-vec4/multiply.d.ts new file mode 100644 index 0000000000..9708f570ea --- /dev/null +++ b/types/gl-vec4/multiply.d.ts @@ -0,0 +1,6 @@ +/** + * Multiplies two vec4's. + */ +declare function multiply(out: number[], a: number[], b: number[]): number[]; + +export default multiply; diff --git a/types/gl-vec4/negate.d.ts b/types/gl-vec4/negate.d.ts new file mode 100644 index 0000000000..b62a5bab84 --- /dev/null +++ b/types/gl-vec4/negate.d.ts @@ -0,0 +1,6 @@ +/** + * Negates the components of a vec4. + */ +declare function negate(out: number[], a: number[]): number[]; + +export default negate; diff --git a/types/gl-vec4/normalize.d.ts b/types/gl-vec4/normalize.d.ts new file mode 100644 index 0000000000..2d09e91543 --- /dev/null +++ b/types/gl-vec4/normalize.d.ts @@ -0,0 +1,6 @@ +/** + * Normalize a vec4. + */ +declare function normalize(out: number[], a: number[]): number[]; + +export default normalize; diff --git a/types/gl-vec4/random.d.ts b/types/gl-vec4/random.d.ts new file mode 100644 index 0000000000..94fd5f57e4 --- /dev/null +++ b/types/gl-vec4/random.d.ts @@ -0,0 +1,6 @@ +/** + * Generates a random vector with the given scale. + */ +declare function random(out: number[], scale: number): number[]; + +export default random; diff --git a/types/gl-vec4/scale.d.ts b/types/gl-vec4/scale.d.ts new file mode 100644 index 0000000000..cb6d5747a8 --- /dev/null +++ b/types/gl-vec4/scale.d.ts @@ -0,0 +1,6 @@ +/** + * Scales a vec4 by a scalar number. + */ +declare function scale(out: number[], a: number[], b: number): number[]; + +export default scale; diff --git a/types/gl-vec4/scaleAndAdd.d.ts b/types/gl-vec4/scaleAndAdd.d.ts new file mode 100644 index 0000000000..3912aadceb --- /dev/null +++ b/types/gl-vec4/scaleAndAdd.d.ts @@ -0,0 +1,6 @@ +/** + * Adds two vec4's after scaling the second operand by a scalar value. + */ +declare function scaleAndAdd(out: number[], a: number[], b: number[], scale: number): number[]; + +export default scaleAndAdd; diff --git a/types/gl-vec4/set.d.ts b/types/gl-vec4/set.d.ts new file mode 100644 index 0000000000..36040f5638 --- /dev/null +++ b/types/gl-vec4/set.d.ts @@ -0,0 +1,6 @@ +/** + * Set the components of a vec4 to the given values. + */ +declare function set(out: number[], x: number[], y: number[], z: number, w: number): number[]; + +export default set; diff --git a/types/gl-vec4/squaredDistance.d.ts b/types/gl-vec4/squaredDistance.d.ts new file mode 100644 index 0000000000..539f702ffb --- /dev/null +++ b/types/gl-vec4/squaredDistance.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared euclidian distance between two vec4's. + */ +declare function squaredDistance(a: number[], b: number[]): number; + +export default squaredDistance; diff --git a/types/gl-vec4/squaredLength.d.ts b/types/gl-vec4/squaredLength.d.ts new file mode 100644 index 0000000000..226d528c81 --- /dev/null +++ b/types/gl-vec4/squaredLength.d.ts @@ -0,0 +1,6 @@ +/** + * Calculates the squared length of a vec4. + */ +declare function squaredLength(a: number[]): number; + +export default squaredLength; diff --git a/types/gl-vec4/subtract.d.ts b/types/gl-vec4/subtract.d.ts new file mode 100644 index 0000000000..1ba0aba3bc --- /dev/null +++ b/types/gl-vec4/subtract.d.ts @@ -0,0 +1,6 @@ +/** + * Subtracts vector b from vector a. + */ +declare function subtract(out: number[], a: number[], b: number[]): number[]; + +export default subtract; diff --git a/types/gl-vec4/transformMat4.d.ts b/types/gl-vec4/transformMat4.d.ts new file mode 100644 index 0000000000..762b5c4bc8 --- /dev/null +++ b/types/gl-vec4/transformMat4.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the vec4 with a mat4.. + */ +declare function transformMat4(out: number[], a: number[], m: number[]): number[]; + +export default transformMat4; diff --git a/types/gl-vec4/transformQuat.d.ts b/types/gl-vec4/transformQuat.d.ts new file mode 100644 index 0000000000..8f6dadd4c1 --- /dev/null +++ b/types/gl-vec4/transformQuat.d.ts @@ -0,0 +1,6 @@ +/** + * Transforms the vec4 with a quat. + */ +declare function transformQuat(out: number[], a: number[], q: number[]): number[]; + +export default transformQuat; diff --git a/types/gl-vec4/tsconfig.json b/types/gl-vec4/tsconfig.json new file mode 100644 index 0000000000..341f7c3271 --- /dev/null +++ b/types/gl-vec4/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "add.d.ts", + "clone.d.ts", + "copy.d.ts", + "create.d.ts", + "distance.d.ts", + "divide.d.ts", + "dot.d.ts", + "fromValues.d.ts", + "inverse.d.ts", + "length.d.ts", + "lerp.d.ts", + "max.d.ts", + "min.d.ts", + "multiply.d.ts", + "negate.d.ts", + "normalize.d.ts", + "random.d.ts", + "scale.d.ts", + "scaleAndAdd.d.ts", + "set.d.ts", + "squaredDistance.d.ts", + "squaredLength.d.ts", + "subtract.d.ts", + "transformMat4.d.ts", + "transformQuat.d.ts", + "gl-vec4-tests.ts" + ] +} diff --git a/types/gl-vec4/tslint.json b/types/gl-vec4/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/gl-vec4/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/google-apps-script/google-apps-script.base.d.ts b/types/google-apps-script/google-apps-script.base.d.ts index 9f7153a6bb..5c2a8d9155 100644 --- a/types/google-apps-script/google-apps-script.base.d.ts +++ b/types/google-apps-script/google-apps-script.base.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -284,7 +284,9 @@ declare namespace GoogleAppsScript { * // A simple INFO log message, using sprintf() formatting. * console.info('Timing the %s function (%d arguments)', 'myFunction', 1); * - * // Log a JSON object at a DEBUG level. Writes the stringified object to the log. + * // Log a JSON object at a DEBUG level. If the object contains a property called "message", + * // that is used as the summary in the log viewer, otherwise a stringified version of + * // the object is used as the summary. * var parameters = { * isValid: true, * content: 'some string', diff --git a/types/google-apps-script/google-apps-script.data-studio.d.ts b/types/google-apps-script/google-apps-script.data-studio.d.ts index 332dff6dbc..c86bd39447 100644 --- a/types/google-apps-script/google-apps-script.data-studio.d.ts +++ b/types/google-apps-script/google-apps-script.data-studio.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -127,6 +127,7 @@ declare namespace GoogleAppsScript { getFormula(): string; getGroup(): string; getId(): string; + getIsReaggregatable(): boolean; getName(): string; getType(): FieldType; isDefault(): boolean; @@ -139,6 +140,7 @@ declare namespace GoogleAppsScript { setGroup(group: string): Field; setId(id: string): Field; setIsHidden(isHidden: boolean): Field; + setIsReaggregatable(isReaggregatable: boolean): Field; setName(name: string): Field; setType(type: FieldType): Field; } diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index d8dc3bc4d0..ba28d9719c 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-23 +// Type definitions for Google Apps Script 2019-02-27 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -49,6 +49,35 @@ declare namespace GoogleAppsScript { */ export enum BandingTheme { LIGHT_GREY, CYAN, GREEN, YELLOW, ORANGE, BLUE, TEAL, GREY, BROWN, LIGHT_GREEN, INDIGO, PINK } + /** + * Access the existing BigQuery data source specification. To create a new data source + * specification, use SpreadsheetApp.newDataSourceSpec(). + */ + export interface BigQueryDataSourceSpec { + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getProjectId(): string; + getRawQuery(): string; + getType(): DataSourceType; + } + + /** + * The builder for BigQueryDataSourceSpecBuilder. + */ + export interface BigQueryDataSourceSpecBuilder { + build(): DataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getProjectId(): string; + getRawQuery(): string; + getType(): DataSourceType; + removeAllParameters(): BigQueryDataSourceSpecBuilder; + removeParameter(parameterName: string): BigQueryDataSourceSpecBuilder; + setParameterFromCell(parameterName: string, sourceCell: string): BigQueryDataSourceSpecBuilder; + setProjectId(projectId: string): BigQueryDataSourceSpecBuilder; + setRawQuery(rawQuery: string): BigQueryDataSourceSpecBuilder; + } + /** * Access boolean conditions in ConditionalFormatRules. Each * conditional format rule may contain a single boolean condition. The boolean condition itself @@ -167,6 +196,154 @@ declare namespace GoogleAppsScript { */ export enum CopyPasteType { PASTE_NORMAL, PASTE_NO_BORDERS, PASTE_FORMAT, PASTE_FORMULA, PASTE_DATA_VALIDATION, PASTE_VALUES, PASTE_CONDITIONAL_FORMATTING, PASTE_COLUMN_WIDTHS } + /** + * An enumeration of data execution error codes. + */ + export enum DataExecutionErrorCode { DATA_EXECUTION_ERROR_CODE_UNSUPPORTED, NONE, TIME_OUT, TOO_MANY_ROWS, TOO_MANY_CELLS, ENGINE, PARAMETER_INVALID, UNSUPPORTED_DATA_TYPE, DUPLICATE_COLUMN_NAMES, INTERRUPTED, OTHER, TOO_MANY_CHARS_PER_CELL } + + /** + * An enumeration of data execution states. + */ + export enum DataExecutionState { DATA_EXECUTION_STATE_UNSUPPORTED, RUNNING, SUCCESS, ERROR, NOT_STARTED } + + /** + * The data execution status. + */ + export interface DataExecutionStatus { + getErrorCode(): DataExecutionErrorCode; + getErrorMessage(): string; + getExecutionState(): DataExecutionState; + getLastRefreshedTime(): Date; + isTruncated(): boolean; + } + + /** + * Access and modify existing data source. To create a data source table with new data source, see + * DataSourceTable. + */ + export interface DataSource { + getSpec(): DataSourceSpec; + updateSpec(spec: DataSourceSpec): DataSource; + } + + /** + * Access existing data source parameters. + */ + export interface DataSourceParameter { + getName(): string; + getSourceCell(): string; + getType(): DataSourceParameterType; + } + + /** + * An enumeration of data source parameter types. + */ + export enum DataSourceParameterType { DATA_SOURCE_PARAMETER_TYPE_UNSUPPORTED, CELL } + + /** + * Access the general settings of an existing data source spec. To access data source spec for + * certain type, use as...() method. To create a new data source spec, use SpreadsheetApp.newDataSourceSpec(). + * + * This example shows how to get information from a BigQuery data source spec. + * + * var dataSourceTable = + * SpreadsheetApp.getActive().getSheetByName("Data Sheet 1").getDataSourceTables()[0]; + * var spec = dataSourceTable.getDataSource().getSpec(); + * if (spec.getType() == SpreadsheetApp.DataSourceType.BIGQUERY) { + * var bqSpec = spec.asBigQuery(); + * Logger.log("Project ID: %s\n", bqSpec.getProjectId()); + * Logger.log("Raw query string: %s\n", bqSpec.getRawQuery()); + * } + */ + export interface DataSourceSpec { + asBigQuery(): BigQueryDataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getType(): DataSourceType; + } + + /** + * The builder for DataSourceSpec. To create a specification for certain type, use as...() method. To create a new builder, use SpreadsheetApp.newDataSourceSpec(). To use the specification, see DataSourceTable. + * + * This examples show how to build a BigQuery data source specification. + * + * var spec = SpreadsheetApp.newDataSourceSpec() + * .asBigQuery() + * .setProjectId('big_query_project') + * .setRawQuery('select @FIELD from table limit @LIMIT') + * .setParameterFromCell('FIELD', 'Sheet1!A1') + * .setParameterFromCell('LIMIT', 'namedRangeCell') + * .build(); + */ + export interface DataSourceSpecBuilder { + asBigQuery(): BigQueryDataSourceSpecBuilder; + build(): DataSourceSpec; + copy(): DataSourceSpecBuilder; + getParameters(): DataSourceParameter[]; + getType(): DataSourceType; + removeAllParameters(): DataSourceSpecBuilder; + removeParameter(parameterName: string): DataSourceSpecBuilder; + setParameterFromCell(parameterName: string, sourceCell: string): DataSourceSpecBuilder; + } + + /** + * Access and modify existing data source table. To create a new data source table on a new sheet, + * use Spreadsheet.insertSheetWithDataSourceTable(spec). + * + * This example shows how to create a new data source table. + * + * SpreadsheetApp.enableBigQueryExecution(); + * var spreadsheet = SpreadsheetApp.getActive(); + * var spec = SpreadsheetApp.newDataSourceSpec() + * .asBigQuery() + * .setProjectId('big_query_project') + * .setRawQuery('select @FIELD from table limit @LIMIT') + * .setParameterFromCell('FIELD', 'Sheet1!A1') + * .setParameterFromCell('LIMIT', 'namedRangeCell') + * .build(); + * // Starts data execution asynchronously. + * var dataSheet = spreadsheet.insertSheetWithDataSourceTable(spec); + * var dataSourceTable = dataSheet.getDataSourceTables()[0]; + * // waitForCompletion() blocks script execution until data execution completes. + * dataSourceTable.waitForCompletion(60); + * // Check status after execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + * + * This example shows how to edit a data source. + * + * SpreadsheetApp.enableBigQueryExecution(); + * var dataSheet = SpreadsheetApp.getActive().getSheetByName("Data Sheet 1"); + * var dataSourceTable = dataSheet.getDataSourceTables()[0]; + * var dataSource = dataSourceTable.getDataSource(); + * var newSpec = dataSource.getSpec() + * .copy() + * .asBigQuery() + * .setRawQuery('select name from table limit 2') + * .removeAllParameters() + * .build(); + * // Updates data source specification and starts data execution asynchronously. + * dataSource.updateSpec(newSpec); + * // Check status during execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + * // waitForCompletion() blocks script execution until data execution completes. + * dataSourceTable.waitForCompletion(60); + * // Check status after execution. + * Logger.log("Data execution state: %s.", dataSourceTable.getStatus().getExecutionState()); + */ + export interface DataSourceTable { + forceRefreshData(): DataSourceTable; + getDataSource(): DataSource; + getRange(): Range; + getStatus(): DataExecutionStatus; + refreshData(): DataSourceTable; + waitForCompletion(timeoutInSeconds: Integer): DataExecutionStatus; + } + + /** + * An enumeration of data source types. + */ + export enum DataSourceType { DATA_SOURCE_TYPE_UNSUPPORTED, BIGQUERY } + /** * Access data validation rules. To create a new rule, use SpreadsheetApp.newDataValidation() and DataValidationBuilder. You can use * Range.setDataValidation(rule) to set the validation rule for a range. @@ -1215,6 +1392,7 @@ declare namespace GoogleAppsScript { getBandings(): Banding[]; getCell(row: Integer, column: Integer): Range; getColumn(): Integer; + getDataSourceTables(): DataSourceTable[]; getDataSourceUrl(): string; getDataTable(): Charts.DataTable; getDataTable(firstRowIsHeader: boolean): Charts.DataTable; @@ -1493,6 +1671,7 @@ declare namespace GoogleAppsScript { getConditionalFormatRules(): ConditionalFormatRule[]; getCurrentCell(): Range; getDataRange(): Range; + getDataSourceTables(): DataSourceTable[]; getDeveloperMetadata(): DeveloperMetadata[]; getFilter(): Filter; getFormUrl(): string; @@ -1627,6 +1806,7 @@ declare namespace GoogleAppsScript { getColumnWidth(columnPosition: Integer): Integer; getCurrentCell(): Range; getDataRange(): Range; + getDataSourceTables(): DataSourceTable[]; getDeveloperMetadata(): DeveloperMetadata[]; getEditors(): Base.User[]; getFormUrl(): string; @@ -1677,6 +1857,7 @@ declare namespace GoogleAppsScript { insertSheet(sheetName: string, sheetIndex: Integer): Sheet; insertSheet(sheetName: string, sheetIndex: Integer, options: Object): Sheet; insertSheet(sheetName: string, options: Object): Sheet; + insertSheetWithDataSourceTable(spec: DataSourceSpec): Sheet; isColumnHiddenByUser(columnPosition: Integer): boolean; isRowHiddenByFilter(rowPosition: Integer): boolean; isRowHiddenByUser(rowPosition: Integer): boolean; @@ -1728,6 +1909,10 @@ declare namespace GoogleAppsScript { BooleanCriteria: typeof BooleanCriteria; BorderStyle: typeof BorderStyle; CopyPasteType: typeof CopyPasteType; + DataExecutionErrorCode: typeof DataExecutionErrorCode; + DataExecutionState: typeof DataExecutionState; + DataSourceParameterType: typeof DataSourceParameterType; + DataSourceType: typeof DataSourceType; DataValidationCriteria: typeof DataValidationCriteria; DeveloperMetadataLocationType: typeof DeveloperMetadataLocationType; DeveloperMetadataVisibility: typeof DeveloperMetadataVisibility; @@ -1744,6 +1929,8 @@ declare namespace GoogleAppsScript { WrapStrategy: typeof WrapStrategy; create(name: string): Spreadsheet; create(name: string, rows: Integer, columns: Integer): Spreadsheet; + enableAllDataSourcesExecution(): void; + enableBigQueryExecution(): void; flush(): void; getActive(): Spreadsheet; getActiveRange(): Range; @@ -1754,6 +1941,7 @@ declare namespace GoogleAppsScript { getSelection(): Selection; getUi(): Base.Ui; newConditionalFormatRule(): ConditionalFormatRuleBuilder; + newDataSourceSpec(): DataSourceSpecBuilder; newDataValidation(): DataValidationBuilder; newFilterCriteria(): FilterCriteriaBuilder; newRichTextValue(): RichTextValueBuilder; diff --git a/types/icepick/icepick-tests.ts b/types/icepick/icepick-tests.ts index 5458509d42..f1d536e78f 100644 --- a/types/icepick/icepick-tests.ts +++ b/types/icepick/icepick-tests.ts @@ -1,5 +1,4 @@ import i = require("icepick"); -import * as _ from 'underscore'; "use strict"; // so attempted modifications of frozen objects will throw errors @@ -146,15 +145,13 @@ class Foo {} { i.map(function(v) { return v * 2 }, [1, 2, 3]); // [2, 4, 6] - var removeEvens = _.partial(i.filter, function(v: number) { return v % 2; }); - - removeEvens([1, 2, 3]); // [1, 3] + i.filter(function(v: number) { return v % 2 === 0; }, [1, 2, 3]); // [1, 3] } { var arr = i.freeze([{ a: 1 }, { b: 2 }]); //ECMAScript 2015 - //arr.find(function(item) { return item.b != null; }); // {b: 2} + //arr.find(function(item) { return item.b != null; }); // {b: 2} } // chain(coll) - not defined diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index a4267d560e..b591ee3abb 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -41,7 +41,7 @@ export class JSDOM { * Behind the scenes, a jsdom Window is indeed a VM context. * To get access to this ability, use the runVMScript() method. */ - runVMScript(script: Script): void; + runVMScript(script: Script): any; reconfigure(settings: ReconfigureSettings): void; } diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 72ef7c117b..4e6a7abc26 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for massive 5.4 -// Project: https://github.com/dmfay/massive-js.git, https://dmfay.github.io/massive-js +// Project: https://massivejs.org, https://github.com/dmfay/massive-js.git, https://dmfay.github.io/massive-js // Definitions by: Pascal Birchler // Clarence Ho // Felix Faust diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index a3725382e4..79da3d5ead 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1,5 +1,6 @@ -// Type definitions for MongoDB v3.1 -// Project: https://github.com/mongodb/node-mongodb-native/tree/3.0.0 +// Type definitions for MongoDB 3.1 +// Project: https://github.com/mongodb/node-mongodb-native +// https://github.com/mongodb/node-mongodb-native/tree/3.1 // Definitions by: Federico Caselli // Alan Marcell // Jason Dreyzehner @@ -20,17 +21,18 @@ // Hector Ribes // Florian Richter // Erik Christensen +// Nick Zahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/ +// Documentation: https://mongodb.github.io/node-mongodb-native/3.1/api/ /// -/// import { ObjectID, Timestamp } from 'bson'; import { EventEmitter } from 'events'; import { Readable, Writable } from "stream"; +import { checkServerIdentity } from "tls"; export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; @@ -53,7 +55,7 @@ export class MongoClient extends EventEmitter { close(force?: boolean): Promise; close(force: boolean, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#db */ - db(dbName?: string, options?: MongoClientCommonOption): Db + db(dbName?: string, options?: MongoClientCommonOption): Db; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#isConnected */ isConnected(options?: MongoClientCommonOption): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#logout */ @@ -63,7 +65,7 @@ export class MongoClient extends EventEmitter { /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */ startSession(options?: SessionOptions): ClientSession; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#watch */ - watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; + watch(pipeline?: object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ withSession(operation: (session: ClientSession) => Promise): Promise; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ @@ -78,37 +80,36 @@ export interface ClientSession extends EventEmitter { id: any; /** * Aborts the currently active transaction in this session. - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; /** * Advances the operationTime for a ClientSession. - * @param {mongodb.Timestamp} operationTime */ advanceOperationTime(operamtionTime: Timestamp): void; /** * Commits the currently active transaction in this session. - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; /** * Ends this session on the server - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param cb Optional callback for completion of this operation */ endSession(cb?: MongoCallback): void; /** * Ends this session on the server - * @param {*} [options] Optional settings. Currently reserved for future use - * @param {MongoCallback} [cb] Optional callback for completion of this operation + * @param options Optional settings. Currently reserved for future use + * @param cb Optional callback for completion of this operation */ - endSession(options: any, cb?: MongoCallback): void + endSession(options: any, cb?: MongoCallback): void; /** * Used to determine if this session equals another * - * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @param session A class representing a client session on the server + * @returns Whether the sessions are equal */ equals(session: ClientSession): boolean; @@ -116,14 +117,12 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns Whether this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options - * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -150,19 +149,17 @@ interface WriteConcern { /** * requests acknowledgement that the write operation has * propagated to a specified number of mongod hosts - * @type {(number | 'majority' | string)} default 1 + * @default 1 */ w?: number | 'majority' | string; /** * requests acknowledgement from MongoDB that the write operation has * been written to the journal - * @type {boolean} default false + * @default false */ j?: boolean; /** * a time limit, in milliseconds, for the write concern - * @type {number} - * @memberof WriteConcern */ wtimeout?: number; } @@ -174,7 +171,7 @@ interface WriteConcern { export interface SessionOptions { /** * Whether causal consistency should be enabled on this session - * @type {boolean} default true + * @default true */ causalConsistency?: boolean; /** @@ -207,7 +204,7 @@ export interface MongoCallback { /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoError.html */ export class MongoError extends Error { constructor(message: string); - static create(options: Object): MongoError; + static create(options: object): MongoError; code?: number; /** * While not documented, the 'errmsg' prop is AFAIK the only way to find out @@ -248,13 +245,13 @@ export interface MongoClientOptions extends /** * Custom logger object */ - logger?: Object | log; + logger?: object | log; /** * Validate MongoClient passed in options for correctness. * Default: false */ - validateOptions?: Object; + validateOptions?: object; /** * The name of the application that created this MongoClient instance. @@ -314,7 +311,7 @@ export interface SSLOptions { /** * Default: true; Server identity checking during SSL */ - checkServerIdentity?: boolean | Function; + checkServerIdentity?: boolean | typeof checkServerIdentity; /** * Array of valid certificates either as Buffers or Strings */ @@ -358,7 +355,7 @@ export interface HighAvailabilityOptions { // See http://mongodb.github.io/node-mongodb-native/3.1/api/ReadPreference.html export class ReadPreference { - constructor(mode: string, tags: Object); + constructor(mode: string, tags: object); mode: string; tags: any; options: { @@ -417,18 +414,18 @@ export interface DbCreateOptions extends CommonOptions { /** * Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. */ - promoteValues?: Object; + promoteValues?: boolean; /** * Custom primary key factory to generate _id values (see Custom primary keys). */ - pkFactory?: Object; + pkFactory?: object; /** * ES6 compatible promise constructor */ - promiseLibrary?: Object; + promiseLibrary?: object; /** * https://docs.mongodb.com/manual/reference/read-concern/#read-concern - **/ + */ readConcern?: ReadConcern; /** * Sets a cap on how many operations the driver will buffer up before giving up on getting a @@ -485,7 +482,7 @@ export interface ServerOptions extends SSLOptions { /** * Default: true; */ - monitoring?: boolean + monitoring?: boolean; /** * Socket Options @@ -558,20 +555,20 @@ export class Db extends EventEmitter { collection(name: string, callback: MongoCallback>): Collection; collection(name: string, options: DbCollectionOptions, callback: MongoCallback>): Collection; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collections */ - collections(): Promise[]>; - collections(callback: MongoCallback[]>): void; + collections(): Promise>>; + collections(callback: MongoCallback>>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#command */ - command(command: Object, callback: MongoCallback): void; - command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; - command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; + command(command: object, callback: MongoCallback): void; + command(command: object, options?: { readPreference: ReadPreference | string, session?: ClientSession }): Promise; + command(command: object, options: { readPreference: ReadPreference | string, session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */ createCollection(name: string, callback: MongoCallback>): void; createCollection(name: string, options?: CollectionCreateOptions): Promise>; createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */ - createIndex(name: string, fieldOrSpec: string | Object, callback: MongoCallback): void; - createIndex(name: string, fieldOrSpec: string | Object, options?: IndexOptions): Promise; - createIndex(name: string, fieldOrSpec: string | Object, options: IndexOptions, callback: MongoCallback): void; + createIndex(name: string, fieldOrSpec: string | object, callback: MongoCallback): void; + createIndex(name: string, fieldOrSpec: string | object, options?: IndexOptions): Promise; + createIndex(name: string, fieldOrSpec: string | object, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#dropCollection */ dropCollection(name: string): Promise; dropCollection(name: string, callback: MongoCallback): void; @@ -579,15 +576,15 @@ export class Db extends EventEmitter { dropDatabase(): Promise; dropDatabase(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#executeDbAdminCommand */ - executeDbAdminCommand(command: Object, callback: MongoCallback): void; - executeDbAdminCommand(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - executeDbAdminCommand(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + executeDbAdminCommand(command: object, callback: MongoCallback): void; + executeDbAdminCommand(command: object, options?: { readPreference?: ReadPreference | string, session?: ClientSession }): Promise; + executeDbAdminCommand(command: object, options: { readPreference?: ReadPreference | string, session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#indexInformation */ indexInformation(name: string, callback: MongoCallback): void; indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; + listCollections(filter?: object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -626,7 +623,7 @@ export interface CommonOptions extends WriteConcern { export class Server extends EventEmitter { constructor(host: string, port: number, options?: ServerOptions); - connections(): Array; + connections(): any[]; } /** @@ -634,9 +631,9 @@ export class Server extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */ export class ReplSet extends EventEmitter { - constructor(servers: Array, options?: ReplSetOptions); + constructor(servers: Server[], options?: ReplSetOptions); - connections(): Array; + connections(): any[]; } /** @@ -644,9 +641,9 @@ export class ReplSet extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */ export class Mongos extends EventEmitter { - constructor(servers: Array, options?: MongosOptions); + constructor(servers: Server[], options?: MongosOptions); - connections(): Array; + connections(): any[]; } /** @@ -654,14 +651,14 @@ export class Mongos extends EventEmitter { * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */ export interface DbAddUserOptions extends CommonOptions { - customData?: Object; - roles?: Object[]; + customData?: object; + roles?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection */ export interface CollectionCreateOptions extends CommonOptions { raw?: boolean; - pkFactory?: Object; + pkFactory?: object; readPreference?: ReadPreference | string; serializeFunctions?: boolean; strict?: boolean; @@ -683,7 +680,7 @@ export interface CollectionCreateOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ export interface DbCollectionOptions extends CommonOptions { raw?: boolean; - pkFactory?: Object; + pkFactory?: object; readPreference?: ReadPreference | string; serializeFunctions?: boolean; strict?: boolean; @@ -736,7 +733,7 @@ export interface IndexOptions extends CommonOptions { */ partialFilterExpression?: any; collation?: CollationDocument; - default_language?: string + default_language?: string; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html */ @@ -749,9 +746,9 @@ export interface Admin { buildInfo(): Promise; buildInfo(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#command */ - command(command: Object, callback: MongoCallback): void; - command(command: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; - command(command: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; + command(command: object, callback: MongoCallback): void; + command(command: object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number }): Promise; + command(command: object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#listDatabases */ listDatabases(): Promise; listDatabases(callback: MongoCallback): void; @@ -773,20 +770,20 @@ export interface Admin { serverStatus(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#validateCollection */ validateCollection(collectionNme: string, callback: MongoCallback): void; - validateCollection(collectionNme: string, options?: Object): Promise; - validateCollection(collectionNme: string, options: Object, callback: MongoCallback): void; + validateCollection(collectionNme: string, options?: object): Promise; + validateCollection(collectionNme: string, options: object, callback: MongoCallback): void; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#addUser */ export interface AddUserOptions extends CommonOptions { fsync: boolean; - customData?: Object; - roles?: Object[] + customData?: object; + roles?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Admin.html#removeUser */ export interface FSyncOptions extends CommonOptions { - fsync?: boolean + fsync?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */ @@ -813,12 +810,12 @@ export interface Collection { hint: any; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */ aggregate(callback: MongoCallback>): AggregationCursor; - aggregate(pipeline: Object[], callback: MongoCallback>): AggregationCursor; - aggregate(pipeline?: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback>): AggregationCursor; + aggregate(pipeline: object[], callback: MongoCallback>): AggregationCursor; + aggregate(pipeline?: object[], options?: CollectionAggregationOptions, callback?: MongoCallback>): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#bulkWrite */ - bulkWrite(operations: Object[], callback: MongoCallback): void; - bulkWrite(operations: Object[], options?: CollectionBulkWriteOptions): Promise; - bulkWrite(operations: Object[], options: CollectionBulkWriteOptions, callback: MongoCallback): void; + bulkWrite(operations: object[], callback: MongoCallback): void; + bulkWrite(operations: object[], options?: CollectionBulkWriteOptions): Promise; + bulkWrite(operations: object[], options: CollectionBulkWriteOptions, callback: MongoCallback): void; /** * http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count * @deprecated Use countDocuments or estimatedDocumentCount @@ -879,12 +876,21 @@ export interface Collection { findOne(filter: FilterQuery, options: FindOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndDelete */ findOneAndDelete(filter: FilterQuery, callback: MongoCallback>): void; - findOneAndDelete(filter: FilterQuery, options?: { projection?: Object, sort?: Object, maxTimeMS?: number, session?: ClientSession }): Promise>; - findOneAndDelete(filter: FilterQuery, options: { projection?: Object, sort?: Object, maxTimeMS?: number, session?: ClientSession }, callback: MongoCallback>): void; + findOneAndDelete(filter: FilterQuery, options?: { projection?: object, sort?: object, maxTimeMS?: number, session?: ClientSession }): Promise>; + findOneAndDelete( + filter: FilterQuery, + options: { + projection?: object, + sort?: object, + maxTimeMS?: number, + session?: ClientSession + }, + callback: MongoCallback> + ): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ - findOneAndReplace(filter: FilterQuery, replacement: Object, callback: MongoCallback>): void; - findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; - findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; + findOneAndReplace(filter: FilterQuery, replacement: object, callback: MongoCallback>): void; + findOneAndReplace(filter: FilterQuery, replacement: object, options?: FindOneAndReplaceOption): Promise>; + findOneAndReplace(filter: FilterQuery, replacement: object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; @@ -893,14 +899,33 @@ export interface Collection { geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; geoHaystackSearch(x: number, y: number, options: GeoHaystackSearchOptions, callback: MongoCallback): void; - /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoNear */ - geoNear(x: number, y: number, callback: MongoCallback): void; - geoNear(x: number, y: number, options?: GeoNearOptions): Promise; - geoNear(x: number, y: number, options: GeoNearOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#group */ - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise; - group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group(keys: object | any[] | Function | Code, condition: object, initial: object, reduce: Function | Code, finalize: Function | Code, command: boolean, callback: MongoCallback): void; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group( + keys: object | any[] | Function | Code, + condition: object, + initial: object, + reduce: Function | Code, + finalize: Function | Code, + command: boolean, + options?: { readPreference?: ReadPreference | string, session?: ClientSession } + ): Promise; + /** @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. */ + group( + keys: object | any[] | Function | Code, + condition: object, + initial: object, + reduce: Function | Code, + finalize: Function | Code, + command: boolean, + options: { + readPreference?: ReadPreference | string, + session?: ClientSession + }, + callback: MongoCallback + ): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexes */ indexes(options?: { session: ClientSession }): Promise; indexes(callback: MongoCallback): void; @@ -939,28 +964,28 @@ export interface Collection { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#listIndexes */ listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */ - mapReduce(map: Function | string, reduce: Function | string, callback: MongoCallback): void; - mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise; - mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback): void; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, callback: MongoCallback): void; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, options?: MapReduceOptions): Promise; + mapReduce(map: CollectionMapFunction | string, reduce: CollectionReduceFunction | string, options: MapReduceOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#options */ options(options?: { session: ClientSession }): Promise; options(callback: MongoCallback): void; options(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */ - parallelCollectionScan(callback: MongoCallback[]>): void; - parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise[]>; - parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback[]>): void; + parallelCollectionScan(callback: MongoCallback>>): void; + parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise>>; + parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback>>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#reIndex */ reIndex(options?: { session: ClientSession }): Promise; reIndex(callback: MongoCallback): void; reIndex(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove */ /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, callback: MongoCallback): void; + remove(selector: object, callback: MongoCallback): void; /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, options?: CommonOptions & { single?: boolean }): Promise; + remove(selector: object, options?: CommonOptions & { single?: boolean }): Promise; /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ - remove(selector: Object, options?: CommonOptions & { single?: boolean }, callback?: MongoCallback): void; + remove(selector: object, options?: CommonOptions & { single?: boolean }, callback?: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#rename */ rename(newName: string, callback: MongoCallback>): void; rename(newName: string, options?: { dropTarget?: boolean, session?: ClientSession }): Promise>; @@ -996,21 +1021,21 @@ export interface Collection { updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions): Promise; updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */ - watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; + watch(pipeline?: object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; } export type Condition = { $eq?: T[P]; $gt?: T[P]; $gte?: T[P]; - $in?: T[P][]; + $in?: Array; $lt?: T[P]; $lte?: T[P]; $ne?: T[P]; - $nin?: T[P][]; - $and?: (FilterQuery | T[P])[]; - $or?: (FilterQuery | T[P])[]; - $not?: (FilterQuery | T[P])[] | T[P]; + $nin?: Array; + $and?: Array | T[P]>; + $or?: Array | T[P]>; + $not?: Array | T[P]> | T[P]; $expr?: any; $jsonSchema?: any; $mod?: [number, number]; @@ -1022,17 +1047,17 @@ export type Condition = { $caseSensitive?: boolean; $diacraticSensitive?: boolean; }; - $where?: Object; - $geoIntersects?: Object; - $geoWithin?: Object; - $near?: Object; - $nearSphere?: Object; - $elemMatch?: Object; + $where?: object; + $geoIntersects?: object; + $geoWithin?: object; + $near?: object; + $nearSphere?: object; + $elemMatch?: object; $size?: number; - $bitsAllClear?: Object; - $bitsAllSet?: Object; - $bitsAnyClear?: Object; - $bitsAnySet?: Object; + $bitsAllClear?: object; + $bitsAllSet?: object; + $bitsAnyClear?: object; + $bitsAnySet?: object; [key: string]: any; }; @@ -1047,12 +1072,12 @@ export type UpdateQuery = { $unset?: { [P in keyof T]?: '' } | { [key: string]: '' }; $rename?: { [key: string]: keyof T } | { [key: string]: string }; $currentDate?: { [P in keyof T]?: (true | { $type: 'date' | 'timestamp' }) } | { [key: string]: (true | { $type: 'date' | 'timestamp' }) }; - $addToSet?: Partial | { [key: string]: any }; + $addToSet?: { [P in keyof T]?: any } | { [key: string]: any }; $pop?: { [P in keyof T]?: -1 | 1 } | { [key: string]: -1 | 1 }; - $pull?: Partial | { [key: string]: Condition }; + $pull?: { [P in keyof T]?: any } | { [key: string]: any }; $push?: Partial | { [key: string]: any }; - $pushAll?: Partial | { [key: string]: Array }; - $each?: Partial | { [key: string]: Array }; + $pushAll?: Partial | { [key: string]: any[] }; + $each?: Partial | { [key: string]: any[] }; $bit?: { [P in keyof T]?: any } | { [key: string]: any }; }; @@ -1298,7 +1323,7 @@ export interface CollectionAggregationOptions { promoteValues?: boolean; promoteBuffers?: boolean; collation?: CollationDocument; - comment?: string + comment?: string; session?: ClientSession; } @@ -1383,7 +1408,7 @@ export interface DeleteWriteOpResultObject { ok?: number; //The total count of documents deleted. n?: number; - } + }; //The connection object used for the operation. connection?: any; //The number of documents deleted. @@ -1402,8 +1427,8 @@ export interface FindAndModifyWriteOpResultObject { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ export interface FindOneAndReplaceOption extends CommonOptions { - projection?: Object; - sort?: Object; + projection?: object; + sort?: object; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean; @@ -1411,34 +1436,21 @@ export interface FindOneAndReplaceOption extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ export interface FindOneAndUpdateOption extends FindOneAndReplaceOption { - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ export interface GeoHaystackSearchOptions { readPreference?: ReadPreference | string; maxDistance?: number; - search?: Object; + search?: object; limit?: number; session?: ClientSession; } -/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoNear */ -export interface GeoNearOptions { - readPreference?: ReadPreference | string; - num?: number; - minDistance?: number; - maxDistance?: number; - distanceMultiplier?: number; - query?: Object; - spherical?: boolean; - uniqueDocs?: boolean; - includeLocs?: boolean; -} - /** http://mongodb.github.io/node-mongodb-native/3.1/api/Code.html */ export class Code { - constructor(code: string | Function, scope?: Object) + constructor(code: string | Function, scope?: object) code: string | Function; scope: any; } @@ -1451,9 +1463,9 @@ export interface OrderedBulkOperation { execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#find */ - find(selector: Object): FindOperatorsOrdered; + find(selector: object): FindOperatorsOrdered; /** http://mongodb.github.io/node-mongodb-native/3.1/api/OrderedBulkOperation.html#insert */ - insert(doc: Object): OrderedBulkOperation; + insert(doc: object): OrderedBulkOperation; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/BulkWriteResult.html */ @@ -1465,15 +1477,15 @@ export interface BulkWriteResult { nModified: number; nRemoved: number; - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; + getInsertedIds(): object[]; + getLastOp(): object; + getRawResponse(): object; + getUpsertedIdAt(index: number): object; + getUpsertedIds(): object[]; getWriteConcernError(): WriteConcernError; getWriteErrorAt(index: number): WriteError; getWriteErrorCount(): number; - getWriteErrors(): Array; + getWriteErrors(): object[]; hasWriteErrors(): boolean; } @@ -1499,9 +1511,9 @@ export interface WriteConcernError { export interface FindOperatorsOrdered { delete(): OrderedBulkOperation; deleteOne(): OrderedBulkOperation; - replaceOne(doc: Object): OrderedBulkOperation; - update(doc: Object): OrderedBulkOperation; - updateOne(doc: Object): OrderedBulkOperation; + replaceOne(doc: object): OrderedBulkOperation; + update(doc: object): OrderedBulkOperation; + updateOne(doc: object): OrderedBulkOperation; upsert(): FindOperatorsOrdered; } @@ -1514,9 +1526,9 @@ export interface UnorderedBulkOperation { execute(options?: FSyncOptions): Promise; execute(options: FSyncOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#find */ - find(selector: Object): FindOperatorsUnordered; + find(selector: object): FindOperatorsUnordered; /** http://mongodb.github.io/node-mongodb-native/3.1/api/UnorderedBulkOperation.html#insert */ - insert(doc: Object): UnorderedBulkOperation; + insert(doc: object): UnorderedBulkOperation; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/FindOperatorsUnordered.html */ @@ -1524,23 +1536,23 @@ export interface FindOperatorsUnordered { length: number; remove(): UnorderedBulkOperation; removeOne(): UnorderedBulkOperation; - replaceOne(doc: Object): UnorderedBulkOperation; - update(doc: Object): UnorderedBulkOperation; - updateOne(doc: Object): UnorderedBulkOperation; + replaceOne(doc: object): UnorderedBulkOperation; + update(doc: object): UnorderedBulkOperation; + updateOne(doc: object): UnorderedBulkOperation; upsert(): FindOperatorsUnordered; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOne */ export interface FindOneOptions { limit?: number; - sort?: Array | Object; - projection?: Object; + sort?: any[] | object; + projection?: object; /** * @deprecated Use options.projection instead */ - fields?: Object; + fields?: object; skip?: number; - hint?: Object; + hint?: object; explain?: boolean; snapshot?: boolean; timeout?: boolean; @@ -1566,10 +1578,10 @@ export interface FindOneOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertWriteOpResult */ export interface InsertWriteOpResult { insertedCount: number; - ops: Array; + ops: any[]; insertedIds: { [key: number]: ObjectID }; connection: any; - result: { ok: number, n: number } + result: { ok: number, n: number }; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */ @@ -1581,16 +1593,16 @@ export interface CollectionInsertOneOptions extends CommonOptions { //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; //Allow driver to bypass schema validation in MongoDB 3.2 or higher. - bypassDocumentValidation?: boolean + bypassDocumentValidation?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult */ export interface InsertOneWriteOpResult { insertedCount: number; - ops: Array; + ops: any[]; insertedId: ObjectID; connection: any; - result: { ok: number, n: number } + result: { ok: number, n: number }; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */ @@ -1610,13 +1622,13 @@ export interface ReplaceOneOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ export interface UpdateOneOptions extends ReplaceOneOptions { - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ export interface UpdateManyOptions extends CommonOptions { upsert?: boolean; - arrayFilters?: Object[]; + arrayFilters?: object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */ @@ -1631,34 +1643,38 @@ export interface UpdateWriteOpResult { /** https://github.com/mongodb/node-mongodb-native/blob/2.2/lib/collection.js#L957 */ export interface ReplaceWriteOpResult extends UpdateWriteOpResult { - ops: Array + ops: any[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */ export interface MapReduceOptions { readPreference?: ReadPreference | string; - out?: Object; - query?: Object; - sort?: Object; + out?: object; + query?: object; + sort?: object; limit?: number; keeptemp?: boolean; finalize?: Function | string; - scope?: Object; + scope?: object; jsMode?: boolean; verbose?: boolean; bypassDocumentValidation?: boolean; session?: ClientSession; } +export type CollectionMapFunction = () => void; + +export type CollectionReduceFunction = (key: string, values: any) => any; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~WriteOpResult */ export interface WriteOpResult { - ops: Array; + ops: any[]; connection: any; result: any; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#~resultCallback */ -export type CursorResult = any | void | boolean; +export type CursorResult = object | null | boolean; type Default = any; @@ -1693,7 +1709,7 @@ export class Cursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#filter */ - filter(filter: Object): Cursor; + filter(filter: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#forEach */ forEach(iterator: IteratorCallback, callback: EndCallback): void; forEach(iterator: IteratorCallback): Promise; @@ -1701,7 +1717,7 @@ export class Cursor extends Readable { hasNext(): Promise; hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#hint */ - hint(hint: Object): Cursor; + hint(hint: string | object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#limit */ @@ -1713,7 +1729,7 @@ export class Cursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxAwaitTimeMS */ maxAwaitTimeMS(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxScan */ - maxScan(maxScan: Object): Cursor; + maxScan(maxScan: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#maxTimeMS */ maxTimeMS(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#min */ @@ -1722,27 +1738,27 @@ export class Cursor extends Readable { next(): Promise; next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#project */ - project(value: Object): Cursor; + project(value: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#next */ - returnKey(returnKey: Object): Cursor; + returnKey(returnKey: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#rewind */ rewind(): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setCursorOption */ - setCursorOption(field: string, value: Object): Cursor; + setCursorOption(field: string, value: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#setReadPreference */ setReadPreference(readPreference: string | ReadPreference): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#showRecordId */ - showRecordId(showRecordId: Object): Cursor; + showRecordId(showRecordId: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#skip */ skip(value: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#snapshot */ - snapshot(snapshot: Object): Cursor; + snapshot(snapshot: object): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#sort */ - sort(keyOrList: string | Object[] | Object, direction?: number): Cursor; + sort(keyOrList: string | object[] | object, direction?: number): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#stream */ - stream(options?: { transform?: Function }): Cursor; + stream(options?: { transform?: (document: T) => any }): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#toArray */ toArray(): Promise; toArray(callback: MongoCallback): void; @@ -1770,7 +1786,7 @@ export interface EndCallback { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#~resultCallback */ -export type AggregationCursorResult = any | void; +export type AggregationCursorResult = object | null; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html */ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#batchSize */ @@ -1786,9 +1802,9 @@ export class AggregationCursor extends Readable { explain(): Promise; explain(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#geoNear */ - geoNear(document: Object): AggregationCursor; + geoNear(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#group */ - group(document: Object): AggregationCursor; + group(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#hasNext */ hasNext(): Promise; hasNext(callback: MongoCallback): void; @@ -1797,7 +1813,7 @@ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#limit */ limit(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#match */ - match(document: Object): AggregationCursor; + match(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#maxTimeMS */ maxTimeMS(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#next */ @@ -1806,17 +1822,17 @@ export class AggregationCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#out */ out(destination: string): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#project */ - project(document: Object): AggregationCursor; + project(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#redact */ - redact(document: Object): AggregationCursor; + redact(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#rewind */ rewind(): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#setEncoding */ skip(value: number): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#sort */ - sort(document: Object): AggregationCursor; + sort(document: object): AggregationCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/AggregationCursor.html#toArray */ toArray(): Promise; toArray(callback: MongoCallback): void; @@ -1827,7 +1843,7 @@ export class AggregationCursor extends Readable { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ -export type CommandCursorResult = any | void; +export type CommandCursorResult = object | null; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ @@ -1871,7 +1887,7 @@ export class GridFSBucket { /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#drop */ drop(callback?: GridFSBucketErrorCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#find */ - find(filter?: Object, options?: GridFSBucketFindOptions): Cursor; + find(filter?: object, options?: GridFSBucketFindOptions): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStream */ openDownloadStream(id: ObjectID, options?: { start: number, end: number }): GridFSBucketReadStream; /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openDownloadStreamByName */ @@ -1888,8 +1904,8 @@ export class GridFSBucket { export interface GridFSBucketOptions { bucketName?: string; chunkSizeBytes?: number; - writeConcern?: Object; - ReadPreference?: Object; + writeConcern?: object; + ReadPreference?: object; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#~errorCallback */ @@ -1904,29 +1920,29 @@ export interface GridFSBucketFindOptions { maxTimeMS?: number; noCursorTimeout?: boolean; skip?: number; - sort?: Object; + sort?: object; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucket.html#openUploadStream */ export interface GridFSBucketOpenUploadStreamOptions { - chunkSizeBytes?: number, - metadata?: Object, - contentType?: string, - aliases?: Array + chunkSizeBytes?: number; + metadata?: object; + contentType?: string; + aliases?: string[]; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */ export class GridFSBucketReadStream extends Readable { id: ObjectID; - constructor(chunks: Collection, files: Collection, readPreference: Object, filter: Object, options?: GridFSBucketReadStreamOptions); + constructor(chunks: Collection, files: Collection, readPreference: object, filter: object, options?: GridFSBucketReadStreamOptions); } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketReadStream.html */ export interface GridFSBucketReadStreamOptions { - sort?: number, - skip?: number, - start?: number, - end?: number + sort?: number; + skip?: number; + start?: number; + end?: number; } /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */ @@ -1939,33 +1955,33 @@ export class GridFSBucketWriteStream extends Writable { export interface GridFSBucketWriteStreamOptions { /** * Custom file id for the GridFS file. - **/ - id?: GridFSBucketWriteStreamId, + */ + id?: GridFSBucketWriteStreamId; /** * The chunk size to use, in bytes */ - chunkSizeBytes?: number, + chunkSizeBytes?: number; /** * The write concern */ - w?: number, + w?: number; /** * The write concern timeout */ - wtimeout?: number, + wtimeout?: number; /** * The journal write concern */ - j?: number + j?: number; /** * Default false; If true, disables adding an md5 field to file data */ - disableMD5?: boolean + disableMD5?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html */ export class ChangeStream extends Readable { - constructor(changeDomain: Db | Collection, pipeline: Object[], options?: ChangeStreamOptions); + constructor(changeDomain: Db | Collection, pipeline: object[], options?: ChangeStreamOptions); /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#close */ close(): Promise; @@ -1983,94 +1999,94 @@ export class ChangeStream extends Readable { next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html#stream */ - stream(options?: { transform: Function }): Cursor; + stream(options?: { transform?: Function }): Cursor; } export interface ChangeStreamOptions { fullDocument?: string; maxAwaitTimeMS?: number; - resumeAfter?: Object; + resumeAfter?: object; batchSize?: number; collation?: CollationDocument; readPreference?: ReadPreference; } -type GridFSBucketWriteStreamId = string | number | Object | ObjectID; +type GridFSBucketWriteStreamId = string | number | object | ObjectID; export interface LoggerOptions { /** * Custom logger function */ - loggerLevel?: string + loggerLevel?: string; /** * Override default global log level. */ - logger?: log + logger?: log; } -export type log = (message?: string, state?: LoggerState) => void +export type log = (message?: string, state?: LoggerState) => void; export interface LoggerState { - type: string - message: string - className: string - pid: number - date: number + type: string; + message: string; + className: string; + pid: number; + date: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Logger.html */ export class Logger { - constructor(className: string, options?: LoggerOptions) + constructor(className: string, options?: LoggerOptions); /** * Log a message at the debug level */ - debug(message: string, state: LoggerState): void + debug(message: string, state: LoggerState): void; /** * Log a message at the warn level */ - warn(message: string, state: LoggerState): void + warn(message: string, state: LoggerState): void; /** * Log a message at the info level */ - info(message: string, state: LoggerState): void + info(message: string, state: LoggerState): void; /** * Log a message at the error level */ - error(message: string, state: LoggerState): void + error(message: string, state: LoggerState): void; /** * Is the logger set at info level */ - isInfo(): boolean + isInfo(): boolean; /** * Is the logger set at error level */ - isError(): boolean + isError(): boolean; /** * Is the logger set at error level */ - isWarn(): boolean + isWarn(): boolean; /** * Is the logger set at debug level */ - isDebug(): boolean + isDebug(): boolean; /** * Resets the logger to default settings, error and no filtered classes */ - static reset(): void + static reset(): void; /** * Get the current logger function */ - static currentLogger(): log + static currentLogger(): log; //Set the current logger function - static setCurrentLogger(log: log): void + static setCurrentLogger(log: log): void; /** * Set what classes to log. */ - static filter(type: string, values: string[]): void + static filter(type: string, values: string[]): void; /** * Set the current log level */ - static setLevel(level: string): void + static setLevel(level: string): void; } /** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index ea755a8eb1..d8eb287964 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -1,19 +1,19 @@ // Test source : https://github.com/mongodb/node-mongodb-native -import mongodb = require('mongodb'); -var MongoClient = mongodb.MongoClient; + +import { format } from 'util'; +import * as mongodb from 'mongodb'; const connectionString = 'mongodb://127.0.0.1:27017/test'; -var format = require('util').format; -let options: mongodb.MongoClientOptions = { +const options: mongodb.MongoClientOptions = { authSource: ' ', loggerLevel: 'debug', w: 1, wtimeout: 300, j: true, bufferMaxEntries: 1000, - readPreference: 'ReadPreference | string', - promoteValues: {}, + readPreference: true ? mongodb.ReadPreference.NEAREST : 'string', + promoteValues: true, pkFactory: {}, poolSize: 1, @@ -24,7 +24,7 @@ let options: mongodb.MongoClientOptions = { reconnectInterval: 123456, ssl: true, sslValidate: false, - checkServerIdentity: function () { }, + checkServerIdentity: true ? true : (host, cert) => { return undefined; }, sslCA: ['str'], sslCRL: ['str'], sslCert: new Buffer(999), @@ -34,58 +34,63 @@ let options: mongodb.MongoClientOptions = { useNewUrlParser: false, authMechanism: 'SCRAM-SHA-1', forceServerObjectId: false -} -MongoClient.connect(connectionString, options, function (err: mongodb.MongoError, client: mongodb.MongoClient) { +}; + +mongodb.MongoClient.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { if (err) throw err; const db = client.db('test'); - var collection = db.collection('test_insert'); - collection.insertOne({ a: 2 }, function (err: mongodb.MongoError, docs: any) { + const collection = db.collection('test_insert'); + collection.insertOne({ a: 2 }, (err: mongodb.MongoError, result) => { + result.insertedCount; // $ExpectType number + result.insertedId; // $ExpectType ObjectId + result.result.n; // $ExpectType number + result.result.ok; // $ExpectType number // Intentionally omitted type annotation from 'count'. // This way it requires a more accurate typedef which allows inferring that it's a number. - collection.countDocuments(function (err: mongodb.MongoError, count) { + collection.countDocuments((err: mongodb.MongoError, count) => { console.log(format("count = %s", count)); }); - collection.countDocuments().then(function (count: number) { + collection.countDocuments().then((count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, function (err: mongodb.MongoError, count: number) { + collection.countDocuments({ foo: 1 }, (err: mongodb.MongoError, count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }).then(function (count: number) { + collection.countDocuments({ foo: 1 }).then((count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, { limit: 10 }, function (err: mongodb.MongoError, count: number) { + collection.countDocuments({ foo: 1 }, { limit: 10 }, (err: mongodb.MongoError, count: number) => { console.log(format("count = %s", count)); }); - collection.countDocuments({ foo: 1 }, { limit: 10 }).then(function (count: number) { + collection.countDocuments({ foo: 1 }, { limit: 10 }).then((count: number) => { console.log(format("count = %s", count)); }); // Locate all the entries using find - collection.find({}).toArray(function (err: mongodb.MongoError, results: any) { + collection.find({}).toArray((err: mongodb.MongoError, results: any) => { console.dir(results); // Let's close the db client.close(); }); // Get some statistics - collection.stats(function (err: mongodb.MongoError, stats: any) { + collection.stats((err: mongodb.MongoError, stats: any) => { console.log(stats.count + " documents"); }); // - collection.stats().then(function (stats) { + collection.stats().then((stats) => { console.log(stats.wiredTiger.cache['bytes currently in the cache']); - }) + }); - collection.createIndex({}, { partialFilterExpression: { rating: { $exists: 1 } } }) + collection.createIndex({}, { partialFilterExpression: { rating: { $exists: 1 } } }); }); { @@ -95,10 +100,11 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError cursor = cursor.addQueryModifier('', true); cursor = cursor.batchSize(1); cursor = cursor.comment(''); - cursor = cursor.filter(1); - cursor = cursor.hint({}); + cursor = cursor.filter({a: 1}); + cursor = cursor.hint({ age: 1 }); + cursor = cursor.hint('age_1'); cursor = cursor.limit(1); - cursor = cursor.map(function (result) { }); + cursor = cursor.map((result) => {}); cursor = cursor.max(1); cursor = cursor.min(1); cursor = cursor.maxAwaitTimeMS(1); @@ -116,54 +122,64 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError } // Collection .findM() & .agggregate() generic tests { - let bag: { cost: number, color: string }; - type bag = typeof bag; - let cursor: mongodb.Cursor = collection.find({ color: 'black' }) - cursor.toArray(function (err, r) { r[0].cost }); - cursor.forEach(function (bag) { bag.color }, () => { }); - collection.findOne({ color: 'white' }).then(b => { let _b: bag = b; }) - collection.findOne({ color: 'white' }).then(b => { b.cost; }) + interface Bag { + cost: number; + color: string; + } + const cursor: mongodb.Cursor = collection.find({ color: 'black' }); + cursor.toArray((err, r) => { r[0].cost; }); + cursor.forEach((bag) => { bag.color; }, () => {}); + collection.findOne({ color: 'white' }).then(b => { const _b: Bag = b; }); + collection.findOne({ color: 'white' }).then(b => { b.cost; }); } { - let payment: { total: number }; - type payment = typeof payment; - let cursor: mongodb.AggregationCursor = collection.aggregate([{}]) + interface Payment { + total: number; + } + const cursor: mongodb.AggregationCursor = collection.aggregate([{}]); - collection.aggregate([{ $match: { bar: 1 } }, { $limit: 10 }]) - collection.aggregate([{ $match: { bar: 1 } }]).limit(10) - collection.aggregate([]).match({ bar: 1 }).limit(10) - collection.aggregate().match({ bar: 1 }).limit(10) + collection.aggregate([{ $match: { bar: 1 } }, { $limit: 10 }]); + collection.aggregate([{ $match: { bar: 1 } }]).limit(10); + collection.aggregate([]).match({ bar: 1 }).limit(10); + collection.aggregate().match({ bar: 1 }).limit(10); - collection.aggregate( + collection.aggregate( [{ $match: { bar: 1 } }], - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.limit(10) + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.limit(10); } - ) + ); - collection.aggregate( + collection.aggregate( [], - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.match({ bar: 1 }).limit(10) + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.match({ bar: 1 }).limit(10); } - ) + ); - collection.aggregate( - function (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) { - cursor.match({ bar: 1 }).limit(10) + collection.aggregate( + (err: mongodb.MongoError, cursor: mongodb.AggregationCursor) => { + cursor.match({ bar: 1 }).limit(10); } - ) + ); } // test for new typings { - type TestCollection = { + interface TestCollection { stringField: string; numberField?: number; - }; - let testCollection = db.collection('testCollection'); - testCollection.insertOne({stringField:'hola'}) - testCollection.insertMany([{stringField:'hola'},{stringField:'hola', numberField: 1}]) + fruitTags: string[]; + } + const testCollection = db.collection('testCollection'); + testCollection.insertOne({ + stringField: 'hola', + fruitTags: ['Strawberry'], + }); + testCollection.insertMany([ + { stringField: 'hola', fruitTags: ['Apple', 'Lemon'] }, + { stringField: 'hola', numberField: 1, fruitTags: [] }, + ]); testCollection.find({ numberField: { $and: [{ $gt: 0, $lt: 100 }] @@ -171,16 +187,28 @@ MongoClient.connect(connectionString, options, function (err: mongodb.MongoError }); const res: mongodb.Cursor = testCollection.find({ _id: 123 }); + + testCollection.updateOne( + { stringField: 'hola' }, + { + $addToSet: { + fruitTags: 'Orange', + }, + $pull: { + fruitTags: 'Lemon', + } + } + ); } -}) +}); -let testFunc = async () => { - let testClient: mongodb.MongoClient; - testClient = await mongodb.connect(connectionString); -}; +async function testFunc(): Promise { + const testClient: mongodb.MongoClient = await mongodb.connect(connectionString); + return testClient; +} -mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); -mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); +mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); +mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); // https://docs.mongodb.com/manual/core/transactions/ @@ -193,10 +221,10 @@ async function commitWithRetry(session: mongodb.ClientSession) { error.errorLabels && error.errorLabels.indexOf('UnknownTransactionCommitResult') < 0 ) { - console.log('UnknownTransactionCommitResult, retrying commit operation ...'); + console.log('UnknownTransactionCommitResult, retrying commit operation...'); await commitWithRetry(session); } else { - console.log('Error during commit ...'); + console.log('Error during commit...'); throw error; } } @@ -205,7 +233,8 @@ async function commitWithRetry(session: mongodb.ClientSession) { async function runTransactionWithRetry( txnFunc: (client: mongodb.MongoClient, session: mongodb.ClientSession) => Promise, client: mongodb.MongoClient, - session: mongodb.ClientSession) { + session: mongodb.ClientSession +) { try { await txnFunc(client, session); } catch (error) { @@ -256,31 +285,31 @@ async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: const session = client.startSession(); session.startTransaction(); try { - const opts = { session, returnOriginal: false }; - const A = await db.collection('Account'). + const opts = { session, returnOriginal: false }; + const A = await db.collection('Account'). findOneAndUpdate({ name: from }, { $inc: { balance: -amount } }, opts). then(res => res.value); - if (A.balance < 0) { - // If A would have negative balance, fail and abort the transaction - // `session.abortTransaction()` will undo the above `findOneAndUpdate()` - throw new Error('Insufficient funds: ' + (A.balance + amount)); - } + if (A.balance < 0) { + // If A would have negative balance, fail and abort the transaction + // `session.abortTransaction()` will undo the above `findOneAndUpdate()` + throw new Error('Insufficient funds: ' + (A.balance + amount)); + } - const B = await db.collection('Account'). - findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts). - then(res => res.value); + const B = await db.collection('Account') + .findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts) + .then(res => res.value); - await session.commitTransaction(); - session.endSession(); - return { from: A, to: B }; + await session.commitTransaction(); + session.endSession(); + return { from: A, to: B }; } catch (error) { - // If an error occurred, abort the whole transaction and - // undo any changes that might have happened - await session.abortTransaction(); - session.endSession(); - throw error; // Rethrow so calling function sees error + // If an error occurred, abort the whole transaction and + // undo any changes that might have happened + await session.abortTransaction(); + session.endSession(); + throw error; // Rethrow so calling function sees error } - } +} mongodb.connect(connectionString).then((client) => { client.startSession(); @@ -288,5 +317,3 @@ mongodb.connect(connectionString).then((client) => { runTransactionWithRetry(updateEmployeeInfo, client, session) ); }); - - diff --git a/types/mongodb/tslint.json b/types/mongodb/tslint.json index e3610fefae..f46f693285 100644 --- a/types/mongodb/tslint.json +++ b/types/mongodb/tslint.json @@ -2,79 +2,50 @@ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, - "array-type": false, "arrow-return-shorthand": false, - "ban-types": false, + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, "callable-types": false, "comment-format": false, - "dt-header": false, - "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, - "no-construct": false, "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, - "only-arrow-functions": false, "prefer-conditional-expression": false, - "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, - "trim-file": false, "triple-equals": false, - "typedef-whitespace": false, "unified-signatures": false, - "use-default-type-parameter": false, - "void-return": false, - "whitespace": false + "use-default-type-parameter": false } } diff --git a/types/node/buffer.d.ts b/types/node/buffer.d.ts index 1d618f2c4b..0fe668b17d 100644 --- a/types/node/buffer.d.ts +++ b/types/node/buffer.d.ts @@ -2,6 +2,10 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ new(size: number): Buffer; diff --git a/types/node/child_process.d.ts b/types/node/child_process.d.ts index 8e10d4e0c7..4e9c882e1b 100644 --- a/types/node/child_process.d.ts +++ b/types/node/child_process.d.ts @@ -1,20 +1,27 @@ declare module "child_process" { import * as events from "events"; - import * as stream from "stream"; import * as net from "net"; + import { Writable, Readable, Stream, Pipe } from "stream"; interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - killed: boolean; - pid: number; + stdin: Writable | null; + stdout: Readable | null; + stderr: Readable | null; + readonly channel?: Pipe | null; + readonly stdio: [ + Writable | null, // stdin + Readable | null, // stdout + Readable | null, // stderr + Readable | Writable | null | undefined, // extra + Readable | Writable | null | undefined // extra + ]; + readonly killed: boolean; + readonly pid: number; + readonly connected: boolean; kill(signal?: string): void; send(message: any, callback?: (error: Error) => void): boolean; send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; - connected: boolean; disconnect(): void; unref(): void; ref(): void; @@ -75,17 +82,20 @@ declare module "child_process" { keepOpen?: boolean; } - type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>; - interface CommonOptions { - /** - * @default true - */ - windowsHide?: boolean; + interface ProcessEnvOptions { uid?: number; gid?: number; cwd?: string; env?: NodeJS.ProcessEnv; + } + + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean; /** * @default 0 */ @@ -249,16 +259,12 @@ declare module "child_process" { ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; } - interface ForkOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; + interface ForkOptions extends ProcessEnvOptions { execPath?: string; execArgv?: string[]; silent?: boolean; stdio?: StdioOptions; windowsVerbatimArguments?: boolean; - uid?: number; - gid?: number; } function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; @@ -285,7 +291,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } function spawnSync(command: string): SpawnSyncReturns; function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index 27bf801c9f..99c6e236f5 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -169,17 +169,17 @@ declare module "crypto" { function createCipheriv( algorithm: CipherCCMTypes, key: CipherKey, - iv: BinaryLike, + iv: BinaryLike | null, options: CipherCCMOptions ): CipherCCM; function createCipheriv( algorithm: CipherGCMTypes, key: CipherKey, - iv: BinaryLike, + iv: BinaryLike | null, options?: CipherGCMOptions ): CipherGCM; function createCipheriv( - algorithm: string, key: CipherKey, iv: BinaryLike, options?: stream.TransformOptions + algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions ): Cipher; interface Cipher extends NodeJS.ReadWriteStream { @@ -213,16 +213,16 @@ declare module "crypto" { function createDecipheriv( algorithm: CipherCCMTypes, key: BinaryLike, - iv: BinaryLike, + iv: BinaryLike | null, options: CipherCCMOptions, ): DecipherCCM; function createDecipheriv( algorithm: CipherGCMTypes, key: BinaryLike, - iv: BinaryLike, + iv: BinaryLike | null, options?: CipherGCMOptions, ): DecipherGCM; - function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike, options?: stream.TransformOptions): Decipher; + function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; interface Decipher extends NodeJS.ReadWriteStream { update(data: Binary): Buffer; @@ -405,6 +405,42 @@ declare module "crypto" { passphrase: string; } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * @default 0x10001 + */ + publicExponent?: number; + } + + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { /** * Key size in bits @@ -467,46 +503,55 @@ declare module "crypto" { function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; namespace generateKeyPair { function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; } } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index dd4198a00e..210830f7e8 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -681,7 +681,7 @@ declare namespace NodeJS { type ExitListener = (code: number) => void; type RejectionHandledListener = (promise: Promise) => void; type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: any, promise: Promise) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; type WarningListener = (warning: Error) => void; type MessageListener = (message: any, sendHandle: any) => void; type SignalsListener = (signal: Signals) => void; @@ -721,6 +721,10 @@ declare namespace NodeJS { destroy(error?: Error): void; } + interface HRTime { + (time?: [number, number]): [number, number]; + } + interface Process extends EventEmitter { /** * Can also be a tty.WriteStream, not typed due to limitation.s @@ -795,12 +799,22 @@ declare namespace NodeJS { cpuUsage(previousValue?: CpuUsage): CpuUsage; nextTick(callback: Function, ...args: any[]): void; release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; /** * Can only be set if not in worker thread. */ umask(mask?: number): number; uptime(): number; - hrtime(time?: [number, number]): [number, number]; + hrtime: HRTime; domain: Domain; // Worker diff --git a/types/node/http.d.ts b/types/node/http.d.ts index b2557963a0..913cf98a37 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -147,8 +147,8 @@ declare module "http" { // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 // no args in writeContinue callback writeContinue(callback?: () => void): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; } // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 @@ -159,6 +159,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/http2.d.ts b/types/node/http2.d.ts index aecbca783f..48e35190d4 100644 --- a/types/node/http2.d.ts +++ b/types/node/http2.d.ts @@ -582,8 +582,8 @@ declare module "http2" { write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; writeContinue(): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): this; createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; addListener(event: string, listener: (...args: any[]) => void): this; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 39db1d52fa..41bfd02671 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for non-npm package Node.js 11.9 +// Type definitions for non-npm package Node.js 11.10 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -35,18 +35,19 @@ // Jeremie Rodriguez // Samuel Ainsworth // Kyle Uehlein +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides -// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.1, so the older definitions will be found here. +// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides +// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.2, so the older definitions will be found here. // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// @@ -54,6 +55,9 @@ // TypeScript 2.1-specific augmentations: // Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be sued without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json interface MapConstructor { } interface WeakMapConstructor { } interface SetConstructor { } @@ -72,8 +76,9 @@ interface SymbolConstructor { readonly asyncIterator: symbol; } declare var Symbol: SymbolConstructor; -declare class SharedArrayBuffer { - constructor(byteSize: number); +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { readonly byteLength: number; slice(begin?: number, end?: number): SharedArrayBuffer; } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 089ca86307..900a8fa21a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -8,24 +8,18 @@ import * as util from "util"; import * as tls from "tls"; import * as http from "http"; import * as https from "https"; -import * as net from "net"; import * as querystring from "querystring"; import * as path from "path"; -import * as childProcess from "child_process"; import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; import * as string_decoder from "string_decoder"; -import * as stream from "stream"; import * as timers from "timers"; -import * as repl from "repl"; 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 * as perf_hooks from "perf_hooks"; import * as trace_events from "trace_events"; import Module = require("module"); @@ -563,468 +557,6 @@ import Module = require("module"); } } -//////////////////////////////////////////////////// -/// Stream tests : http://nodejs.org/api/stream.html -//////////////////////////////////////////////////// - -// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options -function stream_readable_pipe_test() { - const rs = fs.createReadStream(Buffer.from('file.txt')); - const r = fs.createReadStream('file.txt'); - const z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); - const w = fs.createWriteStream('file.txt.gz'); - - assert(typeof z.bytesRead === 'number'); - assert(typeof r.bytesRead === 'number'); - assert(typeof r.path === 'string'); - assert(rs.path instanceof Buffer); - - r.pipe(z).pipe(w); - - z.flush(); - r.close(); - z.close(); - rs.close(); -} - -// helpers -const compressMe = new Buffer("some data"); -const compressMeString = "compress me!"; - -zlib.deflate(compressMe, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); -zlib.deflate( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflate( - result, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -zlib.deflate(compressMeString, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); -zlib.deflate( - compressMeString, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflate( - result, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); -const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); - -zlib.deflateRaw(compressMe, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, result: Buffer) => result)); -zlib.deflateRaw( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflateRaw( - result, { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -zlib.deflateRaw(compressMeString, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, result: Buffer) => result)); -zlib.deflateRaw( - compressMeString, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result), -); -const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); -const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); - -zlib.gzip(compressMe, (err: Error | null, result: Buffer) => zlib.gunzip(result, (err: Error | null, result: Buffer) => result)); -zlib.gzip( - compressMe, - { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => zlib.gunzip( - result, { finishFlush: zlib.Z_SYNC_FLUSH }, - (err: Error | null, result: Buffer) => result - ) -); -const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); - -zlib.unzip(compressMe, (err: Error | null, result: Buffer) => result); -zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result); -const unzipped: Buffer = zlib.unzipSync(compressMe); - -// Simplified constructors -function simplified_stream_ctor_test() { - new stream.Readable({ - read(size) { - // $ExpectType Readable - this; - // $ExpectType number - size; - }, - destroy(error, cb) { - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - } - }); - - new stream.Writable({ - write(chunk, enc, cb) { - // $ExpectType Writable - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Writable - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Writable - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Writable - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - } - }); - - new stream.Duplex({ - read(size) { - // $ExpectType Duplex - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Duplex - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Duplex - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Duplex - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Duplex - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - readableObjectMode: true, - writableObjectMode: true - }); - - new stream.Transform({ - read(size) { - // $ExpectType Transform - this; - // $ExpectType number - size; - }, - write(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - writev(chunks, cb) { - // $ExpectType Transform - this; - // $ExpectType { chunk: any; encoding: string; }[] - chunks; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - destroy(error, cb) { - // $ExpectType Transform - this; - // $ExpectType Error | null - error; - // $ExpectType (error: Error | null) => void - cb; - }, - final(cb) { - // $ExpectType Transform - this; - // $ExpectType (error?: Error | null | undefined) => void - cb; - }, - transform(chunk, enc, cb) { - // $ExpectType Transform - this; - // $ExpectType any - chunk; - // $ExpectType string - enc; - // $ExpectType TransformCallback - cb; - }, - flush(cb) { - // $ExpectType TransformCallback - cb; - }, - allowHalfOpen: true, - readableObjectMode: true, - writableObjectMode: true - }); -} - -function streamPipelineFinished() { - const cancel = stream.finished(process.stdin, (err?: Error) => {}); - cancel(); - - stream.pipeline(process.stdin, process.stdout, (err?: Error) => {}); -} - -async function asyncStreamPipelineFinished() { - const finished = util.promisify(stream.finished); - await finished(process.stdin); - - const pipeline = util.promisify(stream.pipeline); - await pipeline(process.stdin, process.stdout); -} - -////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html /// -////////////////////////////////////////////////// - -{ - { - const ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - const blah = ctx.context; - - const connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - const tlsSocket = tls.connect(connOpts); - - const ciphers: string[] = tls.getCiphers(); - const curve: string = tls.DEFAULT_ECDH_CURVE; - } - - { - let _server = tls.createServer({}); - let _boolean: boolean; - const _func1 = (err: Error, resp: Buffer) => { }; - const _func2 = (err: Error, sessionData: any) => { }; - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - */ - - _server = _server.addListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.addListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.addListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - const _err: Error = new Error(); - const _tlsSocket: tls.TLSSocket = tls.connect(1); - const _any: any = 1; - const _func: Function = () => {}; - const _buffer: Buffer = Buffer.from('a'); - _boolean = _server.emit("tlsClientError", _err, _tlsSocket); - _boolean = _server.emit("newSession", _any, _any, _func1); - _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); - _boolean = _server.emit("resumeSession", _any, _func2); - _boolean = _server.emit("secureConnection", _tlsSocket); - - _server = _server.on("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.on("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.on("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.on("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.once("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.once("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.once("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.once("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { - const _err: Error = err; - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { - const _sessionId: any = sessionId; - const _sessionData: any = sessionData; - const _func1 = callback; - }); - _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { - const _certificate: Buffer = certificate; - const _issuer: Buffer = issuer; - const _callback: Function = callback; - }); - _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { - const _sessionId: any = sessionId; - const _func2 = callback; - }); - _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { - const _tlsSocket: tls.TLSSocket = tlsSocket; - }); - - // close callback parameter is optional - _server = _server.close(); - - // close callback parameter doesn't specify any arguments, so any - // function is acceptable - _server = _server.close(() => { }); - _server = _server.close((...args: any[]) => { }); - } - - { - let _TLSSocket = tls.connect({ - }); - let _boolean: boolean; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); - - const _buffer: Buffer = Buffer.from(""); - _boolean = _TLSSocket.emit("OCSPResponse", _buffer); - _boolean = _TLSSocket.emit("secureConnect"); - - _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.on("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.once("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); - - _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { - const _response: Buffer = response; - }); - _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } -} - ////////////////////////////////////////////////////// /// Https tests : http://nodejs.org/api/https.html /// ////////////////////////////////////////////////////// @@ -1331,294 +863,6 @@ async function asyncStreamPipelineFinished() { const end2: string = decoder1.end(new Buffer('test')); } -////////////////////////////////////////////////////////////////////// -/// Child Process tests: https://nodejs.org/api/child_process.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - childProcess.exec("echo test"); - childProcess.exec("echo test", { windowsHide: true }); - childProcess.spawn("echo"); - childProcess.spawn("echo", { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true }); - childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); - childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); - childProcess.spawnSync("echo test"); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); - childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); - childProcess.spawnSync("echo test", {input: new Uint8Array([])}); - childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - { - childProcess.execFile("npm", () => {}); - childProcess.execFile("npm", { windowsHide: true }, () => {}); - childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); - } - - { - childProcess.execFileSync("echo test", {input: new Uint8Array([])}); - childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); - } - - async function testPromisify() { - const execFile = util.promisify(childProcess.execFile); - let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); - r = await execFile("npm", ["-v"]); - r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); - r = await execFile("npm", ["-v"], { encoding: 'buffer' }); - r = await execFile("npm", { encoding: 'utf-8' }); - r = await execFile("npm", { encoding: 'buffer' }); - } - - { - let _cp = childProcess.spawn('asd'); - const _socket: net.Socket = net.createConnection(1); - const _server: net.Server = net.createServer(); - let _boolean: boolean; - - _boolean = _cp.send(1); - _boolean = _cp.send('one'); - _boolean = _cp.send({ - type: 'test' - }); - - _boolean = _cp.send(1, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket); - _boolean = _cp.send('one', _socket); - _boolean = _cp.send({ - type: 'test' - }, _socket); - - _boolean = _cp.send(1, _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }); - - _boolean = _cp.send(1, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _socket, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server); - _boolean = _cp.send('one', _server); - _boolean = _cp.send({ - type: 'test' - }, _server); - - _boolean = _cp.send(1, _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, (error) => { - const _err: Error = error; - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }); - - _boolean = _cp.send(1, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send('one', _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - _boolean = _cp.send({ - type: 'test' - }, _server, { - keepOpen: true - }, (error) => { - const _err: Error = error; - }); - - _cp = _cp.addListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.addListener("disconnect", () => { }); - _cp = _cp.addListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.addListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.addListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _boolean = _cp.emit("close", () => { }); - _boolean = _cp.emit("disconnect", () => { }); - _boolean = _cp.emit("error", () => { }); - _boolean = _cp.emit("exit", () => { }); - _boolean = _cp.emit("message", () => { }); - - _cp = _cp.on("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.on("disconnect", () => { }); - _cp = _cp.on("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.on("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.on("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.once("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.once("disconnect", () => { }); - _cp = _cp.once("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.once("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.once("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependListener("disconnect", () => { }); - _cp = _cp.prependListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.prependListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - - _cp = _cp.prependOnceListener("close", (code, signal) => { - const _code: number = code; - const _signal: string = signal; - }); - _cp = _cp.prependOnceListener("disconnect", () => { }); - _cp = _cp.prependOnceListener("error", (err) => { - const _err: Error = err; - }); - _cp = _cp.prependOnceListener("exit", (code, signal) => { - const _code: number | null = code; - const _signal: string | null = signal; - }); - _cp = _cp.prependOnceListener("message", (message, sendHandle) => { - const _message: any = message; - const _sendHandle: net.Socket | net.Server = sendHandle; - }); - } - { - process.stdin.setEncoding('utf8'); - - process.stdin.on('readable', () => { - const chunk = process.stdin.read(); - if (chunk !== null) { - process.stdout.write(`data: ${chunk}`); - } - }); - - process.stdin.on('end', () => { - process.stdout.write('end'); - }); - - process.stdin.pipe(process.stdout); - - console.log(process.stdin.isTTY); - console.log(process.stdout.isTTY); - - console.log(process.stdin instanceof net.Socket); - console.log(process.stdout instanceof fs.ReadStream); - - const stdin: stream.Readable = process.stdin; - console.log(stdin instanceof net.Socket); - console.log(stdin instanceof fs.ReadStream); - - const stdout: stream.Writable = process.stdout; - console.log(stdout instanceof net.Socket); - console.log(stdout instanceof fs.WriteStream); - } -} - ////////////////////////////////////////////////////////////////////// /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// @@ -1967,7 +1211,7 @@ import * as p from "process"; process.prependListener("exit", (code: number) => { }); process.prependOnceListener("rejectionHandled", (promise: Promise) => { }); process.on("uncaughtException", (error: Error) => { }); - process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); + process.addListener("unhandledRejection", (reason: {} | null | undefined, promise: Promise) => { }); process.once("warning", (warning: Error) => { }); process.prependListener("message", (message: any, sendHandle: any) => { }); process.prependOnceListener("SIGBREAK", () => { }); @@ -2081,80 +1325,6 @@ import * as p from "process"; } } -///////////////////////////////////////////////////// -/// repl Tests : https://nodejs.org/api/repl.html /// -///////////////////////////////////////////////////// - -{ - { - let _server = repl.start(); - let _boolean: boolean; - const _ctx: vm.Context = {}; - - _server = _server.addListener("exit", () => { }); - _server = _server.addListener("reset", () => { }); - - _boolean = _server.emit("exit", () => { }); - _boolean = _server.emit("reset", _ctx); - - _server = _server.on("exit", () => { }); - _server = _server.on("reset", () => { }); - - _server = _server.once("exit", () => { }); - _server = _server.once("reset", () => { }); - - _server = _server.prependListener("exit", () => { }); - _server = _server.prependListener("reset", () => { }); - - _server = _server.prependOnceListener("exit", () => { }); - _server = _server.prependOnceListener("reset", () => { }); - - _server.outputStream.write("test"); - const line = _server.inputStream.read(); - - _server.clearBufferedCommand(); - _server.displayPrompt(); - _server.displayPrompt(true); - _server.defineCommand("cmd", function(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - }); - _server.defineCommand("cmd", { - help: "", - action(text) { - // $ExpectType string - text; - // $ExpectType REPLServer - this; - } - }); - - repl.start({ - eval() { - // $ExpectType REPLServer - this; - }, - writer() { - // $ExpectType REPLServer - this; - return ""; - } - }); - - function test() { - throw new repl.Recoverable(new Error("test")); - } - - _server.context['key0'] = 1; - _server.context['key1'] = ""; - _server.context['key2'] = true; - _server.context['key3'] = []; - _server.context['key4'] = {}; - } -} - /////////////////////////////////////////////////// /// DNS Tests : https://nodejs.org/api/dns.html /// /////////////////////////////////////////////////// @@ -2434,36 +1604,6 @@ import * as constants from 'constants'; v8.setFlagsFromString('--collect_maps'); } -//////////////////////////////////////////////////// -/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html -//////////////////////////////////////////////////// -{ - perf_hooks.performance.mark('start'); - ( - () => {} - )(); - perf_hooks.performance.mark('end'); - - const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; - const timeOrigin = perf_hooks.performance.timeOrigin; - - const performanceObserverCallback: perf_hooks.PerformanceObserverCallback = (list, obs) => { - const { - duration, - entryType, - name, - startTime, - } = list.getEntries()[0]; - obs.disconnect(); - perf_hooks.performance.clearFunctions(); - }; - const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); - obs.observe({ - entryTypes: ['function'], - buffered: true, - }); -} - //////////////////////////////////////////////////// /// AsyncHooks tests : https://nodejs.org/api/async_hooks.html //////////////////////////////////////////////////// @@ -2536,576 +1676,6 @@ import * as constants from 'constants'; } } -/////////////////////////////////////////////////////////// -/// HTTP/2 Tests /// -/////////////////////////////////////////////////////////// - -{ - // Headers & Settings - { - const headers: http2.OutgoingHttpHeaders = { - ':status': 200, - 'content-type': 'text-plain', - ABC: ['has', 'more', 'than', 'one', 'value'], - undef: undefined - }; - - const settings: http2.Settings = { - headerTableSize: 0, - enablePush: true, - initialWindowSize: 0, - maxFrameSize: 0, - maxConcurrentStreams: 0, - maxHeaderListSize: 0 - }; - } - - // Http2Session - { - const http2Session: http2.Http2Session = {} as any; - const ee: events.EventEmitter = http2Session; - - http2Session.on('close', () => {}); - http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); - http2Session.on('error', (err: Error) => {}); - http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); - http2Session.on('localSettings', (settings: http2.Settings) => {}); - http2Session.on('remoteSettings', (settings: http2.Settings) => {}); - http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('timeout', () => {}); - http2Session.on('ping', () => {}); - - http2Session.destroy(); - - const alpnProtocol: string | undefined = http2Session.alpnProtocol; - const destroyed: boolean | undefined = http2Session.destroyed; - const encrypted: boolean | undefined = http2Session.encrypted; - const originSet: string[] | undefined = http2Session.originSet; - const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; - let settings: http2.Settings = http2Session.localSettings; - const closed: boolean = http2Session.closed; - const connecting: boolean = http2Session.connecting; - settings = http2Session.remoteSettings; - - http2Session.ref(); - http2Session.unref(); - - const headers: http2.OutgoingHttpHeaders = {}; - const options: http2.ClientSessionRequestOptions = { - endStream: true, - exclusive: true, - parent: 0, - weight: 0, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} - }; - (http2Session as http2.ClientHttp2Session).request(); - (http2Session as http2.ClientHttp2Session).request(headers); - (http2Session as http2.ClientHttp2Session).request(headers, options); - - const stream: http2.Http2Stream = {} as any; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - - http2Session.setTimeout(100, () => {}); - http2Session.close(() => {}); - - const socket: net.Socket | tls.TLSSocket = http2Session.socket; - let state: http2.SessionState = http2Session.state; - state = { - effectiveLocalWindowSize: 0, - effectiveRecvDataLength: 0, - nextStreamID: 0, - localWindowSize: 0, - lastProcStreamID: 0, - remoteWindowSize: 0, - outboundQueueSize: 0, - deflateDynamicTableSize: 0, - inflateDynamicTableSize: 0 - }; - - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - http2Session.settings(settings); - - http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); - http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); - } - - // Http2Stream - { - const http2Stream: http2.Http2Stream = {} as any; - const duplex: stream.Duplex = http2Stream; - - http2Stream.on('aborted', () => {}); - http2Stream.on('error', (err: Error) => {}); - http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); - http2Stream.on('streamClosed', (code: number) => {}); - http2Stream.on('timeout', () => {}); - http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Stream.on('wantTrailers', () => {}); - - const aborted: boolean = http2Stream.aborted; - const closed: boolean = http2Stream.closed; - const destroyed: boolean = http2Stream.destroyed; - const pending: boolean = http2Stream.pending; - - http2Stream.priority({ - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - - const sesh: http2.Http2Session = http2Stream.session; - - http2Stream.setTimeout(100, () => {}); - - let state: http2.StreamState = http2Stream.state; - state = { - localWindowSize: 0, - state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, - sumDependencyWeight: 0, - weight: 0 - }; - - http2Stream.close(); - http2Stream.close(0); - http2Stream.close(0, () => {}); - http2Stream.close(undefined, () => {}); - - // ClientHttp2Stream - const clientHttp2Stream: http2.ClientHttp2Stream = {} as any; - clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); - clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders & http2.IncomingHttpStatusHeader, flags: number) => { - const s: number = headers[':status']!; - }); - - // ServerHttp2Stream - const serverHttp2Stream: http2.ServerHttp2Stream = {} as any; - const headers: http2.OutgoingHttpHeaders = {}; - - serverHttp2Stream.additionalHeaders(headers); - const headerSent: boolean = serverHttp2Stream.headersSent; - const pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); - - const options: http2.ServerStreamResponseOptions = { - endStream: true, - waitForTrailers: true, - }; - serverHttp2Stream.respond(); - serverHttp2Stream.respond(headers); - serverHttp2Stream.respond(headers, options); - - const options2: http2.ServerStreamFileResponseOptions = { - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFD(0); - serverHttp2Stream.respondWithFD(0, headers); - serverHttp2Stream.respondWithFD(0, headers, options2); - serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); - const options3: http2.ServerStreamFileResponseOptionsWithError = { - onError: (err: NodeJS.ErrnoException) => {}, - statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, - offset: 0, - length: 0 - }; - serverHttp2Stream.respondWithFile(''); - serverHttp2Stream.respondWithFile('', headers); - serverHttp2Stream.respondWithFile('', headers, options3); - serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); - } - - // Http2Server / Http2SecureServer - { - const http2Server: http2.Http2Server = http2.createServer(); - const http2SecureServer: http2.Http2SecureServer = http2.createSecureServer(); - const s1: net.Server = http2Server; - const s2: tls.Server = http2SecureServer; - [http2Server, http2SecureServer].forEach((server) => { - server.on('sessionError', (err: Error) => {}); - server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); - server.on('timeout', () => {}); - }); - - http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); - } - - // Public API (except constants) - { - let settings: http2.Settings = { - }; - const serverOptions: http2.ServerOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings, - allowHTTP1: true - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ''; - const onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { - // Http2ServerRequest - - const readable: stream.Readable = request; - let incomingHeaders: http2.IncomingHttpHeaders = request.headers; - incomingHeaders = request.trailers; - const httpVersion: string = request.httpVersion; - let method: string = request.method; - let rawHeaders: string[] = request.rawHeaders; - rawHeaders = request.rawTrailers; - let socket: net.Socket | tls.TLSSocket = request.socket; - let stream: http2.ServerHttp2Stream = request.stream; - const url: string = request.url; - - request.setTimeout(0, () => {}); - request.on('aborted', (hadError: boolean, code: number) => {}); - - // Http2ServerResponse - - let outgoingHeaders: http2.OutgoingHttpHeaders = { - }; - response.addTrailers(outgoingHeaders); - socket = response.connection; - const finished: boolean = response.finished; - response.sendDate = true; - response.statusCode = 200; - response.statusMessage = ''; - socket = response.socket; - stream = response.stream; - - method = response.getHeader(':method'); - const headers: string[] = response.getHeaderNames(); - outgoingHeaders = response.getHeaders(); - const hasMethod = response.hasHeader(':method'); - response.removeHeader(':method'); - response.setHeader(':method', 'GET'); - response.setHeader(':status', 200); - response.setHeader('some-list', ['', '']); - const headersSent: boolean = response.headersSent; - - response.setTimeout(0, () => {}); - response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); - - response.writeContinue(); - response.writeHead(200); - response.writeHead(200, outgoingHeaders); - response.writeHead(200, 'OK', outgoingHeaders); - response.writeHead(200, 'OK'); - response.write(''); - response.write('', (err: Error) => {}); - response.write('', 'utf8'); - response.write('', 'utf8', (err: Error) => {}); - response.write(Buffer.from([])); - response.write(Buffer.from([]), (err: Error) => {}); - response.write(Buffer.from([]), 'utf8'); - response.write(Buffer.from([]), 'utf8', (err: Error) => {}); - response.end(); - response.end(() => {}); - response.end(''); - response.end('', () => {}); - response.end('', 'utf8'); - response.end('', 'utf8', () => {}); - response.end(Buffer.from([])); - response.end(Buffer.from([]), () => {}); - response.end(Buffer.from([]), 'utf8'); - response.end(Buffer.from([]), 'utf8', () => {}); - - request.on('aborted', (hadError: boolean, code: number) => {}); - request.on('close', () => {}); - request.on('drain', () => {}); - request.on('error', (error: Error) => {}); - request.on('finish', () => {}); - }; - - let http2Server: http2.Http2Server; - let http2SecureServer: http2.Http2SecureServer; - - http2Server = http2.createServer(); - http2Server = http2.createServer(serverOptions); - http2Server = http2.createServer(onRequestHandler); - http2Server = http2.createServer(serverOptions, onRequestHandler); - - http2SecureServer = http2.createSecureServer(); - http2SecureServer = http2.createSecureServer(secureServerOptions); - http2SecureServer = http2.createSecureServer(onRequestHandler); - http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); - - const clientSessionOptions: http2.ClientSessionOptions = { - maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, - maxSendHeaderBlockLength: 0, - paddingStrategy: 0, - peerMaxConcurrentStreams: 0, - selectPadding: (frameLen: number, maxFrameLen: number) => 0, - settings - }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ''; - const onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; - - const serverHttp2Session: http2.ServerHttp2Session = {} as any; - - serverHttp2Session.altsvc('', ''); - serverHttp2Session.altsvc('', 0); - serverHttp2Session.altsvc('', new url.URL('')); - serverHttp2Session.altsvc('', { origin: '' }); - serverHttp2Session.altsvc('', { origin: 0 }); - serverHttp2Session.altsvc('', { origin: new url.URL('') }); - - let clientHttp2Session: http2.ClientHttp2Session; - - clientHttp2Session = http2.connect(''); - clientHttp2Session = http2.connect('', onConnectHandler); - clientHttp2Session = http2.connect('', clientSessionOptions); - clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); - clientHttp2Session = http2.connect('', secureClientSessionOptions); - clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); - clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); - - settings = http2.getDefaultSettings(); - settings = http2.getPackedSettings(settings); - settings = http2.getUnpackedSettings(Buffer.from([])); - settings = http2.getUnpackedSettings(Uint8Array.from([])); - } - - // constants - { - const constants = http2.constants; - let num: number; - let str: string; - num = constants.NGHTTP2_SESSION_SERVER; - num = constants.NGHTTP2_SESSION_CLIENT; - num = constants.NGHTTP2_STREAM_STATE_IDLE; - num = constants.NGHTTP2_STREAM_STATE_OPEN; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; - num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; - num = constants.NGHTTP2_STREAM_STATE_CLOSED; - num = constants.NGHTTP2_NO_ERROR; - num = constants.NGHTTP2_PROTOCOL_ERROR; - num = constants.NGHTTP2_INTERNAL_ERROR; - num = constants.NGHTTP2_FLOW_CONTROL_ERROR; - num = constants.NGHTTP2_SETTINGS_TIMEOUT; - num = constants.NGHTTP2_STREAM_CLOSED; - num = constants.NGHTTP2_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_REFUSED_STREAM; - num = constants.NGHTTP2_CANCEL; - num = constants.NGHTTP2_COMPRESSION_ERROR; - num = constants.NGHTTP2_CONNECT_ERROR; - num = constants.NGHTTP2_ENHANCE_YOUR_CALM; - num = constants.NGHTTP2_INADEQUATE_SECURITY; - num = constants.NGHTTP2_HTTP_1_1_REQUIRED; - num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; - num = constants.NGHTTP2_FLAG_NONE; - num = constants.NGHTTP2_FLAG_END_STREAM; - num = constants.NGHTTP2_FLAG_END_HEADERS; - num = constants.NGHTTP2_FLAG_ACK; - num = constants.NGHTTP2_FLAG_PADDED; - num = constants.NGHTTP2_FLAG_PRIORITY; - num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; - num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; - num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; - num = constants.MAX_MAX_FRAME_SIZE; - num = constants.MIN_MAX_FRAME_SIZE; - num = constants.MAX_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_DEFAULT_WEIGHT; - num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; - num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; - num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; - num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; - num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; - num = constants.PADDING_STRATEGY_NONE; - num = constants.PADDING_STRATEGY_MAX; - num = constants.PADDING_STRATEGY_CALLBACK; - num = constants.HTTP_STATUS_CONTINUE; - num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; - num = constants.HTTP_STATUS_PROCESSING; - num = constants.HTTP_STATUS_OK; - num = constants.HTTP_STATUS_CREATED; - num = constants.HTTP_STATUS_ACCEPTED; - num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; - num = constants.HTTP_STATUS_NO_CONTENT; - num = constants.HTTP_STATUS_RESET_CONTENT; - num = constants.HTTP_STATUS_PARTIAL_CONTENT; - num = constants.HTTP_STATUS_MULTI_STATUS; - num = constants.HTTP_STATUS_ALREADY_REPORTED; - num = constants.HTTP_STATUS_IM_USED; - num = constants.HTTP_STATUS_MULTIPLE_CHOICES; - num = constants.HTTP_STATUS_MOVED_PERMANENTLY; - num = constants.HTTP_STATUS_FOUND; - num = constants.HTTP_STATUS_SEE_OTHER; - num = constants.HTTP_STATUS_NOT_MODIFIED; - num = constants.HTTP_STATUS_USE_PROXY; - num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; - num = constants.HTTP_STATUS_PERMANENT_REDIRECT; - num = constants.HTTP_STATUS_BAD_REQUEST; - num = constants.HTTP_STATUS_UNAUTHORIZED; - num = constants.HTTP_STATUS_PAYMENT_REQUIRED; - num = constants.HTTP_STATUS_FORBIDDEN; - num = constants.HTTP_STATUS_NOT_FOUND; - num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; - num = constants.HTTP_STATUS_NOT_ACCEPTABLE; - num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; - num = constants.HTTP_STATUS_REQUEST_TIMEOUT; - num = constants.HTTP_STATUS_CONFLICT; - num = constants.HTTP_STATUS_GONE; - num = constants.HTTP_STATUS_LENGTH_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_FAILED; - num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; - num = constants.HTTP_STATUS_URI_TOO_LONG; - num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; - num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; - num = constants.HTTP_STATUS_EXPECTATION_FAILED; - num = constants.HTTP_STATUS_TEAPOT; - num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; - num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; - num = constants.HTTP_STATUS_LOCKED; - num = constants.HTTP_STATUS_FAILED_DEPENDENCY; - num = constants.HTTP_STATUS_UNORDERED_COLLECTION; - num = constants.HTTP_STATUS_UPGRADE_REQUIRED; - num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; - num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; - num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; - num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; - num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; - num = constants.HTTP_STATUS_NOT_IMPLEMENTED; - num = constants.HTTP_STATUS_BAD_GATEWAY; - num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; - num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; - num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; - num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; - num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; - num = constants.HTTP_STATUS_LOOP_DETECTED; - num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; - num = constants.HTTP_STATUS_NOT_EXTENDED; - num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; - str = constants.HTTP2_HEADER_STATUS; - str = constants.HTTP2_HEADER_METHOD; - str = constants.HTTP2_HEADER_AUTHORITY; - str = constants.HTTP2_HEADER_SCHEME; - str = constants.HTTP2_HEADER_PATH; - str = constants.HTTP2_HEADER_ACCEPT_CHARSET; - str = constants.HTTP2_HEADER_ACCEPT_ENCODING; - str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; - str = constants.HTTP2_HEADER_ACCEPT_RANGES; - str = constants.HTTP2_HEADER_ACCEPT; - str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; - str = constants.HTTP2_HEADER_AGE; - str = constants.HTTP2_HEADER_ALLOW; - str = constants.HTTP2_HEADER_AUTHORIZATION; - str = constants.HTTP2_HEADER_CACHE_CONTROL; - str = constants.HTTP2_HEADER_CONNECTION; - str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; - str = constants.HTTP2_HEADER_CONTENT_ENCODING; - str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; - str = constants.HTTP2_HEADER_CONTENT_LENGTH; - str = constants.HTTP2_HEADER_CONTENT_LOCATION; - str = constants.HTTP2_HEADER_CONTENT_MD5; - str = constants.HTTP2_HEADER_CONTENT_RANGE; - str = constants.HTTP2_HEADER_CONTENT_TYPE; - str = constants.HTTP2_HEADER_COOKIE; - str = constants.HTTP2_HEADER_DATE; - str = constants.HTTP2_HEADER_ETAG; - str = constants.HTTP2_HEADER_EXPECT; - str = constants.HTTP2_HEADER_EXPIRES; - str = constants.HTTP2_HEADER_FROM; - str = constants.HTTP2_HEADER_HOST; - str = constants.HTTP2_HEADER_IF_MATCH; - str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; - str = constants.HTTP2_HEADER_IF_NONE_MATCH; - str = constants.HTTP2_HEADER_IF_RANGE; - str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; - str = constants.HTTP2_HEADER_LAST_MODIFIED; - str = constants.HTTP2_HEADER_LINK; - str = constants.HTTP2_HEADER_LOCATION; - str = constants.HTTP2_HEADER_MAX_FORWARDS; - str = constants.HTTP2_HEADER_PREFER; - str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; - str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; - str = constants.HTTP2_HEADER_RANGE; - str = constants.HTTP2_HEADER_REFERER; - str = constants.HTTP2_HEADER_REFRESH; - str = constants.HTTP2_HEADER_RETRY_AFTER; - str = constants.HTTP2_HEADER_SERVER; - str = constants.HTTP2_HEADER_SET_COOKIE; - str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; - str = constants.HTTP2_HEADER_TRANSFER_ENCODING; - str = constants.HTTP2_HEADER_TE; - str = constants.HTTP2_HEADER_UPGRADE; - str = constants.HTTP2_HEADER_USER_AGENT; - str = constants.HTTP2_HEADER_VARY; - str = constants.HTTP2_HEADER_VIA; - str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; - str = constants.HTTP2_HEADER_HTTP2_SETTINGS; - str = constants.HTTP2_HEADER_KEEP_ALIVE; - str = constants.HTTP2_HEADER_PROXY_CONNECTION; - str = constants.HTTP2_METHOD_ACL; - str = constants.HTTP2_METHOD_BASELINE_CONTROL; - str = constants.HTTP2_METHOD_BIND; - str = constants.HTTP2_METHOD_CHECKIN; - str = constants.HTTP2_METHOD_CHECKOUT; - str = constants.HTTP2_METHOD_CONNECT; - str = constants.HTTP2_METHOD_COPY; - str = constants.HTTP2_METHOD_DELETE; - str = constants.HTTP2_METHOD_GET; - str = constants.HTTP2_METHOD_HEAD; - str = constants.HTTP2_METHOD_LABEL; - str = constants.HTTP2_METHOD_LINK; - str = constants.HTTP2_METHOD_LOCK; - str = constants.HTTP2_METHOD_MERGE; - str = constants.HTTP2_METHOD_MKACTIVITY; - str = constants.HTTP2_METHOD_MKCALENDAR; - str = constants.HTTP2_METHOD_MKCOL; - str = constants.HTTP2_METHOD_MKREDIRECTREF; - str = constants.HTTP2_METHOD_MKWORKSPACE; - str = constants.HTTP2_METHOD_MOVE; - str = constants.HTTP2_METHOD_OPTIONS; - str = constants.HTTP2_METHOD_ORDERPATCH; - str = constants.HTTP2_METHOD_PATCH; - str = constants.HTTP2_METHOD_POST; - str = constants.HTTP2_METHOD_PRI; - str = constants.HTTP2_METHOD_PROPFIND; - str = constants.HTTP2_METHOD_PROPPATCH; - str = constants.HTTP2_METHOD_PUT; - str = constants.HTTP2_METHOD_REBIND; - str = constants.HTTP2_METHOD_REPORT; - str = constants.HTTP2_METHOD_SEARCH; - str = constants.HTTP2_METHOD_TRACE; - str = constants.HTTP2_METHOD_UNBIND; - str = constants.HTTP2_METHOD_UNCHECKOUT; - str = constants.HTTP2_METHOD_UNLINK; - str = constants.HTTP2_METHOD_UNLOCK; - str = constants.HTTP2_METHOD_UPDATE; - str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; - str = constants.HTTP2_METHOD_VERSION_CONTROL; - } -} - /////////////////////////////////////////////////////////// /// Inspector Tests /// /////////////////////////////////////////////////////////// diff --git a/types/node/package.json b/types/node/package.json index c1f0c68752..cda6cc6dc8 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -2,10 +2,10 @@ "private": true, "types": "index", "typesVersions": { - ">=3.1.0-0": { + ">=3.2.0-0": { "*": [ - "ts3.1/*" + "ts3.2/*" ] } } -} \ No newline at end of file +} diff --git a/types/node/perf_hooks.d.ts b/types/node/perf_hooks.d.ts index 4f68895ce6..bf44d446eb 100644 --- a/types/node/perf_hooks.d.ts +++ b/types/node/perf_hooks.d.ts @@ -238,4 +238,67 @@ declare module "perf_hooks" { } const performance: Performance; + + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number; + } + + interface EventLoopDelayMonitor { + /** + * Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. + */ + enable(): boolean; + /** + * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. + */ + disable(): boolean; + + /** + * Resets the collected histogram data. + */ + reset(): void; + + /** + * Returns the value at the given percentile. + * @param percentile A percentile value between 1 and 100. + */ + percentile(percentile: number): number; + + /** + * A `Map` object detailing the accumulated percentile distribution. + */ + readonly percentiles: Map; + + /** + * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. + */ + readonly exceeds: number; + + /** + * The minimum recorded event loop delay. + */ + readonly min: number; + + /** + * The maximum recorded event loop delay. + */ + readonly max: number; + + /** + * The mean of the recorded event loop delays. + */ + readonly mean: number; + + /** + * The standard deviation of the recorded event loop delays. + */ + readonly stddev: number; + } + + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; } diff --git a/types/node/repl.d.ts b/types/node/repl.d.ts index cb5a3d037b..71f490443d 100644 --- a/types/node/repl.d.ts +++ b/types/node/repl.d.ts @@ -260,6 +260,16 @@ declare module "repl" { */ clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @param path The path to the history file + */ + setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; + /** * events.EventEmitter * 1. close - inherited from `readline.Interface` diff --git a/types/node/stream.d.ts b/types/node/stream.d.ts index 122ae563c7..2b0e1c72ac 100644 --- a/types/node/stream.d.ts +++ b/types/node/stream.d.ts @@ -288,6 +288,8 @@ declare module "stream" { ...streams: Array, ): Promise; } + + interface Pipe { } } export = internal; diff --git a/types/node/test/buffer.ts b/types/node/test/buffer.ts index 404b8b08c6..dd3329ba24 100644 --- a/types/node/test/buffer.ts +++ b/types/node/test/buffer.ts @@ -1,5 +1,5 @@ // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; const utf8Buffer = new Buffer('test'); const base64Buffer = new Buffer('', 'base64'); @@ -38,7 +38,8 @@ const result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); - const buf7: Buffer = Buffer.from(new SharedArrayBuffer(123)); + const sb: SharedArrayBuffer = {} as any; + const buf7: Buffer = Buffer.from(sb); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -208,3 +209,12 @@ b.fill('a').fill('b'); let res: Buffer = b.reverse(); res = b.subarray(1); } + +// Buffer module, transcode function +{ + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer +} diff --git a/types/node/test/child_process.ts b/types/node/test/child_process.ts new file mode 100644 index 0000000000..cf5b3e4656 --- /dev/null +++ b/types/node/test/child_process.ts @@ -0,0 +1,305 @@ +import * as childProcess from 'child_process'; +import * as net from 'net'; +import * as fs from 'fs'; +import * as assert from 'assert'; +import { promisify } from 'util'; +import { Writable, Readable, Pipe } from 'stream'; + +{ + childProcess.exec("echo test"); + childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); + childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); + childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); + childProcess.spawnSync("echo test", {input: new Uint8Array([])}); + childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); +} + +{ + childProcess.execFile("npm", () => {}); + childProcess.execFile("npm", { windowsHide: true }, () => {}); + childProcess.execFile("npm", ["-v"], () => {}); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); + childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); +} + +{ + childProcess.execFileSync("echo test", {input: new Uint8Array([])}); + childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); +} + +{ + const forked = childProcess.fork('./', ['asd'], { + windowsVerbatimArguments: true, + silent: false, + stdio: "inherit", + execPath: '', + execArgv: ['asda'] + }); + const ipc: Pipe = forked.channel!; +} + +async function testPromisify() { + const execFile = promisify(childProcess.execFile); + let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); + r = await execFile("npm", ["-v"]); + r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); + r = await execFile("npm", ["-v"], { encoding: 'buffer' }); + r = await execFile("npm", { encoding: 'utf-8' }); + r = await execFile("npm", { encoding: 'buffer' }); +} + +{ + let cp = childProcess.spawn('asd'); + const _socket: net.Socket = net.createConnection(1); + const _server: net.Server = net.createServer(); + let _boolean: boolean; + + _boolean = cp.send(1); + _boolean = cp.send('one'); + _boolean = cp.send({ + type: 'test' + }); + + _boolean = cp.send(1, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _socket); + _boolean = cp.send('one', _socket); + _boolean = cp.send({ + type: 'test' + }, _socket); + + _boolean = cp.send(1, _socket, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _socket, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _socket, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _socket, { + keepOpen: true + }); + _boolean = cp.send('one', _socket, { + keepOpen: true + }); + _boolean = cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }); + + _boolean = cp.send(1, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _server); + _boolean = cp.send('one', _server); + _boolean = cp.send({ + type: 'test' + }, _server); + + _boolean = cp.send(1, _server, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _server, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _server, (error) => { + const _err: Error = error; + }); + + _boolean = cp.send(1, _server, { + keepOpen: true + }); + _boolean = cp.send('one', _server, { + keepOpen: true + }); + _boolean = cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }); + + _boolean = cp.send(1, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send('one', _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + const stdin: Writable | null = cp.stdio[0]; + const stdout: Readable | null = cp.stdio[1]; + const stderr: Readable | null = cp.stdio[2]; + const fd4: Readable | Writable | null = cp.stdio[3]!; + const fd5: Readable | Writable | null = cp.stdio[4]!; + + cp = cp.addListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.addListener("disconnect", () => { }); + cp = cp.addListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.addListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.addListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _boolean = cp.emit("close", () => { }); + _boolean = cp.emit("disconnect", () => { }); + _boolean = cp.emit("error", () => { }); + _boolean = cp.emit("exit", () => { }); + _boolean = cp.emit("message", () => { }); + + cp = cp.on("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.on("disconnect", () => { }); + cp = cp.on("error", (err) => { + const _err: Error = err; + }); + cp = cp.on("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.on("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.once("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.once("disconnect", () => { }); + cp = cp.once("error", (err) => { + const _err: Error = err; + }); + cp = cp.once("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.once("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.prependListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.prependListener("disconnect", () => { }); + cp = cp.prependListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.prependListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.prependListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + cp = cp.prependOnceListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + cp = cp.prependOnceListener("disconnect", () => { }); + cp = cp.prependOnceListener("error", (err) => { + const _err: Error = err; + }); + cp = cp.prependOnceListener("exit", (code, signal) => { + const _code: number | null = code; + const _signal: string | null = signal; + }); + cp = cp.prependOnceListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); +} +{ + process.stdin.setEncoding('utf8'); + + process.stdin.on('readable', () => { + const chunk = process.stdin.read(); + if (chunk !== null) { + process.stdout.write(`data: ${chunk}`); + } + }); + + process.stdin.on('end', () => { + process.stdout.write('end'); + }); + + process.stdin.pipe(process.stdout); + + console.log(process.stdin.isTTY); + console.log(process.stdout.isTTY); + + console.log(process.stdin instanceof net.Socket); + console.log(process.stdout instanceof fs.ReadStream); + + const stdin: Readable = process.stdin; + console.log(stdin instanceof net.Socket); + console.log(stdin instanceof fs.ReadStream); + + const stdout: Writable = process.stdout; + console.log(stdout instanceof net.Socket); + console.log(stdout instanceof fs.WriteStream); +} diff --git a/types/node/test/crypto.ts b/types/node/test/crypto.ts index 8238567557..4dbe6e06ff 100644 --- a/types/node/test/crypto.ts +++ b/types/node/test/crypto.ts @@ -113,7 +113,7 @@ import { promisify } from 'util'; } { - const key = 'keykeykeykeykeykeykeykey'; + const key: string | null = 'keykeykeykeykeykeykeykey'; const nonce = crypto.randomBytes(12); const aad = Buffer.from('0123456789', 'hex'); diff --git a/types/node/test/http.ts b/types/node/test/http.ts index 6e4db63a2c..462722a8ff 100644 --- a/types/node/test/http.ts +++ b/types/node/test/http.ts @@ -65,7 +65,7 @@ import * as net from 'net'; res.addTrailers({ 'x-foo': 'bar' }); // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); + res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n').end(); res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); res.writeHead(200); @@ -112,6 +112,9 @@ import * as net from 'net'; // event req.on('data', () => { }); + + // path + const path: string = req.path; } { diff --git a/types/node/test/http2.ts b/types/node/test/http2.ts new file mode 100644 index 0000000000..0bada91a97 --- /dev/null +++ b/types/node/test/http2.ts @@ -0,0 +1,604 @@ +import { + Settings, + Http2Session, + Http2Stream, + ClientSessionRequestOptions, + ClientHttp2Session, + SessionState, + StreamState, + ClientHttp2Stream, + IncomingHttpStatusHeader, + ServerHttp2Stream, + ServerStreamResponseOptions, + ServerStreamFileResponseOptions, + StatOptions, + ServerStreamFileResponseOptionsWithError, + Http2Server, + Http2SecureServer, + createSecureServer, + Http2ServerRequest, + Http2ServerResponse, + SecureServerOptions, + ClientSessionOptions, + SecureClientSessionOptions, + ServerHttp2Session, + connect, + getDefaultSettings, + getPackedSettings, + getUnpackedSettings, + OutgoingHttpHeaders, + IncomingHttpHeaders, + createServer, + constants, + ServerOptions +} from "http2"; +import { EventEmitter } from "events"; +import { Stats } from "fs"; +import { Socket, Server } from "net"; +import { TLSSocket } from "tls"; +import { Duplex, Readable } from "stream"; +import { URL } from 'url'; + +// Headers & Settings +{ + const headers: OutgoingHttpHeaders = { + ':status': 200, + 'content-type': 'text-plain', + ABC: ['has', 'more', 'than', 'one', 'value'], + undef: undefined + }; + + const settings: Settings = { + headerTableSize: 0, + enablePush: true, + initialWindowSize: 0, + maxFrameSize: 0, + maxConcurrentStreams: 0, + maxHeaderListSize: 0 + }; +} + +// Http2Session +{ + const http2Session: Http2Session = {} as any; + const ee: EventEmitter = http2Session; + + http2Session.on('close', () => {}); + http2Session.on('connect', (session: Http2Session, socket: Socket) => {}); + http2Session.on('error', (err: Error) => {}); + http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); + http2Session.on('localSettings', (settings: Settings) => {}); + http2Session.on('remoteSettings', (settings: Settings) => {}); + http2Session.on('stream', (stream: Http2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + http2Session.on('timeout', () => {}); + http2Session.on('ping', () => {}); + + http2Session.destroy(); + + const alpnProtocol: string | undefined = http2Session.alpnProtocol; + const destroyed: boolean | undefined = http2Session.destroyed; + const encrypted: boolean | undefined = http2Session.encrypted; + const originSet: string[] | undefined = http2Session.originSet; + const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; + let settings: Settings = http2Session.localSettings; + const closed: boolean = http2Session.closed; + const connecting: boolean = http2Session.connecting; + settings = http2Session.remoteSettings; + + http2Session.ref(); + http2Session.unref(); + + const headers: OutgoingHttpHeaders = {}; + const options: ClientSessionRequestOptions = { + endStream: true, + exclusive: true, + parent: 0, + weight: 0, + getTrailers: (trailers: OutgoingHttpHeaders) => {} + }; + (http2Session as ClientHttp2Session).request(); + (http2Session as ClientHttp2Session).request(headers); + (http2Session as ClientHttp2Session).request(headers, options); + + const stream: Http2Stream = {} as any; + http2Session.rstStream(stream); + http2Session.rstStream(stream, 0); + + http2Session.setTimeout(100, () => {}); + http2Session.close(() => {}); + + const socket: Socket | TLSSocket = http2Session.socket; + let state: SessionState = http2Session.state; + state = { + effectiveLocalWindowSize: 0, + effectiveRecvDataLength: 0, + nextStreamID: 0, + localWindowSize: 0, + lastProcStreamID: 0, + remoteWindowSize: 0, + outboundQueueSize: 0, + deflateDynamicTableSize: 0, + inflateDynamicTableSize: 0 + }; + + http2Session.priority(stream, { + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + http2Session.settings(settings); + + http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); +} + +// Http2Stream +{ + const http2Stream: Http2Stream = {} as any; + const duplex: Duplex = http2Stream; + + http2Stream.on('aborted', () => {}); + http2Stream.on('error', (err: Error) => {}); + http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Stream.on('streamClosed', (code: number) => {}); + http2Stream.on('timeout', () => {}); + http2Stream.on('trailers', (trailers: IncomingHttpHeaders, flags: number) => {}); + http2Stream.on('wantTrailers', () => {}); + + const aborted: boolean = http2Stream.aborted; + const closed: boolean = http2Stream.closed; + const destroyed: boolean = http2Stream.destroyed; + const pending: boolean = http2Stream.pending; + + http2Stream.priority({ + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + const sesh: Http2Session = http2Stream.session; + + http2Stream.setTimeout(100, () => {}); + + let state: StreamState = http2Stream.state; + state = { + localWindowSize: 0, + state: 0, + streamLocalClose: 0, + streamRemoteClose: 0, + sumDependencyWeight: 0, + weight: 0 + }; + + http2Stream.close(); + http2Stream.close(0); + http2Stream.close(0, () => {}); + http2Stream.close(undefined, () => {}); + + // ClientHttp2Stream + const clientHttp2Stream: ClientHttp2Stream = {} as any; + clientHttp2Stream.on('headers', (headers: IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('push', (headers: IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('response', (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => { + const s: number = headers[':status']!; + }); + + // ServerHttp2Stream + const serverHttp2Stream: ServerHttp2Stream = {} as any; + const headers: OutgoingHttpHeaders = {}; + + serverHttp2Stream.additionalHeaders(headers); + const headerSent: boolean = serverHttp2Stream.headersSent; + const pushAllowed: boolean = serverHttp2Stream.pushAllowed; + serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => {}); + + const options: ServerStreamResponseOptions = { + endStream: true, + waitForTrailers: true, + }; + serverHttp2Stream.respond(); + serverHttp2Stream.respond(headers); + serverHttp2Stream.respond(headers, options); + + const options2: ServerStreamFileResponseOptions = { + statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, + getTrailers: (trailers: OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFD(0); + serverHttp2Stream.respondWithFD(0, headers); + serverHttp2Stream.respondWithFD(0, headers, options2); + serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); + const options3: ServerStreamFileResponseOptionsWithError = { + onError: (err: NodeJS.ErrnoException) => {}, + statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, + getTrailers: (trailers: OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFile(''); + serverHttp2Stream.respondWithFile('', headers); + serverHttp2Stream.respondWithFile('', headers, options3); + serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); +} + +// Http2Server / Http2SecureServer +{ + const http2Server: Http2Server = createServer(); + const http2SecureServer: Http2SecureServer = createSecureServer(); + const s1: Server = http2Server; + const s2: Server = http2SecureServer; + [http2Server, http2SecureServer].forEach((server) => { + server.on('sessionError', (err: Error) => {}); + server.on('checkContinue', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + server.on('stream', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); + server.on('request', (request: Http2ServerRequest, response: Http2ServerResponse) => {}); + server.on('timeout', () => {}); + }); + + http2SecureServer.on('unknownProtocol', (socket: TLSSocket) => {}); +} + +// Public API (except constants) +{ + let settings: Settings = { + }; + const serverOptions: ServerOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings, + allowHTTP1: true + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureServerOptions: SecureServerOptions = Object.assign({}, serverOptions); + secureServerOptions.ca = ''; + const onRequestHandler = (request: Http2ServerRequest, response: Http2ServerResponse) => { + // Http2ServerRequest + + const readable: Readable = request; + let incomingHeaders: IncomingHttpHeaders = request.headers; + incomingHeaders = request.trailers; + const httpVersion: string = request.httpVersion; + let method: string = request.method; + let rawHeaders: string[] = request.rawHeaders; + rawHeaders = request.rawTrailers; + let socket: Socket | TLSSocket = request.socket; + let stream: ServerHttp2Stream = request.stream; + const url: string = request.url; + + request.setTimeout(0, () => {}); + request.on('aborted', (hadError: boolean, code: number) => {}); + + // Http2ServerResponse + + let outgoingHeaders: OutgoingHttpHeaders = { + }; + response.addTrailers(outgoingHeaders); + socket = response.connection; + const finished: boolean = response.finished; + response.sendDate = true; + response.statusCode = 200; + response.statusMessage = ''; + socket = response.socket; + stream = response.stream; + + method = response.getHeader(':method'); + const headers: string[] = response.getHeaderNames(); + outgoingHeaders = response.getHeaders(); + const hasMethod = response.hasHeader(':method'); + response.removeHeader(':method'); + response.setHeader(':method', 'GET'); + response.setHeader(':status', 200); + response.setHeader('some-list', ['', '']); + const headersSent: boolean = response.headersSent; + + response.setTimeout(0, () => {}); + response.createPushResponse(outgoingHeaders, (err: Error | null, res: Http2ServerResponse) => {}); + + response.writeContinue(); + response.writeHead(200).end(); + response.writeHead(200, outgoingHeaders); + response.writeHead(200, 'OK', outgoingHeaders); + response.writeHead(200, 'OK'); + response.write(''); + response.write('', (err: Error) => {}); + response.write('', 'utf8'); + response.write('', 'utf8', (err: Error) => {}); + response.write(Buffer.from([])); + response.write(Buffer.from([]), (err: Error) => {}); + response.write(Buffer.from([]), 'utf8'); + response.write(Buffer.from([]), 'utf8', (err: Error) => {}); + response.end(); + response.end(() => {}); + response.end(''); + response.end('', () => {}); + response.end('', 'utf8'); + response.end('', 'utf8', () => {}); + response.end(Buffer.from([])); + response.end(Buffer.from([]), () => {}); + response.end(Buffer.from([]), 'utf8'); + response.end(Buffer.from([]), 'utf8', () => {}); + + request.on('aborted', (hadError: boolean, code: number) => {}); + request.on('close', () => {}); + request.on('drain', () => {}); + request.on('error', (error: Error) => {}); + request.on('finish', () => {}); + }; + + let http2Server: Http2Server; + let http2SecureServer: Http2SecureServer; + + http2Server = createServer(); + http2Server = createServer(serverOptions); + http2Server = createServer(onRequestHandler); + http2Server = createServer(serverOptions, onRequestHandler); + + http2SecureServer = createSecureServer(); + http2SecureServer = createSecureServer(secureServerOptions); + http2SecureServer = createSecureServer(onRequestHandler); + http2SecureServer = createSecureServer(secureServerOptions, onRequestHandler); + + const clientSessionOptions: ClientSessionOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureClientSessionOptions: SecureClientSessionOptions = Object.assign({}, clientSessionOptions); + secureClientSessionOptions.ca = ''; + const onConnectHandler = (session: Http2Session, socket: Socket) => {}; + + const serverHttp2Session: ServerHttp2Session = {} as any; + + serverHttp2Session.altsvc('', ''); + serverHttp2Session.altsvc('', 0); + serverHttp2Session.altsvc('', new URL('')); + serverHttp2Session.altsvc('', { origin: '' }); + serverHttp2Session.altsvc('', { origin: 0 }); + serverHttp2Session.altsvc('', { origin: new URL('') }); + + let clientHttp2Session: ClientHttp2Session; + + clientHttp2Session = connect(''); + clientHttp2Session = connect('', onConnectHandler); + clientHttp2Session = connect('', clientSessionOptions); + clientHttp2Session = connect('', clientSessionOptions, onConnectHandler); + clientHttp2Session = connect('', secureClientSessionOptions); + clientHttp2Session = connect('', secureClientSessionOptions, onConnectHandler); + clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); + + settings = getDefaultSettings(); + settings = getPackedSettings(settings); + settings = getUnpackedSettings(Buffer.from([])); + settings = getUnpackedSettings(Uint8Array.from([])); +} + +// constants +{ + const consts = constants; + let num: number; + let str: string; + num = consts.NGHTTP2_SESSION_SERVER; + num = consts.NGHTTP2_SESSION_CLIENT; + num = consts.NGHTTP2_STREAM_STATE_IDLE; + num = consts.NGHTTP2_STREAM_STATE_OPEN; + num = consts.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; + num = consts.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; + num = consts.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; + num = consts.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; + num = consts.NGHTTP2_STREAM_STATE_CLOSED; + num = consts.NGHTTP2_NO_ERROR; + num = consts.NGHTTP2_PROTOCOL_ERROR; + num = consts.NGHTTP2_INTERNAL_ERROR; + num = consts.NGHTTP2_FLOW_CONTROL_ERROR; + num = consts.NGHTTP2_SETTINGS_TIMEOUT; + num = consts.NGHTTP2_STREAM_CLOSED; + num = consts.NGHTTP2_FRAME_SIZE_ERROR; + num = consts.NGHTTP2_REFUSED_STREAM; + num = consts.NGHTTP2_CANCEL; + num = consts.NGHTTP2_COMPRESSION_ERROR; + num = consts.NGHTTP2_CONNECT_ERROR; + num = consts.NGHTTP2_ENHANCE_YOUR_CALM; + num = consts.NGHTTP2_INADEQUATE_SECURITY; + num = consts.NGHTTP2_HTTP_1_1_REQUIRED; + num = consts.NGHTTP2_ERR_FRAME_SIZE_ERROR; + num = consts.NGHTTP2_FLAG_NONE; + num = consts.NGHTTP2_FLAG_END_STREAM; + num = consts.NGHTTP2_FLAG_END_HEADERS; + num = consts.NGHTTP2_FLAG_ACK; + num = consts.NGHTTP2_FLAG_PADDED; + num = consts.NGHTTP2_FLAG_PRIORITY; + num = consts.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; + num = consts.DEFAULT_SETTINGS_ENABLE_PUSH; + num = consts.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; + num = consts.DEFAULT_SETTINGS_MAX_FRAME_SIZE; + num = consts.MAX_MAX_FRAME_SIZE; + num = consts.MIN_MAX_FRAME_SIZE; + num = consts.MAX_INITIAL_WINDOW_SIZE; + num = consts.NGHTTP2_DEFAULT_WEIGHT; + num = consts.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; + num = consts.NGHTTP2_SETTINGS_ENABLE_PUSH; + num = consts.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + num = consts.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + num = consts.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; + num = consts.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; + num = consts.PADDING_STRATEGY_NONE; + num = consts.PADDING_STRATEGY_MAX; + num = consts.PADDING_STRATEGY_CALLBACK; + num = consts.HTTP_STATUS_CONTINUE; + num = consts.HTTP_STATUS_SWITCHING_PROTOCOLS; + num = consts.HTTP_STATUS_PROCESSING; + num = consts.HTTP_STATUS_OK; + num = consts.HTTP_STATUS_CREATED; + num = consts.HTTP_STATUS_ACCEPTED; + num = consts.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; + num = consts.HTTP_STATUS_NO_CONTENT; + num = consts.HTTP_STATUS_RESET_CONTENT; + num = consts.HTTP_STATUS_PARTIAL_CONTENT; + num = consts.HTTP_STATUS_MULTI_STATUS; + num = consts.HTTP_STATUS_ALREADY_REPORTED; + num = consts.HTTP_STATUS_IM_USED; + num = consts.HTTP_STATUS_MULTIPLE_CHOICES; + num = consts.HTTP_STATUS_MOVED_PERMANENTLY; + num = consts.HTTP_STATUS_FOUND; + num = consts.HTTP_STATUS_SEE_OTHER; + num = consts.HTTP_STATUS_NOT_MODIFIED; + num = consts.HTTP_STATUS_USE_PROXY; + num = consts.HTTP_STATUS_TEMPORARY_REDIRECT; + num = consts.HTTP_STATUS_PERMANENT_REDIRECT; + num = consts.HTTP_STATUS_BAD_REQUEST; + num = consts.HTTP_STATUS_UNAUTHORIZED; + num = consts.HTTP_STATUS_PAYMENT_REQUIRED; + num = consts.HTTP_STATUS_FORBIDDEN; + num = consts.HTTP_STATUS_NOT_FOUND; + num = consts.HTTP_STATUS_METHOD_NOT_ALLOWED; + num = consts.HTTP_STATUS_NOT_ACCEPTABLE; + num = consts.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; + num = consts.HTTP_STATUS_REQUEST_TIMEOUT; + num = consts.HTTP_STATUS_CONFLICT; + num = consts.HTTP_STATUS_GONE; + num = consts.HTTP_STATUS_LENGTH_REQUIRED; + num = consts.HTTP_STATUS_PRECONDITION_FAILED; + num = consts.HTTP_STATUS_PAYLOAD_TOO_LARGE; + num = consts.HTTP_STATUS_URI_TOO_LONG; + num = consts.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; + num = consts.HTTP_STATUS_RANGE_NOT_SATISFIABLE; + num = consts.HTTP_STATUS_EXPECTATION_FAILED; + num = consts.HTTP_STATUS_TEAPOT; + num = consts.HTTP_STATUS_MISDIRECTED_REQUEST; + num = consts.HTTP_STATUS_UNPROCESSABLE_ENTITY; + num = consts.HTTP_STATUS_LOCKED; + num = consts.HTTP_STATUS_FAILED_DEPENDENCY; + num = consts.HTTP_STATUS_UNORDERED_COLLECTION; + num = consts.HTTP_STATUS_UPGRADE_REQUIRED; + num = consts.HTTP_STATUS_PRECONDITION_REQUIRED; + num = consts.HTTP_STATUS_TOO_MANY_REQUESTS; + num = consts.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; + num = consts.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; + num = consts.HTTP_STATUS_INTERNAL_SERVER_ERROR; + num = consts.HTTP_STATUS_NOT_IMPLEMENTED; + num = consts.HTTP_STATUS_BAD_GATEWAY; + num = consts.HTTP_STATUS_SERVICE_UNAVAILABLE; + num = consts.HTTP_STATUS_GATEWAY_TIMEOUT; + num = consts.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; + num = consts.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; + num = consts.HTTP_STATUS_INSUFFICIENT_STORAGE; + num = consts.HTTP_STATUS_LOOP_DETECTED; + num = consts.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; + num = consts.HTTP_STATUS_NOT_EXTENDED; + num = consts.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; + str = consts.HTTP2_HEADER_STATUS; + str = consts.HTTP2_HEADER_METHOD; + str = consts.HTTP2_HEADER_AUTHORITY; + str = consts.HTTP2_HEADER_SCHEME; + str = consts.HTTP2_HEADER_PATH; + str = consts.HTTP2_HEADER_ACCEPT_CHARSET; + str = consts.HTTP2_HEADER_ACCEPT_ENCODING; + str = consts.HTTP2_HEADER_ACCEPT_LANGUAGE; + str = consts.HTTP2_HEADER_ACCEPT_RANGES; + str = consts.HTTP2_HEADER_ACCEPT; + str = consts.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; + str = consts.HTTP2_HEADER_AGE; + str = consts.HTTP2_HEADER_ALLOW; + str = consts.HTTP2_HEADER_AUTHORIZATION; + str = consts.HTTP2_HEADER_CACHE_CONTROL; + str = consts.HTTP2_HEADER_CONNECTION; + str = consts.HTTP2_HEADER_CONTENT_DISPOSITION; + str = consts.HTTP2_HEADER_CONTENT_ENCODING; + str = consts.HTTP2_HEADER_CONTENT_LANGUAGE; + str = consts.HTTP2_HEADER_CONTENT_LENGTH; + str = consts.HTTP2_HEADER_CONTENT_LOCATION; + str = consts.HTTP2_HEADER_CONTENT_MD5; + str = consts.HTTP2_HEADER_CONTENT_RANGE; + str = consts.HTTP2_HEADER_CONTENT_TYPE; + str = consts.HTTP2_HEADER_COOKIE; + str = consts.HTTP2_HEADER_DATE; + str = consts.HTTP2_HEADER_ETAG; + str = consts.HTTP2_HEADER_EXPECT; + str = consts.HTTP2_HEADER_EXPIRES; + str = consts.HTTP2_HEADER_FROM; + str = consts.HTTP2_HEADER_HOST; + str = consts.HTTP2_HEADER_IF_MATCH; + str = consts.HTTP2_HEADER_IF_MODIFIED_SINCE; + str = consts.HTTP2_HEADER_IF_NONE_MATCH; + str = consts.HTTP2_HEADER_IF_RANGE; + str = consts.HTTP2_HEADER_IF_UNMODIFIED_SINCE; + str = consts.HTTP2_HEADER_LAST_MODIFIED; + str = consts.HTTP2_HEADER_LINK; + str = consts.HTTP2_HEADER_LOCATION; + str = consts.HTTP2_HEADER_MAX_FORWARDS; + str = consts.HTTP2_HEADER_PREFER; + str = consts.HTTP2_HEADER_PROXY_AUTHENTICATE; + str = consts.HTTP2_HEADER_PROXY_AUTHORIZATION; + str = consts.HTTP2_HEADER_RANGE; + str = consts.HTTP2_HEADER_REFERER; + str = consts.HTTP2_HEADER_REFRESH; + str = consts.HTTP2_HEADER_RETRY_AFTER; + str = consts.HTTP2_HEADER_SERVER; + str = consts.HTTP2_HEADER_SET_COOKIE; + str = consts.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; + str = consts.HTTP2_HEADER_TRANSFER_ENCODING; + str = consts.HTTP2_HEADER_TE; + str = consts.HTTP2_HEADER_UPGRADE; + str = consts.HTTP2_HEADER_USER_AGENT; + str = consts.HTTP2_HEADER_VARY; + str = consts.HTTP2_HEADER_VIA; + str = consts.HTTP2_HEADER_WWW_AUTHENTICATE; + str = consts.HTTP2_HEADER_HTTP2_SETTINGS; + str = consts.HTTP2_HEADER_KEEP_ALIVE; + str = consts.HTTP2_HEADER_PROXY_CONNECTION; + str = consts.HTTP2_METHOD_ACL; + str = consts.HTTP2_METHOD_BASELINE_CONTROL; + str = consts.HTTP2_METHOD_BIND; + str = consts.HTTP2_METHOD_CHECKIN; + str = consts.HTTP2_METHOD_CHECKOUT; + str = consts.HTTP2_METHOD_CONNECT; + str = consts.HTTP2_METHOD_COPY; + str = consts.HTTP2_METHOD_DELETE; + str = consts.HTTP2_METHOD_GET; + str = consts.HTTP2_METHOD_HEAD; + str = consts.HTTP2_METHOD_LABEL; + str = consts.HTTP2_METHOD_LINK; + str = consts.HTTP2_METHOD_LOCK; + str = consts.HTTP2_METHOD_MERGE; + str = consts.HTTP2_METHOD_MKACTIVITY; + str = consts.HTTP2_METHOD_MKCALENDAR; + str = consts.HTTP2_METHOD_MKCOL; + str = consts.HTTP2_METHOD_MKREDIRECTREF; + str = consts.HTTP2_METHOD_MKWORKSPACE; + str = consts.HTTP2_METHOD_MOVE; + str = consts.HTTP2_METHOD_OPTIONS; + str = consts.HTTP2_METHOD_ORDERPATCH; + str = consts.HTTP2_METHOD_PATCH; + str = consts.HTTP2_METHOD_POST; + str = consts.HTTP2_METHOD_PRI; + str = consts.HTTP2_METHOD_PROPFIND; + str = consts.HTTP2_METHOD_PROPPATCH; + str = consts.HTTP2_METHOD_PUT; + str = consts.HTTP2_METHOD_REBIND; + str = consts.HTTP2_METHOD_REPORT; + str = consts.HTTP2_METHOD_SEARCH; + str = consts.HTTP2_METHOD_TRACE; + str = consts.HTTP2_METHOD_UNBIND; + str = consts.HTTP2_METHOD_UNCHECKOUT; + str = consts.HTTP2_METHOD_UNLINK; + str = consts.HTTP2_METHOD_UNLOCK; + str = consts.HTTP2_METHOD_UPDATE; + str = consts.HTTP2_METHOD_UPDATEREDIRECTREF; + str = consts.HTTP2_METHOD_VERSION_CONTROL; +} diff --git a/types/node/test/perf_hooks.ts b/types/node/test/perf_hooks.ts new file mode 100644 index 0000000000..8d4c4e23d2 --- /dev/null +++ b/types/node/test/perf_hooks.ts @@ -0,0 +1,42 @@ +import { performance, monitorEventLoopDelay, PerformanceObserverCallback, PerformanceObserver } from 'perf_hooks'; + +performance.mark('start'); +( + () => {} +)(); +performance.mark('end'); + +const { duration } = performance.getEntriesByName('discover')[0]; +const timeOrigin = performance.timeOrigin; + +const performanceObserverCallback: PerformanceObserverCallback = (list, obs) => { + const { + duration, + entryType, + name, + startTime, + } = list.getEntries()[0]; + obs.disconnect(); + performance.clearFunctions(); +}; +const obs = new PerformanceObserver(performanceObserverCallback); +obs.observe({ + entryTypes: ['function'], + buffered: true, +}); + +const monitor = monitorEventLoopDelay({ + resolution: 42, +}); + +monitor.enable(); +monitor.reset(); +monitor.disable(); +const perc: number = monitor.percentile(99); +const perc2: number | undefined = monitor.percentiles.get(42); + +const min: number = monitor.min; +const max: number = monitor.max; +const mean: number = monitor.mean; +const stddev: number = monitor.stddev; +const exceeds: number = monitor.exceeds; diff --git a/types/node/test/repl.ts b/types/node/test/repl.ts new file mode 100644 index 0000000000..b536cd4dc1 --- /dev/null +++ b/types/node/test/repl.ts @@ -0,0 +1,73 @@ +import { start, Recoverable } from "repl"; +import { Context } from "vm"; + +{ + let server = start(); + let _boolean: boolean; + const _ctx: Context = {}; + + server.setupHistory('hurr/durr', (err, repl) => { + }); + + server = server.addListener("exit", () => { }); + server = server.addListener("reset", () => { }); + + _boolean = server.emit("exit", () => { }); + _boolean = server.emit("reset", _ctx); + + server = server.on("exit", () => { }); + server = server.on("reset", () => { }); + + server = server.once("exit", () => { }); + server = server.once("reset", () => { }); + + server = server.prependListener("exit", () => { }); + server = server.prependListener("reset", () => { }); + + server = server.prependOnceListener("exit", () => { }); + server = server.prependOnceListener("reset", () => { }); + + server.outputStream.write("test"); + const line = server.inputStream.read(); + + server.clearBufferedCommand(); + server.displayPrompt(); + server.displayPrompt(true); + server.defineCommand("cmd", function(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + }); + server.defineCommand("cmd", { + help: "", + action(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + } + }); + + start({ + eval() { + // $ExpectType REPLServer + this; + }, + writer() { + // $ExpectType REPLServer + this; + return ""; + } + }); + + function test() { + throw new Recoverable(new Error("test")); + } + + server.context['key0'] = 1; + server.context['key1'] = ""; + server.context['key2'] = true; + server.context['key3'] = []; + server.context['key4'] = {}; +} diff --git a/types/node/test/stream.ts b/types/node/test/stream.ts new file mode 100644 index 0000000000..6fd656e61c --- /dev/null +++ b/types/node/test/stream.ts @@ -0,0 +1,194 @@ +import { Readable, Writable, Transform, finished, pipeline, Duplex } from "stream"; +import { promisify } from "util"; +import { createReadStream, createWriteStream } from "fs"; +import { createGzip, constants } from "zlib"; +import { ok as assert } from 'assert'; + +// Simplified constructors +function simplified_stream_ctor_test() { + new Readable({ + read(size) { + // $ExpectType Readable + this; + // $ExpectType number + size; + }, + destroy(error, cb) { + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + } + }); + + new Writable({ + write(chunk, enc, cb) { + // $ExpectType Writable + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Writable + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Writable + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Writable + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + } + }); + + new Duplex({ + read(size) { + // $ExpectType Duplex + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Duplex + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Duplex + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Duplex + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Duplex + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + readableObjectMode: true, + writableObjectMode: true + }); + + new Transform({ + read(size) { + // $ExpectType Transform + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Transform + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Transform + this; + // $ExpectType Error | null + error; + // $ExpectType (error: Error | null) => void + cb; + }, + final(cb) { + // $ExpectType Transform + this; + // $ExpectType (error?: Error | null | undefined) => void + cb; + }, + transform(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType TransformCallback + cb; + }, + flush(cb) { + // $ExpectType TransformCallback + cb; + }, + allowHalfOpen: true, + readableObjectMode: true, + writableObjectMode: true + }); +} + +function streamPipelineFinished() { + const cancel = finished(process.stdin, (err?: Error) => {}); + cancel(); + + pipeline(process.stdin, process.stdout, (err?: Error) => {}); +} + +async function asyncStreamPipelineFinished() { + const fin = promisify(finished); + await fin(process.stdin); + + const pipe = promisify(pipeline); + await pipe(process.stdin, process.stdout); +} + +// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options +function stream_readable_pipe_test() { + const rs = createReadStream(Buffer.from('file.txt')); + const r = createReadStream('file.txt'); + const z = createGzip({ finishFlush: constants.Z_FINISH }); + const w = createWriteStream('file.txt.gz'); + + assert(typeof z.bytesRead === 'number'); + assert(typeof r.bytesRead === 'number'); + assert(typeof r.path === 'string'); + assert(rs.path instanceof Buffer); + + r.pipe(z).pipe(w); + + z.flush(); + r.close(); + z.close(); + rs.close(); +} diff --git a/types/node/test/tls.ts b/types/node/test/tls.ts new file mode 100644 index 0000000000..807e41393f --- /dev/null +++ b/types/node/test/tls.ts @@ -0,0 +1,206 @@ +import { createSecureContext, SecureContext, ConnectionOptions, connect, getCiphers, DEFAULT_ECDH_CURVE, createServer, TLSSocket } from "tls"; + +{ + const ctx: SecureContext = createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + const blah = ctx.context; + + const connOpts: ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + const tlsSocket = connect(connOpts); + + const ciphers: string[] = getCiphers(); + const curve: string = DEFAULT_ECDH_CURVE; +} + +{ + let _server = createServer({}); + let _boolean: boolean; + const _func1 = (err: Error, resp: Buffer) => { }; + const _func2 = (err: Error, sessionData: any) => { }; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + + _server = _server.addListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.addListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.addListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + const _err: Error = new Error(); + const _tlsSocket: TLSSocket = connect(1); + const _any: any = 1; + const _func: Function = () => {}; + const _buffer: Buffer = Buffer.from('a'); + _boolean = _server.emit("tlsClientError", _err, _tlsSocket); + _boolean = _server.emit("newSession", _any, _any, _func1); + _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); + _boolean = _server.emit("resumeSession", _any, _func2); + _boolean = _server.emit("secureConnection", _tlsSocket); + + _server = _server.on("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.on("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.on("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.on("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.once("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.once("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.once("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.once("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: TLSSocket = tlsSocket; + }); + _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { + const _tlsSocket: TLSSocket = tlsSocket; + }); + + // close callback parameter is optional + _server = _server.close(); + + // close callback parameter doesn't specify any arguments, so any + // function is acceptable + _server = _server.close(() => { }); + _server = _server.close((...args: any[]) => { }); +} + +{ + let socket = connect({ + }); + let _boolean: boolean; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + + socket = socket.addListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.addListener("secureConnect", () => { }); + + const _buffer: Buffer = Buffer.from(""); + _boolean = socket.emit("OCSPResponse", _buffer); + _boolean = socket.emit("secureConnect"); + + socket = socket.on("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.on("secureConnect", () => { }); + + socket = socket.once("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.once("secureConnect", () => { }); + + socket = socket.prependListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.prependListener("secureConnect", () => { }); + + socket = socket.prependOnceListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + socket = socket.prependOnceListener("secureConnect", () => { }); + + socket.once('session', (buff: Buffer) => {}); +} diff --git a/types/node/test/zlib.ts b/types/node/test/zlib.ts new file mode 100644 index 0000000000..d76803a919 --- /dev/null +++ b/types/node/test/zlib.ts @@ -0,0 +1,120 @@ +import { + deflate, + inflate, + inflateSync, + deflateSync, + deflateRaw, + inflateRaw, + inflateRawSync, + deflateRawSync, + gunzip, + gzip, + gunzipSync, + gzipSync, + unzip, + unzipSync, + constants, + createBrotliCompress, + BrotliOptions, + createBrotliDecompress, + BrotliCompress, + BrotliDecompress, + brotliCompress, + brotliDecompressSync, + brotliDecompress, +} from "zlib"; + +const compressMe = new Buffer("some data"); +const compressMeString = "compress me!"; + +// Deflate / Inflate + +deflate(compressMe, (err: Error | null, result: Buffer) => inflate(result, (err: Error | null, result: Buffer) => result)); +deflate( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflate( + result, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +deflate(compressMeString, (err: Error | null, result: Buffer) => inflate(result, (err: Error | null, result: Buffer) => result)); +deflate( + compressMeString, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflate( + result, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const inflated = inflateSync(deflateSync(compressMe)); +const inflatedString = inflateSync(deflateSync(compressMeString)); + +deflateRaw(compressMe, (err: Error | null, result: Buffer) => inflateRaw(result, (err: Error | null, result: Buffer) => result)); +deflateRaw( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflateRaw( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +deflateRaw(compressMeString, (err: Error | null, result: Buffer) => inflateRaw(result, (err: Error | null, result: Buffer) => result)); +deflateRaw( + compressMeString, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => inflateRaw(result, { finishFlush: constants.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result), +); +const inflatedRaw: Buffer = inflateRawSync(deflateRawSync(compressMe)); +const inflatedRawString: Buffer = inflateRawSync(deflateRawSync(compressMeString)); + +// gzip + +gzip(compressMe, (err: Error | null, result: Buffer) => gunzip(result, (err: Error | null, result: Buffer) => result)); +gzip( + compressMe, + { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => gunzip( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const gunzipped: Buffer = gunzipSync(gzipSync(compressMe)); + +unzip(compressMe, (err: Error | null, result: Buffer) => result); +unzip(compressMe, { finishFlush: constants.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result); +const unzipped: Buffer = unzipSync(compressMe); + +const bOpts: BrotliOptions = { + chunkSize: 123, + flush: 123123, + params: { + [constants.BROTLI_PARAM_LARGE_WINDOW]: true, + [constants.BROTLI_PARAM_NPOSTFIX]: 123, + }, + finishFlush: 123123, +}; + +// brotli + +let bC: BrotliCompress = createBrotliCompress(); +bC = createBrotliCompress(bOpts); +let bD: BrotliDecompress = createBrotliDecompress(); +bD = createBrotliDecompress(bOpts); +// gzip + +brotliCompress(compressMe, (err: Error | null, result: Buffer) => gunzip(result, (err: Error | null, result: Buffer) => result)); +brotliCompress( + compressMe, + { finishFlush: constants.BROTLI_OPERATION_FINISH }, + (err: Error | null, result: Buffer) => gunzip( + result, { finishFlush: constants.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +const brotlied: Buffer = brotliDecompressSync(brotliDecompressSync(compressMe)); + +brotliDecompress(compressMe, (err: Error | null, result: Buffer) => result); +brotliDecompress(compressMe, { finishFlush: constants.BROTLI_OPERATION_FINISH }, (err: Error | null, result: Buffer) => result); diff --git a/types/node/tls.d.ts b/types/node/tls.d.ts index e7222b5a5b..ef9a7bd4b0 100644 --- a/types/node/tls.d.ts +++ b/types/node/tls.d.ts @@ -218,26 +218,32 @@ declare module "tls" { addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; } interface TlsOptions extends SecureContextOptions { diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts deleted file mode 100644 index 18db498871..0000000000 --- a/types/node/ts3.1/node-tests.ts +++ /dev/null @@ -1,2 +0,0 @@ -// tslint:disable-next-line:no-bad-reference -import "../node-tests"; diff --git a/types/node/ts3.2/globals.d.ts b/types/node/ts3.2/globals.d.ts new file mode 100644 index 0000000000..c14a1a36b1 --- /dev/null +++ b/types/node/ts3.2/globals.d.ts @@ -0,0 +1,8 @@ +// tslint:disable-next-line:no-bad-reference +/// + +declare namespace NodeJS { + interface HRTime { + bigint(): bigint; + } +} diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.2/index.d.ts similarity index 71% rename from types/node/ts3.1/index.d.ts rename to types/node/ts3.2/index.d.ts index ee9f75cc5f..ce7709bc7c 100644 --- a/types/node/ts3.1/index.d.ts +++ b/types/node/ts3.2/index.d.ts @@ -1,18 +1,20 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 // Reference required types from the default lib: /// /// /// +/// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: // tslint:disable-next-line:no-bad-reference /// -// TypeScript 3.1-specific augmentations: +// TypeScript 3.2-specific augmentations: /// +/// diff --git a/types/node/ts3.2/node-tests.ts b/types/node/ts3.2/node-tests.ts new file mode 100644 index 0000000000..3f64e22e81 --- /dev/null +++ b/types/node/ts3.2/node-tests.ts @@ -0,0 +1,11 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; + +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +{ + { + const hrtimeBigint: bigint = process.hrtime.bigint(); + } +} diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.2/tsconfig.json similarity index 100% rename from types/node/ts3.1/tsconfig.json rename to types/node/ts3.2/tsconfig.json diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.2/tslint.json similarity index 100% rename from types/node/ts3.1/tslint.json rename to types/node/ts3.2/tslint.json diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.2/util.d.ts similarity index 100% rename from types/node/ts3.1/util.d.ts rename to types/node/ts3.2/util.d.ts diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index e16d482b6f..831c9861f0 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -43,16 +43,24 @@ "worker_threads.d.ts", "zlib.d.ts", "node-tests.ts", - "test/http.ts", - "test/readline.ts", - "test/global.ts", - "test/worker_threads.ts", - "test/util.ts", - "test/net.ts", - "test/dgram.ts", + "test/buffer.ts", + "test/child_process.ts", + "test/crypto.ts", + "test/dgram.ts", + "test/global.ts", + "test/http.ts", + "test/http2.ts", + "test/net.ts", + "test/perf_hooks.ts", + "test/readline.ts", + "test/stream.ts", "test/tty.ts", - "test/crypto.ts" + "test/util.ts", + "test/repl.ts", + "test/worker_threads.ts", + "test/zlib.ts", + "test/tls.ts" ], "compilerOptions": { "module": "commonjs", diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 1f29bbcc10..2190660451 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -531,6 +531,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v10/buffer.d.ts b/types/node/v10/buffer.d.ts index 1d618f2c4b..0fe668b17d 100644 --- a/types/node/v10/buffer.d.ts +++ b/types/node/v10/buffer.d.ts @@ -2,6 +2,10 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ new(size: number): Buffer; diff --git a/types/node/v10/child_process.d.ts b/types/node/v10/child_process.d.ts index c8d20b8249..1114247bee 100644 --- a/types/node/v10/child_process.d.ts +++ b/types/node/v10/child_process.d.ts @@ -293,7 +293,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } function spawnSync(command: string): SpawnSyncReturns; function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/v10/globals.d.ts b/types/node/v10/globals.d.ts index 23cab2f1f8..534c03240d 100644 --- a/types/node/v10/globals.d.ts +++ b/types/node/v10/globals.d.ts @@ -696,6 +696,10 @@ declare namespace NodeJS { destroy(error?: Error): void; } + interface HRTime { + (time?: [number, number]): [number, number]; + } + interface Process extends EventEmitter { stdout: WriteStream; stderr: WriteStream; @@ -766,7 +770,7 @@ declare namespace NodeJS { release: ProcessRelease; umask(mask?: number): number; uptime(): number; - hrtime(time?: [number, number]): [number, number]; + hrtime: HRTime; domain: Domain; // Worker diff --git a/types/node/v10/http.d.ts b/types/node/v10/http.d.ts index 5e1ebcc127..b55ab680cf 100644 --- a/types/node/v10/http.d.ts +++ b/types/node/v10/http.d.ts @@ -154,6 +154,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/v10/index.d.ts b/types/node/v10/index.d.ts index a237502039..65f057b262 100644 --- a/types/node/v10/index.d.ts +++ b/types/node/v10/index.d.ts @@ -33,6 +33,7 @@ // Jeremie Rodriguez // Samuel Ainsworth // Kyle Uehlein +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // NOTE: These definitions support NodeJS and TypeScript 3.1. diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 3614c30f97..6602ce7af2 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -35,7 +35,7 @@ import * as trace_events from "trace_events"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -47,6 +47,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff x.children.push(y); x.parent = require.main; require.main = y; + const hrtimeArray: [number, number] = process.hrtime(); } } @@ -632,6 +633,15 @@ function bufferTests() { const buffer = new Buffer('123'); const octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/v10/package.json b/types/node/v10/package.json index c1f0c68752..cda6cc6dc8 100644 --- a/types/node/v10/package.json +++ b/types/node/v10/package.json @@ -2,10 +2,10 @@ "private": true, "types": "index", "typesVersions": { - ">=3.1.0-0": { + ">=3.2.0-0": { "*": [ - "ts3.1/*" + "ts3.2/*" ] } } -} \ No newline at end of file +} diff --git a/types/node/v10/ts3.1/node-tests.ts b/types/node/v10/ts3.1/node-tests.ts deleted file mode 100644 index 18db498871..0000000000 --- a/types/node/v10/ts3.1/node-tests.ts +++ /dev/null @@ -1,2 +0,0 @@ -// tslint:disable-next-line:no-bad-reference -import "../node-tests"; diff --git a/types/node/v10/ts3.2/globals.d.ts b/types/node/v10/ts3.2/globals.d.ts new file mode 100644 index 0000000000..c14a1a36b1 --- /dev/null +++ b/types/node/v10/ts3.2/globals.d.ts @@ -0,0 +1,8 @@ +// tslint:disable-next-line:no-bad-reference +/// + +declare namespace NodeJS { + interface HRTime { + bigint(): bigint; + } +} diff --git a/types/node/v10/ts3.1/index.d.ts b/types/node/v10/ts3.2/index.d.ts similarity index 71% rename from types/node/v10/ts3.1/index.d.ts rename to types/node/v10/ts3.2/index.d.ts index ee9f75cc5f..ce7709bc7c 100644 --- a/types/node/v10/ts3.1/index.d.ts +++ b/types/node/v10/ts3.2/index.d.ts @@ -1,18 +1,20 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // NOTE: TypeScript version-specific augmentations can be found in the following paths: // - ~/base.d.ts - Shared definitions common to all TypeScript versions // - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 // Reference required types from the default lib: /// /// /// +/// // Base definitions for all NodeJS modules that are not specific to any version of TypeScript: // tslint:disable-next-line:no-bad-reference /// -// TypeScript 3.1-specific augmentations: +// TypeScript 3.2-specific augmentations: /// +/// diff --git a/types/node/v10/ts3.2/node-tests.ts b/types/node/v10/ts3.2/node-tests.ts new file mode 100644 index 0000000000..3f64e22e81 --- /dev/null +++ b/types/node/v10/ts3.2/node-tests.ts @@ -0,0 +1,11 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; + +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +{ + { + const hrtimeBigint: bigint = process.hrtime.bigint(); + } +} diff --git a/types/node/v10/ts3.1/tsconfig.json b/types/node/v10/ts3.2/tsconfig.json similarity index 100% rename from types/node/v10/ts3.1/tsconfig.json rename to types/node/v10/ts3.2/tsconfig.json diff --git a/types/node/v10/ts3.1/tslint.json b/types/node/v10/ts3.2/tslint.json similarity index 100% rename from types/node/v10/ts3.1/tslint.json rename to types/node/v10/ts3.2/tslint.json diff --git a/types/node/v10/ts3.1/util.d.ts b/types/node/v10/ts3.2/util.d.ts similarity index 100% rename from types/node/v10/ts3.1/util.d.ts rename to types/node/v10/ts3.2/util.d.ts diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index f52a8d01f8..279c3cefbf 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -785,6 +785,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 6dd1ad1dc0..f4fa74291c 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -857,6 +857,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index a4fde30a97..611b9b7903 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -8,6 +8,7 @@ // Sebastian Silbermann // Hoàng Văn Khải // Sander Koenders +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -683,6 +684,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -854,6 +857,7 @@ declare module "http" { write(str: string, encoding?: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; + readonly path: string; write(chunk: any, encoding?: string): void; abort(): void; setTimeout(timeout: number, callback?: Function): void; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 764dc6e8d0..81c33d9658 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -28,7 +28,7 @@ import * as v8 from "v8"; import * as dns from "dns"; // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -448,6 +448,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 1fac090367..9728ade03f 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -22,6 +22,7 @@ // Hoàng Văn Khải // Lishude // Andrew Makarov +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -909,6 +910,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -1101,6 +1104,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; @@ -2288,7 +2292,7 @@ declare module "child_process" { stderr: T; status: number; signal: string; - error: Error; + error?: Error; } export function spawnSync(command: string): SpawnSyncReturns; export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 76f2ef380e..706b39600a 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -33,7 +33,7 @@ import * as perf_hooks from "perf_hooks"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -568,6 +568,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 220afd9e60..9934b38eb4 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -26,6 +26,7 @@ // Lishude // Andrew Makarov // Eugene Y. Q. Shen +// Jordi Oliveras Rovira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -993,6 +994,8 @@ declare module "buffer" { export var INSPECT_MAX_BYTES: number; var BuffType: typeof Buffer; var SlowBuffType: typeof SlowBuffer; + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } @@ -1186,6 +1189,7 @@ declare module "http" { constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + readonly path: string; abort(): void; onSocket(socket: net.Socket): void; setTimeout(timeout: number, callback?: () => void): this; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index e9c4f70ebb..4d0b5407c7 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -33,7 +33,7 @@ import * as perf_hooks from "perf_hooks"; import Module = require("module"); // Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; ////////////////////////////////////////////////////////// /// Global Tests : https://nodejs.org/api/global.html /// @@ -594,6 +594,15 @@ function bufferTests() { let buffer = new Buffer('123'); let octets = new Uint8Array(buffer.buffer); } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType Buffer + } } //////////////////////////////////////////////////// diff --git a/types/node/zlib.d.ts b/types/node/zlib.d.ts index dff374b8f5..60983fee91 100644 --- a/types/node/zlib.d.ts +++ b/types/node/zlib.d.ts @@ -2,9 +2,18 @@ declare module "zlib" { import * as stream from "stream"; interface ZlibOptions { - flush?: number; // default: zlib.constants.Z_NO_FLUSH - finishFlush?: number; // default: zlib.constants.Z_FINISH - chunkSize?: number; // default: 16*1024 + /** + * @default constants.Z_NO_FLUSH + */ + flush?: number; + /** + * @default constants.Z_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; windowBits?: number; level?: number; // compression only memLevel?: number; // compression only @@ -12,6 +21,27 @@ declare module "zlib" { dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default } + interface BrotliOptions { + /** + * @default constants.BROTLI_OPERATION_PROCESS + */ + flush?: number; + /** + * @default constants.BROTLI_OPERATION_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + params?: { + /** + * Each key is a `constants.BROTLI_*` constant. + */ + [key: number]: boolean | number; + }; + } + interface Zlib { /** @deprecated Use bytesWritten instead. */ readonly bytesRead: number; @@ -29,6 +59,8 @@ declare module "zlib" { reset(): void; } + interface BrotliCompress extends stream.Transform, Zlib { } + interface BrotliDecompress extends stream.Transform, Zlib { } interface Gzip extends stream.Transform, Zlib { } interface Gunzip extends stream.Transform, Zlib { } interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } @@ -37,6 +69,8 @@ declare module "zlib" { interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } interface Unzip extends stream.Transform, Zlib { } + function createBrotliCompress(options?: BrotliOptions): BrotliCompress; + function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; function createGzip(options?: ZlibOptions): Gzip; function createGunzip(options?: ZlibOptions): Gunzip; function createDeflate(options?: ZlibOptions): Deflate; @@ -46,96 +80,273 @@ declare module "zlib" { function createUnzip(options?: ZlibOptions): Unzip; type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; - function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + + type CompressCallback = (error: Error | null, result: Buffer) => void; + + function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliCompress(buf: InputType, callback: CompressCallback): void; + function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliDecompress(buf: InputType, callback: CompressCallback): void; + function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function deflate(buf: InputType, callback: CompressCallback): void; + function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, callback: CompressCallback): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, callback: CompressCallback): void; + function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, callback: CompressCallback): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, callback: CompressCallback): void; + function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, callback: CompressCallback): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; - function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, callback: CompressCallback): void; + function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; namespace constants { - // Allowed flush values. + const BROTLI_DECODE: number; + const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; + const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; + const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; + const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; + const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; + const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; + const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; + const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; + const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; + const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; + const BROTLI_DECODER_ERROR_UNREACHABLE: number; + const BROTLI_DECODER_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_NO_ERROR: number; + const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; + const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; + const BROTLI_DECODER_RESULT_ERROR: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_RESULT_SUCCESS: number; + const BROTLI_DECODER_SUCCESS: number; - const Z_NO_FLUSH: number; - const Z_PARTIAL_FLUSH: number; - const Z_SYNC_FLUSH: number; - const Z_FULL_FLUSH: number; - const Z_FINISH: number; - const Z_BLOCK: number; - const Z_TREES: number; + const BROTLI_DEFAULT_MODE: number; + const BROTLI_DEFAULT_QUALITY: number; + const BROTLI_DEFAULT_WINDOW: number; + const BROTLI_ENCODE: number; + const BROTLI_LARGE_MAX_WINDOW_BITS: number; + const BROTLI_MAX_INPUT_BLOCK_BITS: number; + const BROTLI_MAX_QUALITY: number; + const BROTLI_MAX_WINDOW_BITS: number; + const BROTLI_MIN_INPUT_BLOCK_BITS: number; + const BROTLI_MIN_QUALITY: number; + const BROTLI_MIN_WINDOW_BITS: number; - // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + const BROTLI_MODE_FONT: number; + const BROTLI_MODE_GENERIC: number; + const BROTLI_MODE_TEXT: number; - const Z_OK: number; - const Z_STREAM_END: number; - const Z_NEED_DICT: number; - const Z_ERRNO: number; - const Z_STREAM_ERROR: number; - const Z_DATA_ERROR: number; - const Z_MEM_ERROR: number; - const Z_BUF_ERROR: number; - const Z_VERSION_ERROR: number; + const BROTLI_OPERATION_EMIT_METADATA: number; + const BROTLI_OPERATION_FINISH: number; + const BROTLI_OPERATION_FLUSH: number; + const BROTLI_OPERATION_PROCESS: number; - // Compression levels. + const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; + const BROTLI_PARAM_LARGE_WINDOW: number; + const BROTLI_PARAM_LGBLOCK: number; + const BROTLI_PARAM_LGWIN: number; + const BROTLI_PARAM_MODE: number; + const BROTLI_PARAM_NDIRECT: number; + const BROTLI_PARAM_NPOSTFIX: number; + const BROTLI_PARAM_QUALITY: number; + const BROTLI_PARAM_SIZE_HINT: number; + + const DEFLATE: number; + const DEFLATERAW: number; + const GUNZIP: number; + const GZIP: number; + const INFLATE: number; + const INFLATERAW: number; + const UNZIP: number; - const Z_NO_COMPRESSION: number; - const Z_BEST_SPEED: number; const Z_BEST_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BLOCK: number; + const Z_BUF_ERROR: number; + const Z_DATA_ERROR: number; + + const Z_DEFAULT_CHUNK: number; const Z_DEFAULT_COMPRESSION: number; - - // Compression strategy. - - const Z_FILTERED: number; - const Z_HUFFMAN_ONLY: number; - const Z_RLE: number; - const Z_FIXED: number; + const Z_DEFAULT_LEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; const Z_DEFAULT_STRATEGY: number; + const Z_DEFAULT_WINDOWBITS: number; + + const Z_ERRNO: number; + const Z_FILTERED: number; + const Z_FINISH: number; + const Z_FIXED: number; + const Z_FULL_FLUSH: number; + const Z_HUFFMAN_ONLY: number; + const Z_MAX_CHUNK: number; + const Z_MAX_LEVEL: number; + const Z_MAX_MEMLEVEL: number; + const Z_MAX_WINDOWBITS: number; + const Z_MEM_ERROR: number; + const Z_MIN_CHUNK: number; + const Z_MIN_LEVEL: number; + const Z_MIN_MEMLEVEL: number; + const Z_MIN_WINDOWBITS: number; + const Z_NEED_DICT: number; + const Z_NO_COMPRESSION: number; + const Z_NO_FLUSH: number; + const Z_OK: number; + const Z_PARTIAL_FLUSH: number; + const Z_RLE: number; + const Z_STREAM_END: number; + const Z_STREAM_ERROR: number; + const Z_SYNC_FLUSH: number; + const Z_VERSION_ERROR: number; + const ZLIB_VERNUM: number; } - // Constants + /** + * @deprecated + */ const Z_NO_FLUSH: number; + /** + * @deprecated + */ const Z_PARTIAL_FLUSH: number; + /** + * @deprecated + */ const Z_SYNC_FLUSH: number; + /** + * @deprecated + */ const Z_FULL_FLUSH: number; + /** + * @deprecated + */ const Z_FINISH: number; + /** + * @deprecated + */ const Z_BLOCK: number; + /** + * @deprecated + */ const Z_TREES: number; + /** + * @deprecated + */ const Z_OK: number; + /** + * @deprecated + */ const Z_STREAM_END: number; + /** + * @deprecated + */ const Z_NEED_DICT: number; + /** + * @deprecated + */ const Z_ERRNO: number; + /** + * @deprecated + */ const Z_STREAM_ERROR: number; + /** + * @deprecated + */ const Z_DATA_ERROR: number; + /** + * @deprecated + */ const Z_MEM_ERROR: number; + /** + * @deprecated + */ const Z_BUF_ERROR: number; + /** + * @deprecated + */ const Z_VERSION_ERROR: number; + /** + * @deprecated + */ const Z_NO_COMPRESSION: number; + /** + * @deprecated + */ const Z_BEST_SPEED: number; + /** + * @deprecated + */ const Z_BEST_COMPRESSION: number; + /** + * @deprecated + */ const Z_DEFAULT_COMPRESSION: number; + /** + * @deprecated + */ const Z_FILTERED: number; + /** + * @deprecated + */ const Z_HUFFMAN_ONLY: number; + /** + * @deprecated + */ const Z_RLE: number; + /** + * @deprecated + */ const Z_FIXED: number; + /** + * @deprecated + */ const Z_DEFAULT_STRATEGY: number; + /** + * @deprecated + */ const Z_BINARY: number; + /** + * @deprecated + */ const Z_TEXT: number; + /** + * @deprecated + */ const Z_ASCII: number; + /** + * @deprecated + */ const Z_UNKNOWN: number; + /** + * @deprecated + */ const Z_DEFLATED: number; } diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 80195cf516..b55d2cbb42 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -12118,7 +12118,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -12466,7 +12466,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -12983,7 +12983,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -13371,7 +13371,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -13726,7 +13726,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. @@ -15100,7 +15100,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -15457,7 +15457,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -15990,7 +15990,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -16382,7 +16382,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 43a3bae9b8..f976e947ec 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -12118,7 +12118,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -12466,7 +12466,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -12983,7 +12983,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -13371,7 +13371,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -13726,7 +13726,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. @@ -15100,7 +15100,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -15457,7 +15457,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * @@ -15990,7 +15990,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Adds an event handler for a supported event. * @@ -16382,7 +16382,7 @@ declare namespace Office { * @param callback - Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, * asyncResult, which is an Office.AsyncResult object. */ - removeHandlerAsync(eventType: Office.EventType, options?: any, callback?: (asyncResult: Office.AsyncResult) => void): void; + removeHandlerAsync(eventType: Office.EventType, options?: Office.AsyncContextOptions, callback?: (asyncResult: Office.AsyncResult) => void): void; /** * Removes the event handlers for a supported event type. * diff --git a/types/pino-http/index.d.ts b/types/pino-http/index.d.ts index 54ac4e9149..86fae78a3e 100644 --- a/types/pino-http/index.d.ts +++ b/types/pino-http/index.d.ts @@ -20,6 +20,7 @@ declare namespace PinoHttp { genReqId?: GenReqId; useLevel?: Level; stream?: DestinationStream; + customLogLevel?: (res: ServerResponse, error: Error) => Level; } interface GenReqId { diff --git a/types/pino-http/pino-http-tests.ts b/types/pino-http/pino-http-tests.ts index 8a86bf08e8..013e23ae10 100644 --- a/types/pino-http/pino-http-tests.ts +++ b/types/pino-http/pino-http-tests.ts @@ -18,3 +18,4 @@ pinoHttp({ genReqId: (req) => Buffer.allocUnsafe(16) }); pinoHttp({ useLevel: 'error' }); pinoHttp({ prettyPrint: true }); pinoHttp(new Writable()); +pinoHttp({ customLogLevel(req, res) { return 'info'; } }); diff --git a/types/pkijs/index.d.ts b/types/pkijs/index.d.ts index 106dfa2405..63cbee5207 100644 --- a/types/pkijs/index.d.ts +++ b/types/pkijs/index.d.ts @@ -1908,6 +1908,12 @@ declare module "pkijs/src/RelativeDistinguishedNames" { fromSchema(schema: any): void; toSchema(): any; toJSON(): any; + /** + * Compare two RDN values, or RDN with ArrayBuffer value + * @param {(RelativeDistinguishedNames|ArrayBuffer)} compareTo The value compare to current + * @returns {boolean} + */ + isEqual(compareTo: RelativeDistinguishedNames|ArrayBuffer): boolean; } } diff --git a/types/pkijs/pkijs-tests.ts b/types/pkijs/pkijs-tests.ts index 6b7b73bb00..f2c9a88990 100644 --- a/types/pkijs/pkijs-tests.ts +++ b/types/pkijs/pkijs-tests.ts @@ -12,6 +12,8 @@ import SignerInfo from "pkijs/src/SignerInfo"; import IssuerAndSerialNumber from "pkijs/src/IssuerAndSerialNumber"; import SignedAndUnsignedAttributes from "pkijs/src/SignedAndUnsignedAttributes"; import ContentInfo from "pkijs/src/ContentInfo"; +import RelativeDistinguishedNames from "pkijs/src/RelativeDistinguishedNames"; + // ********************************************************************************* let cmsSignedBuffer = new ArrayBuffer(0); // ArrayBuffer with loaded or created CMS_Signed const trustedCertificates: Certificate[] = []; // Array of root certificates from "CA Bundle" @@ -657,4 +659,14 @@ function handleCABundle(evt: Event) { event => parseCAbundle((event.target as any).result); tempReader.readAsArrayBuffer(currentFiles[0]); -} \ No newline at end of file +} + +function typetest_RelativeDN_isEqual() { + + const rdn1 = new RelativeDistinguishedNames(); + const rdn2 = new RelativeDistinguishedNames(); + const arraybuf = new ArrayBuffer(1); + + rdn1.isEqual(rdn2); // $ExpectType boolean + rdn1.isEqual(arraybuf); // $ExpectType boolean +} diff --git a/types/qs/index.d.ts b/types/qs/index.d.ts index 2a3b10a273..aead3eb442 100644 --- a/types/qs/index.d.ts +++ b/types/qs/index.d.ts @@ -19,7 +19,7 @@ declare namespace QueryString { encode?: boolean; encoder?: (str: string) => any; filter?: Array | ((prefix: string, value: any) => any); - arrayFormat?: 'indices' | 'brackets' | 'repeat'; + arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma'; indices?: boolean; sort?: (a: any, b: any) => number; serializeDate?: (d: Date) => string; diff --git a/types/react-native-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 14d7458140..50866d6d0c 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-dialog 4.0 +// Type definitions for react-native-dialog 5.5 // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje // Stack Builders @@ -39,6 +39,10 @@ interface ContainerProps { * default: false */ visible?: boolean; + buttonSeparatorStyle?: ViewStyle; + contentStyle?: ViewStyle; + footerStyle?: ViewStyle; + headerStyle?: ViewStyle; } interface TitleProps { diff --git a/types/react-native-percentage-circle/index.d.ts b/types/react-native-percentage-circle/index.d.ts new file mode 100644 index 0000000000..a1762ab962 --- /dev/null +++ b/types/react-native-percentage-circle/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for react-native-percentage-circle 1.0 +// Project: https://github.com/JackPu/react-native-percentage-circle +// Definitions by: Haseeb Majid +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { TextStyle } from 'react-native'; + +export interface PercentageCircleProps { + color?: string; + bgcolor?: string; + innerColor?: string; + radius?: number; + percent?: number; + borderWidth?: number; + textStyle?: TextStyle[]; + disabled?: boolean; +} + +export default class PercentageCircle extends React.Component {} diff --git a/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx b/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx new file mode 100644 index 0000000000..7c016122d9 --- /dev/null +++ b/types/react-native-percentage-circle/react-native-percentage-circle-tests.tsx @@ -0,0 +1,20 @@ +import * as React from "react"; +import { View } from "react-native"; +import PercentageCircle from "react-native-percentage-circle"; + +class PercentageCircleTest extends React.Component { + render() { + return ( + + + + ); + } +} diff --git a/types/react-native-percentage-circle/tsconfig.json b/types/react-native-percentage-circle/tsconfig.json new file mode 100644 index 0000000000..77789ef23c --- /dev/null +++ b/types/react-native-percentage-circle/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-percentage-circle-tests.tsx" + ] +} diff --git a/types/react-native-percentage-circle/tslint.json b/types/react-native-percentage-circle/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-percentage-circle/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-snackbar-component/index.d.ts b/types/react-native-snackbar-component/index.d.ts new file mode 100644 index 0000000000..dfa31773e4 --- /dev/null +++ b/types/react-native-snackbar-component/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for react-native-snackbar-components 1.1 +// Project: https://github.com/sidevesh/react-native-snackbar +// Definitions by: Haseeb Majid +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { TextStyle } from 'react-native'; + +export interface SnackbarComponentProps { + accentColor?: string; + actionText?: string; + messageColor?: string; + backgroundColor?: string; + distanceCallback?: () => void; + actionHandler?: () => void; + left?: number; + right?: number; + bottom?: number; + position?: string; + textMessage?: string; + autoHidingTime?: number; + visible?: boolean; +} + +export default class SnackbarComponent extends React.Component {} diff --git a/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx b/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx new file mode 100644 index 0000000000..1795cce93a --- /dev/null +++ b/types/react-native-snackbar-component/react-native-snackbar-component-tests.tsx @@ -0,0 +1,18 @@ +import * as React from "react"; +import { View } from "react-native"; +import SnackbarComponent from "react-native-snackbar-component"; + +class SnackbarComponentTest extends React.Component { + render() { + return ( + + + + ); + } +} diff --git a/types/react-native-snackbar-component/tsconfig.json b/types/react-native-snackbar-component/tsconfig.json new file mode 100644 index 0000000000..7205073e63 --- /dev/null +++ b/types/react-native-snackbar-component/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-snackbar-component-tests.tsx" + ] +} diff --git a/types/react-native-snackbar-component/tslint.json b/types/react-native-snackbar-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-snackbar-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-swipeable-views/index.d.ts b/types/react-swipeable-views/index.d.ts index 68545673e6..24fbaf618d 100644 --- a/types/react-swipeable-views/index.d.ts +++ b/types/react-swipeable-views/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-swipeable-views 0.12 +// Type definitions for react-swipeable-views 0.13 // Project: https://github.com/oliviertassinari/react-swipeable-views // Definitions by: Michael Ledin // Deividas Bakanas @@ -29,6 +29,10 @@ export interface SwipeableViewsProps extends React.HTMLProps { axis?: AxisType; containerStyle?: React.CSSProperties; disabled?: boolean; + /* + * This is the config used to disable lazy loading, if true it will render all the views in first rendering. + */ + disableLazyLoading?: boolean; enableMouseEvents?: boolean; hysteresis?: number; ignoreNativeScroll?: boolean; diff --git a/types/react-swipeable-views/react-swipeable-views-tests.ts b/types/react-swipeable-views/react-swipeable-views-tests.ts index e35be787fb..0bdc2fabfd 100644 --- a/types/react-swipeable-views/react-swipeable-views-tests.ts +++ b/types/react-swipeable-views/react-swipeable-views-tests.ts @@ -44,7 +44,8 @@ React.createElement(SwipeableViews, { title: "Carousel", onTransitionEnd, axis: "x-reverse", - springConfig + springConfig, + disableLazyLoading: false }); React.createElement(SwipeableViews, {}); diff --git a/types/react-tooltip/index.d.ts b/types/react-tooltip/index.d.ts index 9030a2c1f4..aba9cdf734 100644 --- a/types/react-tooltip/index.d.ts +++ b/types/react-tooltip/index.d.ts @@ -79,6 +79,7 @@ declare namespace ReactTooltip { } interface Props { + children?: React.ReactNode; id?: string; place?: Place; type?: Type; diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 4f7192c4fc..b8ef50f3fb 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for slate-react 0.20 +// Type definitions for slate-react 0.21 // Project: https://github.com/ianstormtaylor/slate // Definitions by: Andy Kent // Jamie Talbot @@ -8,6 +8,7 @@ // Irwan Fario Subastian // Hanna Greaves // Francesco Agnoletto +// Jack Allen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { @@ -61,11 +62,6 @@ export interface RenderNodeProps { readOnly: boolean; } -export interface RenderPlaceholderProps { - editor: CoreEditor; - readOnly: boolean; -} - export type EventHook = ( event: Event, editor: CoreEditor, @@ -77,7 +73,6 @@ export interface Plugin { renderEditor?: (props: EditorProps, editor: CoreEditor, next: () => any) => any; renderMark?: (props: RenderMarkProps, editor: CoreEditor, next: () => any) => any; renderNode?: (props: RenderNodeProps, editor: CoreEditor, next: () => any) => any; - renderPlaceholder?: (props: RenderPlaceholderProps, editor: CoreEditor, next: () => any) => any; shouldNodeComponentUpdate?: (previousProps: RenderNodeProps, props: RenderNodeProps, editor: CoreEditor, next: () => any) => any; onBeforeInput?: EventHook; diff --git a/types/underscore.string/index.d.ts b/types/underscore.string/index.d.ts index eb0774b49a..ce2e46edd1 100644 --- a/types/underscore.string/index.d.ts +++ b/types/underscore.string/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/epeli/underscore.string // Definitions by: Ry Racherbaumer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as _ from 'underscore'; diff --git a/types/underscore/index.d.ts b/types/underscore/index.d.ts index 72498e3591..f7c73db4c0 100644 --- a/types/underscore/index.d.ts +++ b/types/underscore/index.d.ts @@ -2,6 +2,7 @@ // Project: http://underscorejs.org/ // Definitions by: Boris Yankov , Josh Baldwin , Christopher Currens , Cassey Lottman , Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare var _: _.UnderscoreStatic; export = _; @@ -553,8 +554,12 @@ declare module _ { * @param propertyName The property to look for on each element within `list`. * @return The list of elements within `list` that have the property `propertyName`. **/ - pluck( + pluck( list: _.List, + propertyName: K): T[K][]; + + pluck( + list: _.List, propertyName: string): any[]; /** diff --git a/types/underscore/underscore-tests.ts b/types/underscore/underscore-tests.ts index 6175c1874b..6ef7fcb168 100644 --- a/types/underscore/underscore-tests.ts +++ b/types/underscore/underscore-tests.ts @@ -172,6 +172,10 @@ _.contains([1, 2, 3], 3, 1); _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); +// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/33479 +var foo: any[] = [{'a': 1, 'b': 2}]; +_.pluck(foo, 'a'); + var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; _.pluck(stooges, 'name'); @@ -520,7 +524,7 @@ function chain_tests() { let numberObjects = [{property: 'odd', value: 1}, {property: 'even', value: 2}, {property: 'even', value: 0}]; let evenAndOddGroupedNumbers = _.chain(numberObjects) .groupBy('property') - .mapObject((objects: any) => _.pluck(objects, 'value')) + .mapObject((objects) => _.pluck(objects, 'value')) .value(); // { odd: [1], even: [0, 2] } var matrixOfString : string[][] = _.chain({'foo' : '1', 'bar': '1'}) diff --git a/types/webpack-env/index.d.ts b/types/webpack-env/index.d.ts index 293f06797d..705e776c1e 100644 --- a/types/webpack-env/index.d.ts +++ b/types/webpack-env/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: use-strict // rhonsby // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * Webpack module API - variables and global functions available inside modules @@ -68,6 +69,53 @@ declare namespace __WebpackModuleApi { } type ModuleId = string|number; + interface HotNotifierInfo { + type: + | 'self-declined' + | 'declined' + | 'unaccepted' + | 'accepted' + | 'disposed' + | 'accept-errored' + | 'self-accept-errored' + | 'self-accept-error-handler-errored'; + /** + * The module in question. + */ + moduleId: number; + /** + * For errors: the module id owning the accept handler. + */ + dependencyId?: number; + /** + * For declined/accepted/unaccepted: the chain from where the update was propagated. + */ + chain?: number[]; + /** + * For declined: the module id of the declining parent + */ + parentId?: number; + /** + * For accepted: the modules that are outdated and will be disposed + */ + outdatedModules?: number[]; + /** + * For accepted: The location of accept handlers that will handle the update + */ + outdatedDependencies?: { + [dependencyId: number]: number[]; + }; + /** + * For errors: the thrown error + */ + error?: Error; + /** + * For self-accept-error-handler-errored: the error thrown by the module + * before the error handler tried to handle it. + */ + originalError?: Error; + } + interface Hot { /** * Accept code updates for the specified dependencies. The callback is called when dependencies were replaced. @@ -180,6 +228,34 @@ declare namespace __WebpackModuleApi { * If true the update process continues even if some modules are not accepted (and would bubble to the entry point). */ ignoreUnaccepted?: boolean; + /** + * Ignore changes made to declined modules. + */ + ignoreDeclined?: boolean; + /** + * Ignore errors throw in accept handlers, error handlers and while reevaluating module. + */ + ignoreErrored?: boolean; + /** + * Notifier for declined modules. + */ + onDeclined?: (info: HotNotifierInfo) => void; + /** + * Notifier for unaccepted modules. + */ + onUnaccepted?: (info: HotNotifierInfo) => void; + /** + * Notifier for accepted modules. + */ + onAccepted?: (info: HotNotifierInfo) => void; + /** + * Notifier for disposed modules. + */ + onDisposed?: (info: HotNotifierInfo) => void; + /** + * Notifier for errors. + */ + onErrored?: (info: HotNotifierInfo) => void; /** * Indicates that apply() is automatically called by check function */ diff --git a/types/wu/index.d.ts b/types/wu/index.d.ts index d4a4e56c91..2164d982ef 100644 --- a/types/wu/index.d.ts +++ b/types/wu/index.d.ts @@ -57,6 +57,7 @@ declare namespace wu { function take(n: number, iter: Iterable): WuIterable; function takeWhile(fn: Filter, iter: Iterable): WuIterable; function tap(fn: Consumer, iter: Iterable): WuIterable; + function toArray(iter: Iterable): T[]; function unique(iter: Iterable): WuIterable; function zip(iter2: Iterable, iter: Iterable): WuIterable<[T, U]>; function zipLongest(iter2: Iterable, iter: Iterable): WuIterable<[T, U]>; @@ -99,6 +100,7 @@ declare namespace wu { take(n: number): WuIterable; takeWhile(fn: Filter): WuIterable; tap(fn: Consumer): WuIterable; + toArray(): T[]; unique(): WuIterable; // TODO: this makes no sense, where did the second entry come from? // tslint:disable-next-line no-unnecessary-generics diff --git a/types/wu/wu-tests.ts b/types/wu/wu-tests.ts index 86be4300db..56859811db 100644 --- a/types/wu/wu-tests.ts +++ b/types/wu/wu-tests.ts @@ -355,6 +355,18 @@ describe("wu.tee", () => { assert.equal(i2.next().value, 24); }); }); +describe("wu.toArray", () => { + it("should return array from the iterable", () => { + assert.eqArray( + wu.count(0).take(3).toArray(), + [0, 1, 2], + ); + assert.eqArray( + wu([0, 1, 2]).toArray(), + [0, 1, 2] + ); + }); +}); describe("wu.unique", () => { it("should yield only the unique items from the iterable", () => { assert.eqArray([1, 2, 3], diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 7e03517143..58067b926b 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -106,6 +106,7 @@ export interface StringSchemaConstructor { } export interface StringSchema extends Schema { + length(limit: number | Ref, message?: TestOptionsMessage): StringSchema; min(limit: number | Ref, message?: TestOptionsMessage): StringSchema; max(limit: number | Ref, message?: TestOptionsMessage): StringSchema; matches( diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index fdead13b2b..0c515ef78c 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -292,6 +292,8 @@ strSchema.isValid("hello"); // => true strSchema.required(); strSchema.required("req"); strSchema.required(() => "req"); +strSchema.length(5, "message"); +strSchema.length(5, () => "message"); strSchema.min(5, "message"); strSchema.min(5, () => "message"); strSchema.max(5, "message");