From 16b909b10fbaed9f6d8cd7e145a8d33201cf0d97 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 02:54:53 +0300 Subject: [PATCH 01/85] Node api fix according to official API --- node/index.d.ts | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index a52b0424de..e9b120cc2b 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -281,9 +281,9 @@ declare namespace NodeJS { readable: boolean; isTTY?: boolean; read(size?: number): string | Buffer; - setEncoding(encoding: string | null): void; - pause(): ReadableStream; - resume(): ReadableStream; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: string): void; @@ -302,10 +302,7 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; - } + export interface ReadWriteStream extends ReadableStream, WritableStream { } export interface Events extends EventEmitter { } @@ -1845,11 +1842,11 @@ declare module "net" { connect(port: number, host?: string, connectionListener?: Function): void; connect(path: string, connectionListener?: Function): void; bufferSize: number; - setEncoding(encoding?: string): void; + setEncoding(encoding?: string): this; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - pause(): Socket; - resume(): Socket; + pause(): this; + resume(): this; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: boolean): void; setKeepAlive(enable?: boolean, initialDelay?: number): void; @@ -3339,9 +3336,9 @@ declare module "stream" { constructor(opts?: ReadableOptions); protected _read(size: number): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: any): void; @@ -3502,8 +3499,8 @@ declare module "stream" { // Note: Duplex extends both Readable and Writable. export class Duplex extends Readable implements NodeJS.ReadWriteStream { // Readable - pause(): Duplex; - resume(): Duplex; + pause(): this; + resume(): this; // Writeable writable: boolean; constructor(opts?: DuplexOptions); @@ -3528,9 +3525,9 @@ declare module "stream" { protected _transform(chunk: any, encoding: string, callback: Function): void; protected _flush(callback: Function): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: any): void; From bbc7449794201aaa4a8c34363068e2a2e70c5321 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 19:57:33 +0300 Subject: [PATCH 02/85] Mongodb-node reconciliation --- mongodb/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index 82f8f0dcce..26d1656baf 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1185,7 +1185,7 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption setCursorOption(field: string, value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId @@ -1271,7 +1271,7 @@ export interface AggregationCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort @@ -1312,7 +1312,7 @@ export interface CommandCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray From 6c25f377ff8bbaf1cf1f9d39b22f5350b8eca55e Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 23:13:39 +0300 Subject: [PATCH 03/85] Fixed @node/node interface accroding to official NodeJS API. Closing #13782 --- node/index.d.ts | 7243 ++++++++++++++++++++++------------------------- 1 file changed, 3445 insertions(+), 3798 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index e9b120cc2b..e6333dd7d1 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -8,37 +8,162 @@ * Node.js v6.x API * * * ************************************************/ +interface NodeError { + /** + * Returns a string describing the point in the code at which the Error was instantiated. + * + * For example: + * + * ``` + * Error: Things keep happening! + * at /home/gbusey/file.js:525:2 + * at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) + * at Actor. (/home/gbusey/actors.js:400:8) + * at increaseSynergy (/home/gbusey/actors.js:701:6) + * ``` + * + * The first line is formatted as : , and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. + */ + stack?: string; -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: typeof NodeJS.Console; - assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; - error(message?: any, ...optionalParams: any[]): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; + /** + * Returns the string description of error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace. + * + * ``` + * const err = new Error('The message'); + * console.log(err.message); + * // Prints: The message + * ``` + */ + message: string; } -interface Error { - stack?: string; -} +interface Error extends NodeError { } interface ErrorConstructor { - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - stackTraceLimit: number; + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()`` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack // similar to `new Error().stack` + * ``` + * + * The first line of the trace, instead of being prefixed with `ErrorType : message`, will be the result of calling `targetObject.toString()``. + * + * The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace. + * + * The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance: + * + * ```js + * function MyError() { + * Error.captureStackTrace(this, MyError); + * } + * + * // Without passing MyError to captureStackTrace, the MyError + * // frame would should up in the .stack property. by passing + * // the constructor, we omit that frame and all frames above it. + * new MyError().stack + * ``` + */ + captureStackTrace(targetObject: T, constructorOpt?: new () => T): void; + + /** + * The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj))``. + * + * The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will not capture any frames. + */ + stackTraceLimit: number; } -// compat for TypeScript 1.8 -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } +// ES2015 collection types +interface NodeCollection { + size: number; +} + +interface NodeWeakCollection {} + +interface IterableIterator {} + +interface NodeCollectionConstructor { + prototype: T; +} + +interface Map extends NodeCollection { + clear(): void; + delete(key: K): boolean; + entries(): Array<[K, V]>; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + keys(): Array; + set(key: K, value?: V): Map; + values(): Array; + // [Symbol.iterator]():Array<[K,V]>; + // [Symbol.toStringTag]: "Map"; +} + +interface MapConstructor extends NodeCollectionConstructor> { + new (): Map; + new (): Map; +} + +declare var Map: MapConstructor; + +interface WeakMap extends NodeWeakCollection { + clear(): void; + delete(key: K): boolean; + get(key: K): V | void; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor extends NodeCollectionConstructor> { + new (): WeakMap; + new (): WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface Set extends NodeCollection { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + entries(): Array<[T, T]>; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + keys(): Array; + values(): Array; + // [Symbol.iterator]():Array; + // [Symbol.toStringTag]: "Set"; +} + +interface SetConstructor extends NodeCollectionConstructor> { + new (): Set; + new (): Set; + new (iterable: Array): Set; +} + +declare var Set: SetConstructor; + +interface WeakSet extends NodeWeakCollection { + add(value: T): WeakSet; + clear(): void; + delete(value: T): boolean; + has(value: T): boolean; + // [Symbol.toStringTag]: "WeakSet"; +} + +interface WeakSetConstructor extends NodeCollectionConstructor> { + new (): WeakSet; + new (): WeakSet; + new (iterable: Array): WeakSet; +} + +declare var WeakSet: WeakSetConstructor; /************************************************ * * @@ -47,7 +172,6 @@ interface WeakSetConstructor { } ************************************************/ declare var process: NodeJS.Process; declare var global: NodeJS.Global; -declare var console: Console; declare var __filename: string; declare var __dirname: string; @@ -60,26 +184,44 @@ declare function setImmediate(callback: (...args: any[]) => void, ...args: any[] declare function clearImmediate(immediateId: any): void; interface NodeRequireFunction { - (id: string): any; + (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; - cache: any; - extensions: any; - main: NodeModule | undefined; + resolve(id: string): string; + cache: { [filename: string]: NodeModule }; + extensions: NodeExtensions; + main: any; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; } declare var require: NodeRequire; -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: NodeModule | null; - children: NodeModule[]; +declare class NodeModule { + static runMain(): void; + static wrap(code: string): string; + static _nodeModulePaths(path: string): string[]; + static _load(request: string, parent?: NodeModule, isMain?: boolean): any; + static _resolveFilename(request: string, parent?: NodeModule, isMain?: boolean): string; + static _extensions: NodeExtensions; + + constructor(filename: string); + _compile(code: string, filename: string): string; + + id: string; + parent: NodeModule; + filename: string; + paths: string[]; + children: NodeModule[]; + exports: any; + loaded: boolean; + require: NodeRequireFunction; } declare var module: NodeModule; @@ -87,159 +229,209 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; }; +// Console class (compatible with TypeScript `lib.d.ts`). +declare interface Console { + log(msg: any, ...params: any[]): void; + info(msg: any, ...params: any[]): void; + warn(msg: any, ...params: any[]): void; + error(msg: any, ...params: any[]): void; + dir(value: any, ...params: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(msg: any, ...params: any[]): void; + assert(test?: boolean, msg?: string, ...params: any[]): void; -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } + Console: new (stdout: NodeJS.WritableStream) => Console; +} -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare var Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - new (str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - new (size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - new (arrayBuffer: ArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - new (buffer: Buffer): Buffer; - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafeSlow(size: number): Buffer; -}; +declare var console: Console; + +declare class Buffer extends Uint8Array { + [index: number]: number; + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor(str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor(arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor(array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor(buffer: Buffer); + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be _zero-filled_. + * + * @param size The desired length of the new `Buffer` + * @param fill A value to pre-fill the new `Buffer` with. Default: `0` + * @param encoding If `fill` is a string, this is its encoding. Default: `'utf8'` + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new _non-zero-filled_ `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `buffer.kMaxLength`. Otherwise, a `RangeError` is thrown. A zero-length `Buffer` will be created if `size <= 0`. + * + * The underlying memory for `Buffer` instances created in this way is not initialized. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize such `Buffer` instances to zeroes. + * + * @param size The desired length of the new `Buffer` + */ + static allocUnsafe(size: number): Buffer; + /** + * Returns `true` if `obj` is a Buffer, `false` otherwise. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise. + * + * @param encoding A character encoding name to check. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + swap16(): this; + swap32(): this; + swap64(): this; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + entries(): IterableIterator<[number, number]>; + keys(): IterableIterator; + values(): IterableIterator; +} /************************************************ * * @@ -247,301 +439,244 @@ declare var Buffer: { * * ************************************************/ declare namespace NodeJS { - export var Console: { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream): Console; - } + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } + export interface EventEmitter { + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + prependListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + eventNames(): string[]; + listenerCount(type: string): number; + } - export class EventEmitter { - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - eventNames(): (string | symbol)[]; - } + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + isPaused(): boolean; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } - export interface ReadableStream extends EventEmitter { - readable: boolean; - isTTY?: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string | null): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } + export interface WritableStream extends EventEmitter { + writable: boolean; + setDefaultEncoding(encoding: string): this; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - export interface WritableStream extends EventEmitter { - writable: boolean; - isTTY?: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface ReadWriteStream extends ReadableStream, WritableStream { } - export interface ReadWriteStream extends ReadableStream, WritableStream { } + export interface Events extends EventEmitter { } - export interface Events extends EventEmitter { } + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } + export interface Env { + PATH: string; + [key: string]: string; + } - export interface CpuUsage { - user: number; - system: number; - } + export interface Versions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } - export interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + argv0: string; + /** + * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. + */ + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: Env; + exit(code?: number): void; + exitCode?: number; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: Versions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): MemoryUsage; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - exitCode: number; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - title: string; - arch: string; - platform: string; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } + export interface Timer { + ref(): void; + unref(): void; + _called: boolean; + _onTimeout: Function; + _timerArgs?: any[]; + } - export interface Timer { - ref(): void; - unref(): void; - } -} - -interface IterableIterator { } - -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; + export interface Immediate { + _argv?: any[]; + _callback: Function; + _onImmediate: Function; + } } /************************************************ @@ -550,3566 +685,3078 @@ interface NodeBuffer extends Uint8Array { * * ************************************************/ declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + export var INSPECT_MAX_BYTES: number; + export var kMaxLength: number; + + export type Encoding = "ascii" | "latin1" | "binary" | "utf8" | "utf-8" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "hex" | "base64"; + + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } + export interface StringifyOptions { + encodeURIComponent?: Function; + } - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - class internal extends NodeJS.EventEmitter { } + export class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: number; - namespace internal { - export class EventEmitter extends internal { - static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated - static defaultMaxListeners: number; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Array<(...args: any[]) => void>; + listenerCount(event: string): number; + emit(event: string, ...args: any[]): boolean; + eventNames(): string[]; + } - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): (string | symbol)[]; - listenerCount(type: string | symbol): number; - } - } - - export = internal; + export interface Listener { + on(event: E, listener: L): this; + once(event: E, listener: L): this; + addListener(event: E, listener: L): this; + removeListener(event: E, listener: L): this; + listeners(event: E): L[]; + } } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: { [key: string]: any }; - auth?: string; - agent?: Agent | boolean; - } + export interface OutgoingHeaders { + [header: string]: number | string | string[]; + } - export interface Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - listening: boolean; - } + export interface IncomingHeaders { + [header: string]: string | string[]; + } + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHeaders; + auth?: string; + agent?: Agent | boolean; + } + + export class Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + listening: boolean; + } + + export class ServerResponse extends stream.Writable { + finished: boolean; + headersSent: boolean; + statusCode: number; + statusMessage: string; + sendDate: boolean; + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHeaders): void; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: () => void): this; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: OutgoingHeaders): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export class ClientRequest extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export class IncomingMessage extends stream.Readable { + httpVersion: string; + headers: IncomingHeaders; + rawHeaders: string[]; + trailers: IncomingHeaders; + rawTrailers: string[]; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + destroy(error?: Error): void; /** - * @deprecated Use IncomingMessage + * Only valid for request obtained from http.Server. */ - export interface ServerRequest extends IncomingMessage { - connection: net.Socket; - } - export interface ServerResponse extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - statusMessage: string; - headersSent: boolean; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: Function): ServerResponse; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - finished: boolean; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface IncomingMessage extends stream.Readable { - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - connection: net.Socket; - headers: any; - rawHeaders: string[]; - trailers: any; - rawTrailers: any; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - destroy(error?: Error): void; - } + method?: string; /** - * @deprecated Use IncomingMessage + * Only valid for request obtained from http.Server. */ - export interface ClientResponse extends IncomingMessage { } + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } - export class Agent { - maxSockets: number; - sockets: any; - requests: any; + export class Agent { + maxSockets: number; + sockets: any; + requests: any; - constructor(opts?: AgentOptions); + constructor(opts?: AgentOptions); - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } - export var METHODS: string[]; + export var METHODS: string[]; - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; + import * as child from "child_process"; + import * as events from "events"; - // interfaces - export interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv - exec?: string; - args?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - } + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } - export interface ClusterSetupMasterSettings { - exec?: string; // default: process.argv[1] - args?: string[]; // default: process.argv.slice(2) - silent?: boolean; // default: false - stdio?: any[]; - } + export interface Address { + address: string; + port: number; + addressType: string; + } - export interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + } - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: Function): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (code: number, signal: string) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - - emit(event: string, listener: Function): boolean - emit(event: "disconnect", listener: () => void): boolean - emit(event: "error", listener: (code: number, signal: string) => void): boolean - emit(event: "exit", listener: (code: number, signal: string) => void): boolean - emit(event: "listening", listener: (address: Address) => void): boolean - emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean - emit(event: "online", listener: () => void): boolean - - on(event: string, listener: Function): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (code: number, signal: string) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (code: number, signal: string) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - - export interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: Function): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - // TODO: cluster.schedulingPolicy - settings: ClusterSettings; - setupMaster(settings?: ClusterSetupMasterSettings): void; - worker: Worker; - workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: Function): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: any) => void): this; - - emit(event: string, listener: Function): boolean; - emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - emit(event: "fork", listener: (worker: Worker) => void): boolean; - emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - emit(event: "online", listener: (worker: Worker) => void): boolean; - emit(event: "setup", listener: (settings: any) => void): boolean; - - on(event: string, listener: Function): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: any) => void): this; - - once(event: string, listener: Function): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: any) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: any) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: any) => void): this; - - } - - export function disconnect(callback?: Function): void; - export function fork(env?: any): Worker; - export var isMaster: boolean; - export var isWorker: boolean; - // TODO: cluster.schedulingPolicy - export var settings: ClusterSettings; - export function setupMaster(settings?: ClusterSetupMasterSettings): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - export function addListener(event: string, listener: Function): Cluster; - export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function emit(event: string, listener: Function): boolean; - export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - export function emit(event: "fork", listener: (worker: Worker) => void): boolean; - export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - export function emit(event: "online", listener: (worker: Worker) => void): boolean; - export function emit(event: "setup", listener: (settings: any) => void): boolean; - - export function on(event: string, listener: Function): Cluster; - export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function on(event: "fork", listener: (worker: Worker) => void): Cluster; - export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function on(event: "online", listener: (worker: Worker) => void): Cluster; - export function on(event: "setup", listener: (settings: any) => void): Cluster; - - export function once(event: string, listener: Function): Cluster; - export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function once(event: "fork", listener: (worker: Worker) => void): Cluster; - export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function once(event: "online", listener: (worker: Worker) => void): Cluster; - export function once(event: "setup", listener: (settings: any) => void): Cluster; - - export function removeListener(event: string, listener: Function): Cluster; - export function removeAllListeners(event?: string): Cluster; - export function setMaxListeners(n: number): Cluster; - export function getMaxListeners(): number; - export function listeners(event: string): Function[]; - export function listenerCount(type: string): number; - - export function prependListener(event: string, listener: Function): Cluster; - export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function prependOnceListener(event: string, listener: Function): Cluster; - export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function eventNames(): string[]; + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: "disconnect", listener: (worker: Worker) => void): void; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; + export function on(event: "fork", listener: (worker: Worker) => void): void; + export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; + export function on(event: "message", listener: (worker: Worker, message: any) => void): void; + export function on(event: "online", listener: (worker: Worker) => void): void; + export function on(event: "setup", listener: (settings: any) => void): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; } declare module "zlib" { - import * as stream from "stream"; - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; finishFlush?: number } + import * as stream from "stream"; - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + export interface ZlibCallback { (error: Error, result: any): void } - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } - export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; + export function deflate(buf: Buffer | string, callback?: ZlibCallback): void; + export function deflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; + export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; + export function gzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function gzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function gzipSync(buf: Buffer | string, options?: ZlibOptions): any; + export function gunzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function gunzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): any; + export function inflate(buf: Buffer | string, callback?: ZlibCallback): void; + export function inflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function inflateSync(buf: Buffer | string, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; + export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; + export function unzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function unzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function unzipSync(buf: Buffer | string, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function hostname(): string; - export function loadavg(): number[]; - export function uptime(): number; - export function freemem(): number; - export function totalmem(): number; - export function cpus(): CpuInfo[]; - export function type(): string; - export function release(): string; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function homedir(): string; - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } - export var constants: { - UV_UDP_REUSEADDR: number, - errno: { - SIGHUP: number; - SIGINT: number; - SIGQUIT: number; - SIGILL: number; - SIGTRAP: number; - SIGABRT: number; - SIGIOT: number; - SIGBUS: number; - SIGFPE: number; - SIGKILL: number; - SIGUSR1: number; - SIGSEGV: number; - SIGUSR2: number; - SIGPIPE: number; - SIGALRM: number; - SIGTERM: number; - SIGCHLD: number; - SIGSTKFLT: number; - SIGCONT: number; - SIGSTOP: number; - SIGTSTP: number; - SIGTTIN: number; - SIGTTOU: number; - SIGURG: number; - SIGXCPU: number; - SIGXFSZ: number; - SIGVTALRM: number; - SIGPROF: number; - SIGWINCH: number; - SIGIO: number; - SIGPOLL: number; - SIGPWR: number; - SIGSYS: number; - SIGUNUSED: number; - }, - signals: { - E2BIG: number; - EACCES: number; - EADDRINUSE: number; - EADDRNOTAVAIL: number; - EAFNOSUPPORT: number; - EAGAIN: number; - EALREADY: number; - EBADF: number; - EBADMSG: number; - EBUSY: number; - ECANCELED: number; - ECHILD: number; - ECONNABORTED: number; - ECONNREFUSED: number; - ECONNRESET: number; - EDEADLK: number; - EDESTADDRREQ: number; - EDOM: number; - EDQUOT: number; - EEXIST: number; - EFAULT: number; - EFBIG: number; - EHOSTUNREACH: number; - EIDRM: number; - EILSEQ: number; - EINPROGRESS: number; - EINTR: number; - EINVAL: number; - EIO: number; - EISCONN: number; - EISDIR: number; - ELOOP: number; - EMFILE: number; - EMLINK: number; - EMSGSIZE: number; - EMULTIHOP: number; - ENAMETOOLONG: number; - ENETDOWN: number; - ENETRESET: number; - ENETUNREACH: number; - ENFILE: number; - ENOBUFS: number; - ENODATA: number; - ENODEV: number; - ENOENT: number; - ENOEXEC: number; - ENOLCK: number; - ENOLINK: number; - ENOMEM: number; - ENOMSG: number; - ENOPROTOOPT: number; - ENOSPC: number; - ENOSR: number; - ENOSTR: number; - ENOSYS: number; - ENOTCONN: number; - ENOTDIR: number; - ENOTEMPTY: number; - ENOTSOCK: number; - ENOTSUP: number; - ENOTTY: number; - ENXIO: number; - EOPNOTSUPP: number; - EOVERFLOW: number; - EPERM: number; - EPIPE: number; - EPROTO: number; - EPROTONOSUPPORT: number; - EPROTOTYPE: number; - ERANGE: number; - EROFS: number; - ESPIPE: number; - ESRCH: number; - ESTALE: number; - ETIME: number; - ETIMEDOUT: number; - ETXTBSY: number; - EWOULDBLOCK: number; - EXDEV: number; - }, + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; }; - export function arch(): string; - export function platform(): string; - export function tmpdir(): string; - export var EOL: string; - export function endianness(): "BE" | "LE"; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function tmpdir(): string; + export function homedir(): string; + export function endianness(): "BE" | "LE"; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function userInfo(options?: { encoding: 'buffer' }): { username: Buffer, uid: number, gid: number, shell: Buffer | null, homedir: Buffer } + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: string | null, homedir: string } + export var EOL: string; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; - } + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } - export interface RequestOptions extends http.RequestOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } + export interface RequestOptions extends http.RequestOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer | string[] | Buffer[]; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } - export interface Agent extends http.Agent { } + export interface AgentOptions extends http.AgentOptions { + /** + * Certificate, Private key and CA certificates to use for SSL. Default `null`. + */ + pfx?: string | Buffer; + /** + * Private key to use for SSL. Default `null`. + */ + key?: string | Buffer | string[] | Buffer[]; + /** + * A string of passphrase for the private key or pfx. Default `null`. + */ + passphrase?: string; + /** + * Public x509 certificate to use. Default `null`. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. + */ + ciphers?: string; + /** + * If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default `true`. + */ + rejectUnauthorized?: boolean; + /** + * Servername for SNI (Server Name Indication) TLS extension. + */ + servername?: string; + /** + * The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + maxCachedSessions?: number; + } - export interface AgentOptions extends http.AgentOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - maxCachedSessions?: number; - } + export class Agent extends http.Agent { + constructor(options?: AgentOptions); + } - export var Agent: { - new (options?: AgentOptions): Agent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export var globalAgent: Agent; + export class Server extends tls.Server { } + + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; } declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; } declare module "repl" { - import * as stream from "stream"; - import * as readline from "readline"; + import { EventEmitter } from "events"; + import { Interface } from "readline"; - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: any; - breakEvalOnSigint?: any; - } + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: symbol; + breakEvalOnSigint?: boolean; + } - export interface REPLServer extends readline.ReadLine { - defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; - displayPrompt(preserveCursor?: boolean): void; + export function start(options: ReplOptions): REPLServer; - /** - * events.EventEmitter - * 1. exit - * 2. reset - **/ + export type REPLCommand = (this: REPLServer, rest: string) => void; - addListener(event: string, listener: Function): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: Function): this; + export class REPLServer extends Interface { + inputStream: NodeJS.ReadableStream; + outputStream: NodeJS.WritableStream; + useColors: boolean; + commands: { + [command: string]: REPLCommand; + }; + defineCommand(keyword: string, cmd: REPLCommand | { help: string, action: REPLCommand }): void; + displayPrompt(preserveCursor?: boolean): void; + setPrompt(prompt: string): void; + turnOffEditorMode(): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: any): boolean; - - on(event: string, listener: Function): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: Function): this; - - once(event: string, listener: Function): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: Function): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: Function): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: Function): this; - } - - export function start(options: ReplOptions): REPLServer; + export class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; + import * as events from "events"; + import * as stream from "stream"; - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } - export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; - close(): void; - write(data: string | Buffer, key?: Key): void; + export class Interface extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + } - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - **/ + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: any) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; + export interface CompleterResult { + completions: string[]; + line: string; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: any): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; + export interface InterfaceOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: any) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface; + export function createInterface(options: InterfaceOptions): Interface; - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: any) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: any) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: any) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - } - - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } - - export type CompleterResult = [string[], string]; - - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } - - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; - export function createInterface(options: ReadLineOptions): ReadLine; - - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - export class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; - export function runInThisContext(code: string, options?: RunningScriptOptions): any; + export interface Context { } + + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + + export interface RunInNewContextOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + + export interface RunInContextOptions extends RunInNewContextOptions { + breakOnSigint?: boolean; + } + + export class Script { + constructor(code: string, options?: string | ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunInContextOptions): any; + runInNewContext(sandbox?: Context, options?: RunInNewContextOptions): any; + runInThisContext(options?: RunInNewContextOptions): any; + } + + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: string | RunInNewContextOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: string | RunInNewContextOptions): any; + export function runInThisContext(code: string, options?: string | RunInNewContextOptions): any; + /** + * @deprecated + */ + export function createScript(code: string, options?: string | ScriptOptions): Script; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as net from "net"; + import * as events from "events"; + import * as stream from "stream"; + import * as buffer from "buffer"; + import * as net from "net"; - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle?: any): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - ref(): void; + export class ChildProcess extends events.EventEmitter implements + events.Listener<'close', (code: number, signal: string) => void>, + events.Listener<'error', (error: Error) => void>, + events.Listener<'exit', ((code: number, signal: string | null) => void) | ((code: number | null, signal: string) => void)>, + events.Listener<'message', (message: any, sendHandle?: net.Socket | net.Server) => void>, + events.Listener<'disconnect', () => void> { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + } - /** - * events.EventEmitter - * 1. close - * 2. disconnet - * 3. error - * 4. exit - * 5. message - **/ + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: (code: number, signal: string) => void): this; - addListener(event: "disconnet", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - emit(event: string, ...args: any[]): boolean; - emit(event: "close", code: number, signal: string): boolean; - emit(event: "disconnet"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + encoding?: buffer.Encoding | 'buffer'; + } - on(event: string, listener: Function): this; - on(event: "close", listener: (code: number, signal: string) => void): this; - on(event: "disconnet", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - once(event: string, listener: Function): this; - once(event: "close", listener: (code: number, signal: string) => void): this; - once(event: "disconnet", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + encoding?: buffer.Encoding | 'buffer'; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: (code: number, signal: string) => void): this; - prependListener(event: "disconnet", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "disconnet", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - } + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. - } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + shell?: boolean | string; + encoding?: buffer.Encoding | 'buffer'; + } - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. - } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: buffer.Encoding | 'buffer'; + } - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptions & { encoding: 'buffer' }): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: buffer.Encoding | 'buffer'; + } - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string | any; - slashes?: boolean; - hash?: string; - path?: string; - } + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; - export function format(url: Url): string; - export function resolve(from: string, to: string): string; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url | string): string; + export function resolve(from: string, to: string): string; } declare module "dns" { - export interface MxRecord { - exchange: string, - priority: number - } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; - export function setServers(servers: string[]): void; - - //Error codes - export var NODATA: string; - export var FORMERR: string; - export var SERVFAIL: string; - export var NOTFOUND: string; - export var NOTIMP: string; - export var REFUSED: string; - export var BADQUERY: string; - export var BADNAME: string; - export var BADFAMILY: string; - export var BADRESP: string; - export var CONNREFUSED: string; - export var TIMEOUT: string; - export var EOF: string; - export var FILE: string; - export var NOMEM: string; - export var DESTRUCTION: string; - export var BADSTR: string; - export var BADFLAGS: string; - export var NONAME: string; - export var BADHINTS: string; - export var NOTINITIALIZED: string; - export var LOADIPHLPAPI: string; - export var ADDRGETNETWORKPARAMS: string; - export var CANCELLED: string; + export const NODATA: 'ENODATA'; + export const FORMERR: 'EFORMERR'; + export const SERVFAIL: 'ESERVFAIL'; + export const NOTFOUND: 'ENOTFOUND'; + export const NOTIMP: 'ENOTIMP'; + export const REFUSED: 'EREFUSED'; + export const BADQUERY: 'EBADQUERY'; + export const BADNAME: 'EBADNAME'; + export const BADFAMILY: 'EBADFAMILY'; + export const BADRESP: 'EBADRESP'; + export const CONNREFUSED: 'ECONNREFUSED'; + export const TIMEOUT: 'ETIMEOUT'; + export const EOF: 'EOF'; + export const FILE: 'EFILE'; + export const NOMEM: 'ENOMEM'; + export const DESTRUCTION: 'EDESTRUCTION'; + export const BADSTR: 'EBADSTR'; + export const BADFLAGS: 'EBADFLAGS'; + export const NONAME: 'ENONAME'; + export const BADHINTS: 'EBADHINTS'; + export const NOTINITIALIZED: 'ENOTINITIALIZED'; + export const LOADIPHLPAPI: 'ELOADIPHLPAPI'; + export const ADDRGETNETWORKPARAMS: 'EADDRGETNETWORKPARAMS'; + export const CANCELLED: 'ECANCELLED'; } declare module "net" { - import * as stream from "stream"; - import * as events from "events"; + import * as stream from "stream"; - export interface Socket extends stream.Duplex { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; + export class Socket extends stream.Duplex { + constructor(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }); - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): this; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): this; - resume(): this; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; - destroyed: boolean; + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } - on(event: string, listener: Function): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; + export class Server extends Socket { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port: number, hostname?: string, listeningListener?: Function): this; + listen(port: number, backlog?: number, listeningListener?: Function): this; + listen(port: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + close(callback?: () => void): this; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + } - once(event: string, listener: Function): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; - listen(port: number, hostname?: string, listeningListener?: Function): Server; - listen(port: number, backlog?: number, listeningListener?: Function): Server; - listen(port: number, listeningListener?: Function): Server; - listen(path: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; - listen(handle: any, backlog?: number, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): Server; - unref(): Server; - maxConnections: number; - connections: number; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - } - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; } declare module "dgram" { - import * as events from "events"; + import * as events from "events"; - interface RemoteInfo { - address: string; - family: string; - port: number; - } + export interface RemoteInfo { + address: string; + port: number; + size: number; + } - interface AddressInfo { - address: string; - family: string; - port: number; - } + export interface AddressInfo { + address: string; + family: string; + port: number; + } - interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } + export interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - interface SocketOptions { - type: "udp4" | "udp6"; - reuseAddr?: boolean; - } + export interface SocketOptions { + type: string; + reuseAddr?: boolean; + } - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(type: string | SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export interface Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port?: number, address?: string, callback?: () => void): void; - bind(options: BindOptions, callback?: Function): void; - close(callback?: any): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setTTL(ttl: number): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): this; - unref(): this; - - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - } + export class Socket extends events.EventEmitter { + send(msg: Buffer | string | Array, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | string | Array, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + close(callback?: () => void): void; + setTTL(ttl: number): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): void; + unref(): void; + } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: Function): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (code: number, signal: string) => void): this; - - on(event: string, listener: Function): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (code: number, signal: string) => void): this; - - once(event: string, listener: Function): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (code: number, signal: string) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; - } - - export interface ReadStream extends stream.Readable { - close(): void; - destroy(): void; - bytesRead: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - export interface WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } + import * as stream from "stream"; + import * as events from "events"; + import * as buffer from "buffer"; + /** + * Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type. + */ + export class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. + * "Access Time" - Time when file data last accessed. Changed by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + atime: Date; /** - * Synchronous rename - * @param oldPath - * @param newPath + * "Modified Time" - Time when file data last modified. Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string | Buffer, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string | Buffer, mode: number): void; - export function chmodSync(path: string | Buffer, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string | Buffer, mode: number): void; - export function lchmodSync(path: string | Buffer, mode: string): void; - export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string | Buffer): Stats; - export function lstatSync(path: string | Buffer): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; - export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; - export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string | Buffer): string; - export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; - /* - * Asynchronous unlink - deletes the file specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + mtime: Date; + /** + * "Change Time" - Time when file status was last changed (inode data modification). Changed by the `chmod(2)`, `chown(2)`, `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`,` utimes(2)`, `read(2)`, and `write(2)` system calls. */ - export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous unlink - deletes the file specified in {path} - * - * @param path + ctime: Date; + /** + * "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the `utimes(2)` system call. */ - export function unlinkSync(path: string | Buffer): void; - /* - * Asynchronous rmdir - removes the directory specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + birthtime: Date; + } + + export type WatchListener = (eventType: string, filename?: string | Buffer) => void; + + /** + * Objects returned from fs.watch() are of this type. + */ + export class FSWatcher extends events.EventEmitter implements + events.Listener<'change', WatchListener> { + close(): void; + } + + export class ReadStream extends stream.Readable implements + events.Listener<'open', (fd: number) => void>, + events.Listener<'close', () => void> { + bytesRead: number; + path: string | Buffer; + close(): void; + destroy(): void; + } + + export class WriteStream extends stream.Writable implements + events.Listener<'open', (fd: number) => void>, + events.Listener<'close', () => void> { + close(): void; + bytesWritten: number; + path: string | Buffer; + } + + export const F_OK: number; + export const R_OK: number; + export const W_OK: number; + export const X_OK: number; + + export const constants: { + O_RDONLY: number; + O_WRONLY: number; + O_RDWR: number; + S_IFMT: number; + S_IFREG: number; + S_IFDIR: number; + S_IFCHR: number; + S_IFBLK: number; + S_IFIFO: number; + S_IFLNK: number; + S_IFSOCK: number; + O_CREAT: number; + O_EXCL: number; + O_NOCTTY: number; + O_TRUNC: number; + O_APPEND: number; + O_DIRECTORY: number; + O_NOFOLLOW: number; + O_SYNC: number; + O_SYMLINK: number; + O_NONBLOCK: number; + S_IRWXU: number; + S_IRUSR: number; + S_IWUSR: number; + S_IXUSR: number; + S_IRWXG: number; + S_IRGRP: number; + S_IWGRP: number; + S_IXGRP: number; + S_IRWXO: number; + S_IROTH: number; + S_IWOTH: number; + S_IXOTH: number; + F_OK: number; + R_OK: number; + W_OK: number; + X_OK: number; + [key: string]: number; + } + + /** + * Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of `mode`. It is possible to create a mask consisting of the bitwise OR of two or more values. + */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.access()`. This throws if any accessibility checks fail, and does nothing otherwise. + */ + export function accessSync(path: string | Buffer, mode?: number): void; + + export interface AppendFileOptions { + encoding?: buffer.Encoding; + mode?: number; + flag?: string; + } + + /** + * Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a buffer. + */ + export function appendFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function appendFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | AppendFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * The synchronous version of `fs.appendFile()`. + */ + export function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: AppendFileOptions | null): void; + + /** + * Asynchronous chmod(2). + */ + export function chmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous chmod(2). + */ + export function chmodSync(path: string | Buffer, mode: number): void; + + /** + * Asynchronous chown(2). + */ + export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous chown(2). + */ + export function chownSync(path: string | Buffer, uid: number, gid: number): void; + + /** + * Asynchronous close(2). + */ + export function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous close(2). + */ + export function closeSync(fd: number): void; + + export interface ReadStreamOptions { + flags?: string; + encoding?: buffer.Encoding; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + } + + /** + * Returns a new ReadStream object. + * + * Be aware that, unlike the default value set for `highWaterMark` on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter. + */ + export function createReadStream(path: string | Buffer, options?: ReadStreamOptions | null): ReadStream; + + export interface WriteStreamOptions { + flags?: string; + defaultEncoding?: buffer.Encoding; + fd?: number; + mode?: number; + autoClose?: boolean; + start: number; + end: number; + } + + /** + * Returns a new WriteStream object. + */ + export function createWriteStream(path: string | Buffer, options?: WriteStreamOptions | null): WriteStream; + + /** + * Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. + * + * @deprecated + */ + export function exists(path: string | Buffer, callback: (exists: boolean) => void): void; + + /** + * Synchronous version of `fs.exists()`. Returns true if the file exists, false otherwise. + */ + export function existsSync(path: string | Buffer): boolean; + + /** + * Asynchronous fchmod(2). + */ + export function fchmod(fd: number, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fchmod(2). + */ + export function fchmodSync(fd: number, mode: number): void; + + /** + * Asynchronous fchown(2). + */ + export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fchown(2). + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous fdatasync(2). + */ + export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fdatasync(2). + */ + export function fdatasyncSync(fd: number): void; + + /** + * Asynchronous fstat(2). + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous fstat(2). + */ + export function fstatSync(fd: number): Stats; + + /** + * Asynchronous fsync(2). + */ + export function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fsync(2). + */ + export function fsyncSync(fd: number): void; + + /** + * Asynchronous ftruncate(2). + * + * If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. + * + * If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes ('\0'). + */ + export function ftruncate(fd: number, len: number | null | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous ftruncate(2). + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Change the file timestamps of a file referenced by the supplied file descriptor. + */ + export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.futimes()`. + */ + export function futimesSync(fd: number, atime: number, mtime: number): void; + + /** + * Asynchronous lchmod(2). + * + * Only available on Mac OS X. + * + * @deprecated + */ + export function lchmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous lchmod(2). + * + * @deprecated + */ + export function lchmodSync(path: string | Buffer, mode: number): void; + + /** + * Asynchronous lchown(2). + * + * @deprecated + */ + export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous lchown(2). + * + * @deprecated + */ + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + + /** + * Asynchronous link(2). + */ + export function link(existingPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous link(2). + */ + export function linkSync(existingPath: string | Buffer, newPath: string | Buffer): void; + + /** + * Asynchronous lstat(2). `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. + */ + export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous lstat(2). + */ + export function lstatSync(path: string | Buffer): Stats; + + /** + * Asynchronous mkdir(2). `mode` defaults to `0o777`. + */ + export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function mkdir(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous mkdir(2). + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + + export interface MkdtempOptions { + encoding: buffer.Encoding; + } + + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; + export function mkdtemp(prefix: string, options: buffer.Encoding | MkdtempOptions | null, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; + + /** + * The synchronous version of fs.mkdtemp(). Returns the created folder path. + */ + export function mkdtempSync(prefix: string, options?: buffer.Encoding | MkdtempOptions | null): string; + + /** + * Asynchronous file open. See open(2). `flags` can be: + * + * 'r' - Open file for reading. An exception occurs if the file does not exist. + * + * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist. + * + * 'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. + * + * This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. + * + * Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()` + * + * 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). + * + * 'wx' - Like `'w'` but fails if `path` exists. + * + * 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). + * + * 'wx+' - Like `'w+'` but fails if `path` exists. + * + * 'a' - Open file for appending. The file is created if it does not exist. + * + * 'ax' - Like 'a' but fails if `path` exists. + * + * 'a+' - Open file for reading and appending. The file is created if it does not exist. + * + * 'ax+' - Like 'a+' but fails if `path` exists. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writable. + */ + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Synchronous version of `fs.open()`. + */ + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + + /** + * Read data from the file specified by fd. + * + * @param buffer is the buffer that the data will be written to. + * @param offset is the offset in the buffer to start writing at. + * @param length is an integer specifying the number of bytes to read. + * @param position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. + */ + export function read(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; + + export interface ReaddirOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous readdir(3). Reads the contents of a directory. + * + * @param files is an array of the names of the files in the directory excluding '.' and '..'. + */ + export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + export function readdir(path: string | Buffer, options: 'buffer' | (ReadFileOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + export function readdir(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'. + */ + export function readdirSync(path: string | Buffer): string[]; + export function readdirSync(path: string | Buffer, options: 'buffer' | (ReaddirOptions & { encoding: 'buffer' })): Buffer[]; + export function readdirSync(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null): string[]; + + export interface ReadFileOptions { + encoding?: buffer.Encoding | 'buffer'; + flag?: string; + } + + /** + * Asynchronously reads the entire contents of a file. + */ + export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export function readFile(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding }), callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + export function readFile(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Synchronous version of `fs.readFile`. + */ + export function readFileSync(file: string | Buffer | number): Buffer; + export function readFileSync(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding })): string; + export function readFileSync(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null): Buffer; + + export interface ReadlinkOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous readlink(2). + */ + export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export function readlink(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + export function readlink(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Synchronous readlink(2). + */ + export function readlinkSync(path: string | Buffer): string; + export function readlinkSync(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' })): Buffer; + export function readlinkSync(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null): string; + + /** + * Synchronous version of `fs.read()`. + */ + export function readSync(fd: number, buffer: string | Buffer, offset: number, length: number, position: number): number; + + export interface RealpathOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous realpath(3). May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + */ + export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export function realpath(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + export function realpath(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Synchronous realpath(3). Returns the resolved path. + * + * Only paths that can be converted to UTF8 strings are supported. + */ + export function realpathSync(path: string | Buffer): string; + export function realpathSync(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' })): Buffer; + export function realpathSync(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null): string; + + /** + * Asynchronous rename(2). + */ + export function rename(oldPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous rename(2). + */ + export function renameSync(oldPath: string | Buffer, newPath: string | Buffer): void; + + /** + * Asynchronous rmdir(2). + */ + export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous rmdir(2). + */ + export function rmdirSync(path: string | Buffer): void; + + /** + * Asynchronous stat(2). + * + * In case of an error, the `err.code` will be one of Common System Errors. + * + * Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, `fs.access()` is recommended. + */ + export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous stat(2). + */ + export function statSync(path: string | Buffer): Stats; + + /** + * Asynchronous symlink(2). The type argument is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the target argument will automatically be normalized to absolute path. + */ + export function symlink(target: string | Buffer, path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function symlink(target: string | Buffer, path: string | Buffer, type: 'dir' | 'file' | 'junction', callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous symlink(2). + */ + export function symlinkSync(target: string | Buffer, path: string | Buffer, type?: 'dir' | 'file' | 'junction'): void; + + /** + * Asynchronous truncate(2). + */ + export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous truncate(2). + */ + export function truncateSync(path: string | Buffer, len?: number): void; + + /** + * Asynchronous unlink(2). + */ + export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous unlink(2). + */ + export function unlinkSync(path: string | Buffer): void; + + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed and you have effectively stopped watching `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. + * + * Note: `fs.watch()` is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + */ + export function unwatchFile(filename: string | Buffer, listener?: WatchListener): void; + + /** + * Change file timestamps of the file referenced by the supplied path. + * + * Note: the arguments `atime` and `mtime` of the following related functions follow these rules: + * + * - The value should be a Unix timestamp in seconds. For example, `Date.now()` returns milliseconds, so it should be divided by 1000 before passing it in. + * If the value is a numeric string like `'123456789'`, the value will get converted to the corresponding number. + * If the value is `NaN` or `Infinity`, the value will get converted to `Date.now() / 1000`. + */ + export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.utimes()`. + */ + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + + export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. default = `true`. */ - export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path + persistent?: boolean; + /** + * Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See Caveats). default = `false`. */ - export function rmdirSync(path: string | Buffer): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + recursive?: boolean; + /** + * Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`. */ - export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + encoding?: buffer.Encoding; + } + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a `fs.FSWatcher`. + * + * Please note the listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but they are not the same thing. + */ + export function watch(filename: string | Buffer): FSWatcher; + export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null): FSWatcher; + export function watch(filename: string | Buffer, listener: WatchListener): FSWatcher; + export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null, listener: WatchListener): FSWatcher; + + export interface WatchFileOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched */ - export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + persistent: boolean; + /** + * Indicates how often the target should be polled in milliseconds. The default is `5007`. */ - export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: string): void; - /* - * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @param callback The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; - /* - * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @returns Returns the created folder path. - */ - export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; - export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - */ - export function readFileSync(filename: string, encoding: string): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; - export function existsSync(path: string | Buffer): boolean; + interval: number; + } - export namespace constants { - // File Access Constants + /** + * Watch for changes on filename. The callback listener will be called each time the file is accessed. + * + * Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. + * + * Note: `fs.watch()` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + */ + export function watchFile(filename: string | Buffer, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string | Buffer, options: WatchFileOptions | null, listener: (curr: Stats, prev: Stats) => void): void; - /** Constant for fs.access(). File is visible to the calling process. */ - export const F_OK: number; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` and `length` determine the part of the buffer to be written. + * + * `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2). + * + * Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. + */ + export function write(fd: number, buffer: string | Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + export function write(fd: number, data: string | Buffer, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + export function write(fd: number, data: string | Buffer, position: number, encoding: buffer.Encoding, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - /** Constant for fs.access(). File can be read by the calling process. */ - export const R_OK: number; + export interface WriteFileOptions { + encoding?: buffer.Encoding; + mode?: number; + flag?: string; + } - /** Constant for fs.access(). File can be written by the calling process. */ - export const W_OK: number; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * + * Note that it is unsafe to use `fs.writeFile` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. + * + * Note: If a file descriptor is specified as the `file`, it will not be closed automatically. + */ + export function writeFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function writeFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | WriteFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; - /** Constant for fs.access(). File can be executed by the calling process. */ - export const X_OK: number; + /** + * The synchronous version of `fs.writeFile()`. + */ + export function writeFileSync(file: string | Buffer | number, data: string | Buffer, options?: buffer.Encoding | WriteFileOptions | null): void; - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - export const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - export const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - export const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - export const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - export const O_EXCL: number; - - /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ - export const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - export const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - export const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - export const O_DIRECTORY: number; - - /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ - export const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - export const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - export const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - export const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - export const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - export const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - export const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - export const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - export const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - export const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - export const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - export const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - export const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - export const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - export const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - export const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - export const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - export const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - export const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - export const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - export const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - export const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - export const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - export const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - export const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - export const S_IXOTH: number; - } - - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode?: number): void; - export function createReadStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - }): ReadStream; - export function createWriteStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - }): WriteStream; - export function fdatasync(fd: number, callback: Function): void; - export function fdatasyncSync(fd: number): void; + /** + * Synchronous `fs.write`. + */ + export function writeSync(fd: number, buffer: string | Buffer, offset: number, length: number, position?: number): void; + export function writeSync(fd: number, data: string | Buffer, position?: number, encoding?: buffer.Encoding): void; } declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { /** - * A parsed path object generated by path.parse() or consumed by path.format(). + * The root of the path such as '/' or 'c:\' */ - export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths paths to join. - */ export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: any[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ + export function resolve(...pathSegments: string[]): string; + export function isAbsolute(p: string): boolean; export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + export module win32 { + export function normalize(p: string): string; + export function join(...paths: string[]): string; + export function resolve(...pathSegments: string[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - end(buffer?: Buffer): string; - } - export var StringDecoder: { - new (encoding?: string): NodeStringDecoder; - }; + import * as buffer from "buffer"; + + export class StringDecoder { + /** + * @param encoding The character encoding the `StringDecoder` will use. Defaults to `'utf8'`. + */ + constructor(encoding?: buffer.Encoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * + * @param buffer A `Buffer` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * + * @param buffer A `Buffer` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; + export var CLIENT_RENEG_LIMIT: number; + export var CLIENT_RENEG_WINDOW: number; + export var SLAB_BUFFER_SIZE: number; + export var DEFAULT_CIPHERS: string; + export var DEFAULT_ECDH_CURVE: string; - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } + export class Server extends net.Server { + /** + * The `server.addContext()` method adds a secure context that will be used if the client request's SNS hostname matches the supplied `hostname` (or wildcard). + * + * @param hostname A SNI hostname or wildcard (e.g. `'*'`) + * @param options An object containing any of the possible properties from the `tls.createSecureContext()` options arguments + */ + addContext(hostName: string, options: SecureContextOptions): void; + /** + * Returns a `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets. + */ + getTicketKeys(): Buffer; + /** + * Updates the keys for encryption/decryption of the TLS Session Tickets. + * + * Note: The key's Buffer should be 48 bytes long. See ticketKeys option in tls.createServer for more information on how it is used. + * + * Note: Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * Returns the current number of concurrent connections on the server. + */ + connections: number; + } - export interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } - export class TLSSocket extends stream.Duplex { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket:net.Socket, options?: { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext, - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean, - /** - * An optional net.Server instance. - */ - server?: net.Server, - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean, - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. Defaults to false. - */ - rejectUnauthorized?: boolean, - /** - * An array of strings or a Buffer naming possible NPN protocols. - * (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer, - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) When the server - * receives both NPN and ALPN extensions from the client, ALPN takes - * precedence over NPN and the server does not send an NPN extension - * to the client. - */ - ALPNProtocols?: string[] | Buffer, - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: Function, - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer, - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean - }); - /** - * Returns the bound address, the address family name and port of the underlying socket as reported by - * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. - */ - address(): { port: number; family: string; address: string }; - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {any} - An object representing the peer's certificate. - */ - getPeerCertificate(detailed?: boolean): { - subject: Certificate; - issuerInfo: Certificate; - issuer: Certificate; - raw: any; - valid_from: string; - valid_to: string; - fingerprint: string; - serialNumber: string; - }; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): any; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): any; - /** - * The string representation of the local IP address. - */ - localAddress: string; - /** - * The numeric representation of the local port. - */ - localPort: string; - /** - * The string representation of the remote IP address. - * For example, '74.125.127.100' or '2001:4860:a005::68'. - */ - remoteAddress: string; - /** - * The string representation of the remote IP family. 'IPv4' or 'IPv6'. - */ - remoteFamily: string; - /** - * The numeric representation of the remote port. For example, 443. - */ - remotePort: number; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - */ - renegotiate(options: TlsOptions, callback: (err: Error) => any): any; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; + export interface Cipher { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } - /** - * events.EventEmitter - * 1. OCSPResponse - * 2. secureConnect - **/ - addListener(event: string, listener: Function): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; + export interface EphemeralKeyInfo { + type: 'DH' | 'ECDH'; + name?: string; + size: number; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; + export interface PeerCertificate { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: Buffer; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + } - on(event: string, listener: Function): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; + export interface TLSSocketOptions { + /** + * An optional TLS context object from `tls.createSecureContext()`. + */ + secureContext?: SecureContext; + /** + * If true the TLS socket will be instantiated in server-mode. Defaults to `false`. + */ + isServer?: boolean; + /** + * An optional net.Server instance. + */ + server?: net.Server; + /** + * Optional, see `tls.createServer()`. + */ + requestCert?: boolean; + /** + * Optional, see `tls.createServer()`. + */ + rejectUnauthorized?: boolean; + /** + * Optional, see `tls.createServer()`. + */ + NPNProtocols?: string[] | Buffer; + /** + * Optional, see `tls.createServer()`. + */ + ALPNProtocols?: string[] | Buffer; + /** + * Optional, see `tls.createServer()`. + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer; + /** + * If `true`, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean; + } - once(event: string, listener: Function): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; + export interface RenegotiateOptions { + rejectUnauthorized?: boolean; + requestCert?: boolean; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; + export class TLSSocket extends net.Socket { + /** + * Construct a new `tls.TLSSocket` object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. + */ + authorizationError?: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. + */ + encrypted: true; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version that first defined the cipher. + */ + getCipher(): Cipher; + /** + * Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in Perfect Forward Secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + */ + getEphemeralKeyInfo(): EphemeralKeyInfo; + /** + * Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. + * + * @param detailed Specify `true` to request that the full certificate chain with the `issuer` property be returned; false to return only the top certificate without the `issuer` property. + */ + getPeerCertificate(detailed?: boolean): PeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. The value `null` will be returned for server sockets or disconnected client sockets. + */ + getProtocol(): string | null; + /** + * Returns the ASN.1 encoded TLS session or `undefined` if no session was negotiated. Can be used to speed up handshake establishment when reconnecting to the server. + */ + getSession(): Buffer | undefined; + /** + * Returns the TLS session ticket or `undefined` if no session was negotiated. + * + * Note: This only works with client TLS sockets. Useful only for debugging, for session reuse `provide` session option to `tls.connect()`. + */ + getTLSTicket(): Buffer | undefined; + /** + * Returns the string representation of the local IP address. + */ + localAddress: string; + /** + * Returns the numeric representation of the local port. + */ + localPort: number; + /** + * Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. + */ + remoteAddress: string; + /** + * Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * + * Note: This method can be used to request a peer's certificate after the secure connection has been established. + * + * Note: When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + */ + renegotiate(options: RenegotiateOptions, callback: (err: Error | null) => any): any; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. Returns `true` if setting the limit succeeded; false otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. + * + * @param size The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + } - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - } + export interface ConnectOptions { + /** + * Host the client should connect to. + */ + host?: string; + /** + * Port the client should connect to. + */ + port?: number | string; + /** + * Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored. + */ + socket?: net.Socket; + /** + * Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + */ + path?: string; + /** + * A `string` or `Buffer` containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format. + */ + pfx?: string | Buffer; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s containing the private key of the client in PEM format. + */ + key?: string | Buffer | string[] | Buffer[]; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s containing the certificate key of the client in PEM format. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * A string describing the ciphers to use or exclude, separated by `:`. Uses the same default cipher suite as `tls.createServer()`. + */ + ciphers?: string; + /** + * If true, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. + */ + rejectUnauthorized?: boolean; + /** + * An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. + */ + NPNProtocols?: string[] | Buffer[]; + /** + * An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.) + */ + ALPNProtocols?: string[] | Buffer[]; + /** + * Server name for the SNI (Server Name Indication) TLS extension. + */ + servername?: string; + /** + * A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. + */ + checkServerIdentity?: (servername: string, cert: Buffer) => void; + /** + * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + /** + * An optional TLS context object as returned by from `tls.createSecureContext( ... )`. It can be used for caching client certificates, keys, and CA certificates. + */ + secureContext?: SecureContext; + /** + * A `Buffer` instance, containing TLS session. + */ + session?: Buffer; + /** + * Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. + */ + minDHSize?: number; + } - export interface TlsOptions { - host?: string; - port?: number; - pfx?: string | Buffer[]; - key?: string | string[] | Buffer | any[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | string[] | Buffer | Buffer[]; - crl?: string | string[]; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer; - SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; - ecdhCurve?: string; - dhparam?: string | Buffer; - handshakeTimeout?: number; - ALPNProtocols?: string[] | Buffer; - sessionTimeout?: number; - ticketKeys?: any; - sessionIdContext?: string; - secureProtocol?: string; - } + export interface SecureContextOptions { + /** + * A string or `Buffer` holding the PFX or PKCS12 encoded private key, certificate, and CA certificates. + */ + pfx?: string | Buffer; + /** + * The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as an array of key strings or as an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. + */ + key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string containing the PEM encoded certificate. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). + */ + crl?: string | string[]; + /** + * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. + */ + ciphers?: string; + /** + * If `true`, when a cipher is being selected, the server's preferences will be used instead of the client preferences. + */ + honorCipherOrder?: boolean; + } - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: string | Buffer - key?: string | string[] | Buffer | Buffer[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | Buffer | (string | Buffer)[]; - rejectUnauthorized?: boolean; - NPNProtocols?: (string | Buffer)[]; - servername?: string; - path?: string; - ALPNProtocols?: (string | Buffer)[]; - checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; - secureProtocol?: string; - secureContext?: Object; - session?: Buffer; - minDHSize?: number; - } + export interface CreateServerOptions { + /** + * A `string` or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert`, and `ca` options.) + */ + pfx?: string | Buffer; + /** + * The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. + */ + key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string containing the PEM encoded certificate. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). + */ + crl?: string | string[]; + /** + * A string describing the ciphers to use or exclude, separated by `:`. + */ + ciphers?: string; + /** + * A string describing a named curve to use for ECDH key agreement or false to disable ECDH. Defaults to `prime256v1` (NIST P-256). Use crypto.getCurves() to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. + */ + ecdhCurve?: string; + /** + * A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer; + /** + * Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. + */ + handshakeTimeout?: number; + /** + * When choosing a cipher, use the server's preferences instead of the client preferences. Defaults to `true`. + */ + honorCipherOrder?: boolean; + /** + * If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. + */ + requestCert?: boolean; + /** + * If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`. + */ + rejectUnauthorized?: boolean; + /** + * An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer; + /** + * An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. + */ + ALPNProtocols?: string[] | Buffer; + /** + * A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + /** + * An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See SSL_CTX_set_timeout for more details. + */ + sessionTimeout?: number; + /** + * A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. Note that this is automatically shared between `cluster` module workers. + */ + ticketKeys?: Buffer; + /** + * A string containing an opaque identifier for session resumption. If `requestCert` is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided. + */ + sessionIdContext?: string; + /** + * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + } - export interface Server extends net.Server { - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; + export interface SecureContext { + context: any; + } - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - **/ - addListener(event: string, listener: Function): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + /** + * Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the `'secureConnection'` event. + */ + export function createServer(options: CreateServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - emit(event: string, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; - emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + /** + * Creates a new client connection to the given `port` and `host` or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.) + */ + export function connect(options: ConnectOptions, callback?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectOptions, callback?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectOptions, callback?: () => void): TLSSocket; - on(event: string, listener: Function): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + /** + * The `tls.createSecureContext()` method creates a credentials object. + * + * If the `'ca'` option is not given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. + */ + export function createSecureContext(options: SecureContextOptions): SecureContext; - once(event: string, listener: Function): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - } - - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[] - ciphers?: string; - honorCipherOrder?: boolean; - } - - export interface SecureContext { - context: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported SSL ciphers. + */ + export function getCiphers(): string[]; } declare module "crypto" { - export interface Certificate { - exportChallenge(spkac: string | Buffer): Buffer; - exportPublicKey(spkac: string | Buffer): Buffer; - verifySpkac(spkac: Buffer): boolean; - } - export var Certificate: { - new (): Certificate; - (): Certificate; - } + import * as stream from "stream"; - export var fips: boolean; + export var constants: { + defaultCipherList: string; + defaultCoreCipherList: string; + [key: string]: string | number; + } - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string | Buffer): Hmac; + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + export class Certificate { + constructor(); + exportChallenge(spkac: string | Buffer, encoding?: string): string; + exportPublicKey(spkac: string | Buffer, encoding?: string): Buffer; + verifySpkac(spkac: Buffer): boolean; + } - export interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hash; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hmac; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - getAuthTag(): Buffer; - setAAD(buffer: Buffer): void; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; - update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - setAuthTag(tag: Buffer): void; - setAAD(buffer: Buffer): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer): Signer; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer): Verify; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: string, signature: Buffer): boolean; - verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; - } - export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; - export function createDiffieHellman(prime: Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - export interface DiffieHellman { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer): void; - setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: string): void; - verifyError: number; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export interface RsaPublicKey { - key: string; - padding?: number; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: number; - } - export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; - export interface ECDH { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - export function createECDH(curve_name: string): ECDH; - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export var DEFAULT_ENCODING: string; + export function createHash(algorithm: string): Hash; + + export class Hash extends stream.Transform { + update(data: string | Buffer, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): string; + digest(): Buffer; + } + + export function createHmac(algorithm: string, key: string | Buffer): Hmac; + + export class Hmac extends stream.Transform { + update(data: string | Buffer, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): string; + digest(): Buffer; + } + + export function createCipher(algorithm: string, password: string | Buffer): Cipher; + export function createCipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Cipher; + + export class Cipher extends stream.Transform { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary" | "latin1" | "base64" | "hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1", output_encoding: "binary" | "latin1" | "base64" | "hex"): string; + final(): Buffer; + final(output_encoding: string): string; + setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; + } + + export function createDecipher(algorithm: string, password: string | Buffer): Decipher; + export function createDecipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Decipher; + + export class Decipher extends stream.Transform { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; + update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; + final(): Buffer; + final(output_encoding: string): string; + setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; + } + + export function createSign(algorithm: string): Signer; + + export class Signer extends stream.Writable { + update(data: string | Buffer): void; + sign(private_key: string): Buffer; + sign(private_key: string, output_format: string): string; + } + + export function createVerify(algorith: string): Verify; + + export class Verify extends stream.Writable { + update(data: string | Buffer): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + + export function createDiffieHellman(prime: number, prime_encoding?: string, generator?: number | string | Buffer, generator_encoding?: string): DiffieHellman; + export function createDiffieHellman(prime_length: number, generator?: number | string | Buffer): DiffieHellman; + export function getDiffieHellman(group_name: string): DiffieHellman; + + export class DiffieHellman { + verifyError: number; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + generateKeys(encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding?: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + + export function createECDH(curve_name: string): ECDH; + + export class ECDH { + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + generateKeys(encoding?: string, format?: string): string; + getPrivateKey(encoding?: string): string; + getPublicKey(encoding?: string, format?: string): string; + setPrivateKey(private_key: string, encoding?: string): void; + } + + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => void): void; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => void): void; + + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + + export interface RsaKey { + key: string; + passphrase?: string, + padding?: number; + } + + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export function publicEncrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; + export function privateEncrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; + export function publicDecrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; + export function privateDecrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; + + export function setEngine(engine: string, flags?: number): void; } declare module "stream" { - import * as events from "events"; + import * as events from "events"; - class internal extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - namespace internal { + export class Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } - export class Stream extends internal { } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (this: Readable, size?: number) => any; + } - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (size?: number) => any; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + isPaused(): boolean; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - protected _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. readable - * 5. error - **/ - addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + setDefaultEncoding(encoding: string): this; + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements Writable { + writable: boolean; + constructor(opts?: DuplexOptions); + setDefaultEncoding(encoding: string): this; + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; + export interface TransformOptions extends ReadableOptions, WritableOptions { + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; + export class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + } - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "drain", chunk: Buffer | string): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - // Readable - pause(): this; - resume(): this; - // Writeable - writable: boolean; - constructor(opts?: DuplexOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends DuplexOptions { - transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; - } - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - protected _transform(chunk: any, encoding: string, callback: Function): void; - protected _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform { } - } - - export = internal; + export class PassThrough extends Transform { } } declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; + /** + * The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` environment variable. If the `section` name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op. + */ + export function debuglog(section: string): (msg: any, ...args: any[]) => void; + + export interface InspectOptions { + /** + * If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. + */ + showHidden?: boolean; + /** + * Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. + */ + depth?: number | null; + /** + * If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see "Customizing util.inspect colors". + */ + colors?: boolean; + /** + * If `false`, then custom `inspect(depth, opts)` functions exported on the object being inspected will not be called. Defaults to `true`. + */ + customInspect?: boolean; + /** + * If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. + */ + showProxy?: boolean; + /** + * Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. + */ + maxArrayLength?: number | null; + /** + * The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to `60` for legacy compatibility. + */ + breakLength?: number; + } + + /** + * The `util.inspect()` method returns a string representation of object that is primarily useful for debugging. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + + export namespace inspect { + export var colors: { + bold: [number, number]; + italic: [number, number]; + underline: [number, number]; + inverse: [number, number]; + white: [number, number]; + grey: [number, number]; + black: [number, number]; + blue: [number, number]; + cyan: [number, number]; + green: [number, number]; + magenta: [number, number]; + red: [number, number]; + yellow: [number, number]; } - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key: string): (msg: string, ...param: any[]) => void; - export function isBoolean(object: any): boolean; - export function isBuffer(object: any): boolean; - export function isFunction(object: any): boolean; - export function isNull(object: any): boolean; - export function isNullOrUndefined(object: any): boolean; - export function isNumber(object: any): boolean; - export function isObject(object: any): boolean; - export function isPrimitive(object: any): boolean; - export function isString(object: any): boolean; - export function isSymbol(object: any): boolean; - export function isUndefined(object: any): boolean; - export function deprecate(fn: Function, message: string): Function; + export var styles: { + special: string; + number: string; + boolean: string; + undefined: string; + null: string; + string: string; + symbol: string; + date: string; + regexp: string; + }; + + export var custom: symbol; + } + + /** + * The `util.deprecate()` method wraps the given function or class in such a way that it is marked as deprecated. + */ + export function deprecate(fn: T, string: string): T; + + /** + * The `util.format()` method returns a formatted string using the first argument as a printf-like format. + */ + export function format(format: any, ...param: any[]): string; + + /** + * Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor. + */ + export function inherits(constructor: any, superConstructor: any): void; + + /** + * Deprecated predecessor of `console.error`. + * + * @deprecated + */ + export function debug(string: string): void; + + /** + * Deprecated predecessor of `console.error`. + * + * @deprecated + */ + export function error(...strings: string[]): void; + + /** + * Internal alias for `Array.isArray`. + * + * @deprecated + */ + export function isArray(object: any): object is any[]; + + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isBoolean(object: any): object is boolean; + + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isBuffer(object: any): object is Buffer; + + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isDate(object: any): object is Date; + + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isError(object: any): object is Error; + + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isFunction(object: any): object is Function; + + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNull(object: any): object is null; + + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNullOrUndefined(object: any): object is null | undefined; + + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNumber(object: any): object is number; + + /** + * Returns true if the given `object` is strictly an `Object` and not a `Function`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isObject(object: any): object is Object; + + /** + * Returns true if the given `object` is a primitive type. Otherwise, returns `false`. + * + * @deprecated + */ + export function isPrimitive(object: any): object is string | number | boolean | null | undefined; + + /** + * Returns true if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isRegExp(object: any): object is RegExp; + + /** + * Returns true if the given `object` is a `String`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isString(object: any): object is string; + + /** + * Returns true if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isSymbol(object: any): object is symbol; + + /** + * Returns true if the given `object` is `undefined`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isUndefined(object: any): object is symbol; + + /** + * The `util.log()` method prints the given `string` to `stdout` with an included timestamp. + * + * @deprecated + */ + export function log(string: string): void; + + /** + * Deprecated predecessor of `console.log`. + * + * @deprecated + */ + export function print(strings: string[]): void; + + /** + * Deprecated predecessor of `console.log`. + * + * @deprecated + */ + export function puts(strings: string[]): void; + + /** + * The `util._extend()` method was never intended to be used outside of internal Node.js modules. The community found and used it anyway. + * + * It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through `Object.assign()`. + * + * @deprecated + */ + export function _extend(target: T, source: U): T & U; } declare module "assert" { - function internal(value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function - }); - } - - export function fail(actual: any, expected: any, message: string, operator: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); } - export = internal; + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; } declare module "tty" { - import * as net from "net"; + import * as net from "net"; - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } } declare module "domain" { - import * as events from "events"; + import * as events from "events"; - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - members: any[]; - enter(): void; - exit(): void; - } + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + members: any[]; + enter(): void; + exit(): void; + } - export function create(): Domain; + export function create(): Domain; } declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; - export var SIGQUIT: number; - export var SIGTRAP: number; - export var SIGIOT: number; - export var SIGBUS: number; - export var SIGUSR1: number; - export var SIGUSR2: number; - export var SIGPIPE: number; - export var SIGALRM: number; - export var SIGCHLD: number; - export var SIGSTKFLT: number; - export var SIGCONT: number; - export var SIGSTOP: number; - export var SIGTSTP: number; - export var SIGTTIN: number; - export var SIGTTOU: number; - export var SIGURG: number; - export var SIGXCPU: number; - export var SIGXFSZ: number; - export var SIGVTALRM: number; - export var SIGPROF: number; - export var SIGIO: number; - export var SIGPOLL: number; - export var SIGPWR: number; - export var SIGSYS: number; - export var SIGUNUSED: number; - export var defaultCoreCipherList: string; - export var defaultCipherList: string; - export var ENGINE_METHOD_RSA: number; - export var ALPN_ENABLED: number; + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; +} + +declare module "module" { + export = NodeModule; } declare module "process" { - export = process; -} - -declare module "v8" { - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - - const enum DoesZapCodeSpaceFlag { - Disabled = 0, - Enabled = 1 - } - - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - } - - export function getHeapStatistics(): HeapInfo; - export function getHeapSpaceStatistics(): HeapSpaceInfo[]; - export function setFlagsFromString(flags: string): void; + export = process; } declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - export function clearImmediate(immediateId: any): void; -} - -declare module "console" { - export = console; -} - -/** - * _debugger module is not documented. - * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js - */ -declare module "_debugger" { - export interface Packet { - raw: string; - headers: string[]; - body: Message; - } - - export interface Message { - seq: number; - type: string; - } - - export interface RequestInfo { - command: string; - arguments: any; - } - - export interface Request extends Message, RequestInfo { - } - - export interface Event extends Message { - event: string; - body?: any; - } - - export interface Response extends Message { - request_seq: number; - success: boolean; - /** Contains error message if success === false. */ - message?: string; - /** Contains message body if success === true. */ - body?: any; - } - - export interface BreakpointMessageBody { - type: string; - target: number; - line: number; - } - - export class Protocol { - res: Packet; - state: string; - execute(data: string): void; - serialize(rq: Request): string; - onResponse: (pkt: Packet) => void; - } - - export var NO_FRAME: number; - export var port: number; - - export interface ScriptDesc { - name: string; - id: number; - isNative?: boolean; - handle?: number; - type: string; - lineOffset?: number; - columnOffset?: number; - lineCount?: number; - } - - export interface Breakpoint { - id: number; - scriptId: number; - script: ScriptDesc; - line: number; - condition?: string; - scriptReq?: string; - } - - export interface RequestHandler { - (err: boolean, body: Message, res: Packet): void; - request_seq?: number; - } - - export interface ResponseBodyHandler { - (err: boolean, body?: any): void; - request_seq?: number; - } - - export interface ExceptionInfo { - text: string; - } - - export interface BreakResponse { - script?: ScriptDesc; - exception?: ExceptionInfo; - sourceLine: number; - sourceLineText: string; - sourceColumn: number; - } - - export function SourceInfo(body: BreakResponse): string; - - export interface ClientInstance extends NodeJS.EventEmitter { - protocol: Protocol; - scripts: ScriptDesc[]; - handles: ScriptDesc[]; - breakpoints: Breakpoint[]; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceLineText: string; - currentFrame: number; - currentScript: string; - - connect(port: number, host: string): void; - req(req: any, cb: RequestHandler): void; - reqFrameEval(code: string, frame: number, cb: RequestHandler): void; - mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; - setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; - clearBreakpoint(rq: Request, cb: RequestHandler): void; - listbreakpoints(cb: RequestHandler): void; - reqSource(from: number, to: number, cb: RequestHandler): void; - reqScripts(cb: any): void; - reqContinue(cb: RequestHandler): void; - } - - export var Client : { - new (): ClientInstance - } + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function clearImmediate(immediateId: NodeJS.Immediate): void; } From 41da5eb070a6578eb8cbef441d8bc474908d91e7 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 01:30:51 +0300 Subject: [PATCH 04/85] Fixed @node/node interface according to official API. Resolving #13782 Changed api: stream.Readable, Renamed: NodeJS.Console to NodeJS.ConsoleConstructor Reconciled all consequent interfaces, like writeStream etc. --- node/index.d.ts | 7241 +++++++++++++++++++++++++---------------------- 1 file changed, 3797 insertions(+), 3444 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index e6333dd7d1..0620b9df9a 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -8,162 +8,37 @@ * Node.js v6.x API * * * ************************************************/ -interface NodeError { - /** - * Returns a string describing the point in the code at which the Error was instantiated. - * - * For example: - * - * ``` - * Error: Things keep happening! - * at /home/gbusey/file.js:525:2 - * at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) - * at Actor. (/home/gbusey/actors.js:400:8) - * at increaseSynergy (/home/gbusey/actors.js:701:6) - * ``` - * - * The first line is formatted as : , and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. - */ - stack?: string; - /** - * Returns the string description of error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace. - * - * ``` - * const err = new Error('The message'); - * console.log(err.message); - * // Prints: The message - * ``` - */ - message: string; +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + assert(value: any, message?: string, ...optionalParams: any[]): void; + dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; + error(message?: any, ...optionalParams: any[]): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + time(label: string): void; + timeEnd(label: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; } -interface Error extends NodeError { } +interface Error { + stack?: string; +} interface ErrorConstructor { - /** - * Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()`` was called. - * - * ```js - * const myObject = {}; - * Error.captureStackTrace(myObject); - * myObject.stack // similar to `new Error().stack` - * ``` - * - * The first line of the trace, instead of being prefixed with `ErrorType : message`, will be the result of calling `targetObject.toString()``. - * - * The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace. - * - * The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance: - * - * ```js - * function MyError() { - * Error.captureStackTrace(this, MyError); - * } - * - * // Without passing MyError to captureStackTrace, the MyError - * // frame would should up in the .stack property. by passing - * // the constructor, we omit that frame and all frames above it. - * new MyError().stack - * ``` - */ - captureStackTrace(targetObject: T, constructorOpt?: new () => T): void; - - /** - * The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj))``. - * - * The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. - * - * If set to a non-number value, or set to a negative number, stack traces will not capture any frames. - */ - stackTraceLimit: number; + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; } -// ES2015 collection types -interface NodeCollection { - size: number; -} - -interface NodeWeakCollection {} - -interface IterableIterator {} - -interface NodeCollectionConstructor { - prototype: T; -} - -interface Map extends NodeCollection { - clear(): void; - delete(key: K): boolean; - entries(): Array<[K, V]>; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; - get(key: K): V; - has(key: K): boolean; - keys(): Array; - set(key: K, value?: V): Map; - values(): Array; - // [Symbol.iterator]():Array<[K,V]>; - // [Symbol.toStringTag]: "Map"; -} - -interface MapConstructor extends NodeCollectionConstructor> { - new (): Map; - new (): Map; -} - -declare var Map: MapConstructor; - -interface WeakMap extends NodeWeakCollection { - clear(): void; - delete(key: K): boolean; - get(key: K): V | void; - has(key: K): boolean; - set(key: K, value?: V): WeakMap; -} - -interface WeakMapConstructor extends NodeCollectionConstructor> { - new (): WeakMap; - new (): WeakMap; -} - -declare var WeakMap: WeakMapConstructor; - -interface Set extends NodeCollection { - add(value: T): Set; - clear(): void; - delete(value: T): boolean; - entries(): Array<[T, T]>; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - keys(): Array; - values(): Array; - // [Symbol.iterator]():Array; - // [Symbol.toStringTag]: "Set"; -} - -interface SetConstructor extends NodeCollectionConstructor> { - new (): Set; - new (): Set; - new (iterable: Array): Set; -} - -declare var Set: SetConstructor; - -interface WeakSet extends NodeWeakCollection { - add(value: T): WeakSet; - clear(): void; - delete(value: T): boolean; - has(value: T): boolean; - // [Symbol.toStringTag]: "WeakSet"; -} - -interface WeakSetConstructor extends NodeCollectionConstructor> { - new (): WeakSet; - new (): WeakSet; - new (iterable: Array): WeakSet; -} - -declare var WeakSet: WeakSetConstructor; +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } /************************************************ * * @@ -172,6 +47,7 @@ declare var WeakSet: WeakSetConstructor; ************************************************/ declare var process: NodeJS.Process; declare var global: NodeJS.Global; +declare var console: Console; declare var __filename: string; declare var __dirname: string; @@ -184,44 +60,26 @@ declare function setImmediate(callback: (...args: any[]) => void, ...args: any[] declare function clearImmediate(immediateId: any): void; interface NodeRequireFunction { - (id: string): any; + (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; - cache: { [filename: string]: NodeModule }; - extensions: NodeExtensions; - main: any; -} - -interface NodeExtensions { - '.js': (m: NodeModule, filename: string) => any; - '.json': (m: NodeModule, filename: string) => any; - '.node': (m: NodeModule, filename: string) => any; - [ext: string]: (m: NodeModule, filename: string) => any; + resolve(id: string): string; + cache: any; + extensions: any; + main: NodeModule | undefined; } declare var require: NodeRequire; -declare class NodeModule { - static runMain(): void; - static wrap(code: string): string; - static _nodeModulePaths(path: string): string[]; - static _load(request: string, parent?: NodeModule, isMain?: boolean): any; - static _resolveFilename(request: string, parent?: NodeModule, isMain?: boolean): string; - static _extensions: NodeExtensions; - - constructor(filename: string); - _compile(code: string, filename: string): string; - - id: string; - parent: NodeModule; - filename: string; - paths: string[]; - children: NodeModule[]; - exports: any; - loaded: boolean; - require: NodeRequireFunction; +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; } declare var module: NodeModule; @@ -229,209 +87,159 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; }; -// Console class (compatible with TypeScript `lib.d.ts`). -declare interface Console { - log(msg: any, ...params: any[]): void; - info(msg: any, ...params: any[]): void; - warn(msg: any, ...params: any[]): void; - error(msg: any, ...params: any[]): void; - dir(value: any, ...params: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(msg: any, ...params: any[]): void; - assert(test?: boolean, msg?: string, ...params: any[]): void; - Console: new (stdout: NodeJS.WritableStream) => Console; -} +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer { } -declare var console: Console; - -declare class Buffer extends Uint8Array { - [index: number]: number; - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor(str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor(arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor(array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor(buffer: Buffer); - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be _zero-filled_. - * - * @param size The desired length of the new `Buffer` - * @param fill A value to pre-fill the new `Buffer` with. Default: `0` - * @param encoding If `fill` is a string, this is its encoding. Default: `'utf8'` - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new _non-zero-filled_ `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `buffer.kMaxLength`. Otherwise, a `RangeError` is thrown. A zero-length `Buffer` will be created if `size <= 0`. - * - * The underlying memory for `Buffer` instances created in this way is not initialized. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize such `Buffer` instances to zeroes. - * - * @param size The desired length of the new `Buffer` - */ - static allocUnsafe(size: number): Buffer; - /** - * Returns `true` if `obj` is a Buffer, `false` otherwise. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise. - * - * @param encoding A character encoding name to check. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - swap16(): this; - swap32(): this; - swap64(): this; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - entries(): IterableIterator<[number, number]>; - keys(): IterableIterator; - values(): IterableIterator; -} +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + new (arrayBuffer: ArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + new (buffer: Buffer): Buffer; + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; +}; /************************************************ * * @@ -439,244 +247,301 @@ declare class Buffer extends Uint8Array { * * ************************************************/ declare namespace NodeJS { - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } + export interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream): Console; + } - export interface EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - listenerCount(type: string): number; - } + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - isPaused(): boolean; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } + export class EventEmitter { + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + eventNames(): (string | symbol)[]; + } - export interface WritableStream extends EventEmitter { - writable: boolean; - setDefaultEncoding(encoding: string): this; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface ReadableStream extends EventEmitter { + readable: boolean; + isTTY?: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } - export interface ReadWriteStream extends ReadableStream, WritableStream { } + export interface WritableStream extends EventEmitter { + writable: boolean; + isTTY?: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - export interface Events extends EventEmitter { } + export interface ReadWriteStream extends ReadableStream, WritableStream { } - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; + export interface Events extends EventEmitter { } - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } - export interface Env { - PATH: string; - [key: string]: string; - } + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } - export interface Versions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } + export interface CpuUsage { + user: number; + system: number; + } - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - argv0: string; - /** - * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. - */ - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: Env; - exit(code?: number): void; - exitCode?: number; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: Versions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): MemoryUsage; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + exitCode: number; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: string; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } - export interface Timer { - ref(): void; - unref(): void; - _called: boolean; - _onTimeout: Function; - _timerArgs?: any[]; - } + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } - export interface Immediate { - _argv?: any[]; - _callback: Function; - _onImmediate: Function; - } + export interface Timer { + ref(): void; + unref(): void; + } +} + +interface IterableIterator { } + +/** + * @deprecated + */ +interface NodeBuffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; } /************************************************ @@ -685,3078 +550,3566 @@ declare namespace NodeJS { * * ************************************************/ declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - export var kMaxLength: number; - - export type Encoding = "ascii" | "latin1" | "binary" | "utf8" | "utf-8" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "hex" | "base64"; - - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } + export interface StringifyOptions { + encodeURIComponent?: Function; + } - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated - static defaultMaxListeners: number; + class internal extends NodeJS.EventEmitter { } - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Array<(...args: any[]) => void>; - listenerCount(event: string): number; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - } + namespace internal { + export class EventEmitter extends internal { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated + static defaultMaxListeners: number; - export interface Listener { - on(event: E, listener: L): this; - once(event: E, listener: L): this; - addListener(event: E, listener: L): this; - removeListener(event: E, listener: L): this; - listeners(event: E): L[]; - } + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): (string | symbol)[]; + listenerCount(type: string | symbol): number; + } + } + + export = internal; } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; - export interface OutgoingHeaders { - [header: string]: number | string | string[]; - } + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent | boolean; + } - export interface IncomingHeaders { - [header: string]: string | string[]; - } - - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number | string; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: OutgoingHeaders; - auth?: string; - agent?: Agent | boolean; - } - - export class Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - listening: boolean; - } - - export class ServerResponse extends stream.Writable { - finished: boolean; - headersSent: boolean; - statusCode: number; - statusMessage: string; - sendDate: boolean; - - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHeaders): void; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: () => void): this; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: OutgoingHeaders): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export class ClientRequest extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export class IncomingMessage extends stream.Readable { - httpVersion: string; - headers: IncomingHeaders; - rawHeaders: string[]; - trailers: IncomingHeaders; - rawTrailers: string[]; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - destroy(error?: Error): void; + export interface Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + listening: boolean; + } /** - * Only valid for request obtained from http.Server. + * @deprecated Use IncomingMessage */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - } + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - export interface AgentOptions { + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: Function): ServerResponse; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + finished: boolean; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends stream.Readable { + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false + * @deprecated Use IncomingMessage */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } + export interface ClientResponse extends IncomingMessage { } - export class Agent { - maxSockets: number; - sockets: any; - requests: any; + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } - constructor(opts?: AgentOptions); + export class Agent { + maxSockets: number; + sockets: any; + requests: any; - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } + constructor(opts?: AgentOptions); - export var METHODS: string[]; + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; + export var METHODS: string[]; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } + // interfaces + export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } - export interface Address { - address: string; - port: number; - addressType: string; - } + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; + } - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker - }; + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string, listener: Function): boolean + emit(event: "disconnect", listener: () => void): boolean + emit(event: "error", listener: (code: number, signal: string) => void): boolean + emit(event: "exit", listener: (code: number, signal: string) => void): boolean + emit(event: "listening", listener: (address: Address) => void): boolean + emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean + emit(event: "online", listener: () => void): boolean + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string, listener: Function): boolean; + emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + emit(event: "fork", listener: (worker: Worker) => void): boolean; + emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + emit(event: "online", listener: (worker: Worker) => void): boolean; + emit(event: "setup", listener: (settings: any) => void): boolean; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback?: Function): void; + export function fork(env?: any): Worker; + export var isMaster: boolean; + export var isWorker: boolean; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function emit(event: string, listener: Function): boolean; + export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + export function emit(event: "fork", listener: (worker: Worker) => void): boolean; + export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + export function emit(event: "online", listener: (worker: Worker) => void): boolean; + export function emit(event: "setup", listener: (settings: any) => void): boolean; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; + export function listeners(event: string): Function[]; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { - import * as stream from "stream"; + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; finishFlush?: number } - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - export interface ZlibCallback { (error: Error, result: any): void } + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; + export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function deflate(buf: Buffer | string, callback?: ZlibCallback): void; - export function deflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; - export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; - export function gzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function gzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function gzipSync(buf: Buffer | string, options?: ZlibOptions): any; - export function gunzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function gunzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): any; - export function inflate(buf: Buffer | string, callback?: ZlibCallback): void; - export function inflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function inflateSync(buf: Buffer | string, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; - export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; - export function unzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function unzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function unzipSync(buf: Buffer | string, options?: ZlibOptions): any; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function hostname(): string; + export function loadavg(): number[]; + export function uptime(): number; + export function freemem(): number; + export function totalmem(): number; + export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }, }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): "BE" | "LE"; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): CpuInfo[]; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function userInfo(options?: { encoding: 'buffer' }): { username: Buffer, uid: number, gid: number, shell: Buffer | null, homedir: Buffer } - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: string | null, homedir: string } - export var EOL: string; + export function arch(): string; + export function platform(): string; + export function tmpdir(): string; + export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; + } - export interface RequestOptions extends http.RequestOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer | string[] | Buffer[]; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } + export interface RequestOptions extends http.RequestOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } - export interface AgentOptions extends http.AgentOptions { - /** - * Certificate, Private key and CA certificates to use for SSL. Default `null`. - */ - pfx?: string | Buffer; - /** - * Private key to use for SSL. Default `null`. - */ - key?: string | Buffer | string[] | Buffer[]; - /** - * A string of passphrase for the private key or pfx. Default `null`. - */ - passphrase?: string; - /** - * Public x509 certificate to use. Default `null`. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. - */ - ciphers?: string; - /** - * If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default `true`. - */ - rejectUnauthorized?: boolean; - /** - * Servername for SNI (Server Name Indication) TLS extension. - */ - servername?: string; - /** - * The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - maxCachedSessions?: number; - } + export interface Agent extends http.Agent { } - export class Agent extends http.Agent { - constructor(options?: AgentOptions); - } + export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + maxCachedSessions?: number; + } - export class Server extends tls.Server { } - - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export var globalAgent: Agent; + export var Agent: { + new (options?: AgentOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; } declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; } declare module "repl" { - import { EventEmitter } from "events"; - import { Interface } from "readline"; + import * as stream from "stream"; + import * as readline from "readline"; - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: symbol; - breakEvalOnSigint?: boolean; - } + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; + } - export function start(options: ReplOptions): REPLServer; + export interface REPLServer extends readline.ReadLine { + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void; - export type REPLCommand = (this: REPLServer, rest: string) => void; + /** + * events.EventEmitter + * 1. exit + * 2. reset + **/ - export class REPLServer extends Interface { - inputStream: NodeJS.ReadableStream; - outputStream: NodeJS.WritableStream; - useColors: boolean; - commands: { - [command: string]: REPLCommand; - }; - defineCommand(keyword: string, cmd: REPLCommand | { help: string, action: REPLCommand }): void; - displayPrompt(preserveCursor?: boolean): void; - setPrompt(prompt: string): void; - turnOffEditorMode(): void; - } + addListener(event: string, listener: Function): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: Function): this; - export class Recoverable extends SyntaxError { - err: Error; - constructor(err: Error); - } + emit(event: string, ...args: any[]): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: any): boolean; + + on(event: string, listener: Function): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: Function): this; + + once(event: string, listener: Function): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: Function): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: Function): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: Function): this; + } + + export function start(options: ReplOptions): REPLServer; } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; + import * as events from "events"; + import * as stream from "stream"; - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } - export class Interface extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): this; - resume(): this; - close(): void; - write(data: string | Buffer, key?: Key): void; - } + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + close(): void; + write(data: string | Buffer, key?: Key): void; - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + **/ - export interface CompleterResult { - completions: string[]; - line: string; - } + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: any) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; - export interface InterfaceOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: any): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface; - export function createInterface(options: InterfaceOptions): Interface; + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: any) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: any) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: any) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: any) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export type CompleterResult = [string[], string]; + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } - - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - - export interface RunInNewContextOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - - export interface RunInContextOptions extends RunInNewContextOptions { - breakOnSigint?: boolean; - } - - export class Script { - constructor(code: string, options?: string | ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunInContextOptions): any; - runInNewContext(sandbox?: Context, options?: RunInNewContextOptions): any; - runInThisContext(options?: RunInNewContextOptions): any; - } - - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: string | RunInNewContextOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: string | RunInNewContextOptions): any; - export function runInThisContext(code: string, options?: string | RunInNewContextOptions): any; - /** - * @deprecated - */ - export function createScript(code: string, options?: string | ScriptOptions): Script; + export interface Context { } + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as buffer from "buffer"; - import * as net from "net"; + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; - export class ChildProcess extends events.EventEmitter implements - events.Listener<'close', (code: number, signal: string) => void>, - events.Listener<'error', (error: Error) => void>, - events.Listener<'exit', ((code: number, signal: string | null) => void) | ((code: number | null, signal: string) => void)>, - events.Listener<'message', (message: any, sendHandle?: net.Socket | net.Server) => void>, - events.Listener<'disconnect', () => void> { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle?: any): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - } + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } + /** + * events.EventEmitter + * 1. close + * 2. disconnet + * 3. error + * 4. exit + * 5. message + **/ - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnet", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - encoding?: buffer.Encoding | 'buffer'; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnet"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + on(event: string, listener: Function): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnet", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - encoding?: buffer.Encoding | 'buffer'; - } + once(event: string, listener: Function): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnet", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnet", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnet", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - shell?: boolean | string; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptions & { encoding: 'buffer' }): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string | any; - slashes?: boolean; - hash?: string; - path?: string; - } + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; - export function format(url: Url | string): string; - export function resolve(from: string, to: string): string; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export interface MxRecord { + exchange: string, + priority: number + } - export const NODATA: 'ENODATA'; - export const FORMERR: 'EFORMERR'; - export const SERVFAIL: 'ESERVFAIL'; - export const NOTFOUND: 'ENOTFOUND'; - export const NOTIMP: 'ENOTIMP'; - export const REFUSED: 'EREFUSED'; - export const BADQUERY: 'EBADQUERY'; - export const BADNAME: 'EBADNAME'; - export const BADFAMILY: 'EBADFAMILY'; - export const BADRESP: 'EBADRESP'; - export const CONNREFUSED: 'ECONNREFUSED'; - export const TIMEOUT: 'ETIMEOUT'; - export const EOF: 'EOF'; - export const FILE: 'EFILE'; - export const NOMEM: 'ENOMEM'; - export const DESTRUCTION: 'EDESTRUCTION'; - export const BADSTR: 'EBADSTR'; - export const BADFLAGS: 'EBADFLAGS'; - export const NONAME: 'ENONAME'; - export const BADHINTS: 'EBADHINTS'; - export const NOTINITIALIZED: 'ENOTINITIALIZED'; - export const LOADIPHLPAPI: 'ELOADIPHLPAPI'; - export const ADDRGETNETWORKPARAMS: 'EADDRGETNETWORKPARAMS'; - export const CANCELLED: 'ECANCELLED'; + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; } declare module "net" { - import * as stream from "stream"; + import * as stream from "stream"; + import * as events from "events"; - export class Socket extends stream.Duplex { - constructor(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }); + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): this; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + destroyed: boolean; - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; - export class Server extends Socket { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): this; - listen(port: number, hostname?: string, listeningListener?: Function): this; - listen(port: number, backlog?: number, listeningListener?: Function): this; - listen(port: number, listeningListener?: Function): this; - listen(path: string, backlog?: number, listeningListener?: Function): this; - listen(path: string, listeningListener?: Function): this; - listen(handle: any, backlog?: number, listeningListener?: Function): this; - listen(handle: any, listeningListener?: Function): this; - listen(options: ListenOptions, listeningListener?: Function): this; - close(callback?: () => void): this; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): this; - unref(): this; - maxConnections: number; - connections: number; - } + on(event: string, listener: Function): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; + once(event: string, listener: Function): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; + maxConnections: number; + connections: number; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; } declare module "dgram" { - import * as events from "events"; + import * as events from "events"; - export interface RemoteInfo { - address: string; - port: number; - size: number; - } + interface RemoteInfo { + address: string; + family: string; + port: number; + } - export interface AddressInfo { - address: string; - family: string; - port: number; - } + interface AddressInfo { + address: string; + family: string; + port: number; + } - export interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - export interface SocketOptions { - type: string; - reuseAddr?: boolean; - } + interface SocketOptions { + type: "udp4" | "udp6"; + reuseAddr?: boolean; + } - export function createSocket(type: string | SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export class Socket extends events.EventEmitter { - send(msg: Buffer | string | Array, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(msg: Buffer | string | Array, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - bind(options: BindOptions, callback?: () => void): void; - close(callback?: () => void): void; - setTTL(ttl: number): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): void; - unref(): void; - } + export interface Socket extends events.EventEmitter { + send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: any): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import * as buffer from "buffer"; + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + } + + export interface ReadStream extends stream.Readable { + close(): void; + destroy(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } - /** - * Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type. - */ - export class Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; /** - * "Access Time" - Time when file data last accessed. Changed by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. */ - atime: Date; + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** - * "Modified Time" - Time when file data last modified. Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. + * Synchronous rename + * @param oldPath + * @param newPath */ - mtime: Date; - /** - * "Change Time" - Time when file status was last changed (inode data modification). Changed by the `chmod(2)`, `chown(2)`, `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`,` utimes(2)`, `read(2)`, and `write(2)` system calls. + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string | Buffer, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string | Buffer, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string | Buffer, mode: number): void; + export function chmodSync(path: string | Buffer, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string | Buffer, mode: number): void; + export function lchmodSync(path: string | Buffer, mode: string): void; + export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string | Buffer): Stats; + export function lstatSync(path: string | Buffer): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; + export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; + export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string | Buffer): string; + export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - ctime: Date; - /** - * "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the `utimes(2)` system call. + export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path */ - birthtime: Date; - } - - export type WatchListener = (eventType: string, filename?: string | Buffer) => void; - - /** - * Objects returned from fs.watch() are of this type. - */ - export class FSWatcher extends events.EventEmitter implements - events.Listener<'change', WatchListener> { - close(): void; - } - - export class ReadStream extends stream.Readable implements - events.Listener<'open', (fd: number) => void>, - events.Listener<'close', () => void> { - bytesRead: number; - path: string | Buffer; - close(): void; - destroy(): void; - } - - export class WriteStream extends stream.Writable implements - events.Listener<'open', (fd: number) => void>, - events.Listener<'close', () => void> { - close(): void; - bytesWritten: number; - path: string | Buffer; - } - - export const F_OK: number; - export const R_OK: number; - export const W_OK: number; - export const X_OK: number; - - export const constants: { - O_RDONLY: number; - O_WRONLY: number; - O_RDWR: number; - S_IFMT: number; - S_IFREG: number; - S_IFDIR: number; - S_IFCHR: number; - S_IFBLK: number; - S_IFIFO: number; - S_IFLNK: number; - S_IFSOCK: number; - O_CREAT: number; - O_EXCL: number; - O_NOCTTY: number; - O_TRUNC: number; - O_APPEND: number; - O_DIRECTORY: number; - O_NOFOLLOW: number; - O_SYNC: number; - O_SYMLINK: number; - O_NONBLOCK: number; - S_IRWXU: number; - S_IRUSR: number; - S_IWUSR: number; - S_IXUSR: number; - S_IRWXG: number; - S_IRGRP: number; - S_IWGRP: number; - S_IXGRP: number; - S_IRWXO: number; - S_IROTH: number; - S_IWOTH: number; - S_IXOTH: number; - F_OK: number; - R_OK: number; - W_OK: number; - X_OK: number; - [key: string]: number; - } - - /** - * Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of `mode`. It is possible to create a mask consisting of the bitwise OR of two or more values. - */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.access()`. This throws if any accessibility checks fail, and does nothing otherwise. - */ - export function accessSync(path: string | Buffer, mode?: number): void; - - export interface AppendFileOptions { - encoding?: buffer.Encoding; - mode?: number; - flag?: string; - } - - /** - * Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a buffer. - */ - export function appendFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function appendFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | AppendFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * The synchronous version of `fs.appendFile()`. - */ - export function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: AppendFileOptions | null): void; - - /** - * Asynchronous chmod(2). - */ - export function chmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous chmod(2). - */ - export function chmodSync(path: string | Buffer, mode: number): void; - - /** - * Asynchronous chown(2). - */ - export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous chown(2). - */ - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - - /** - * Asynchronous close(2). - */ - export function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous close(2). - */ - export function closeSync(fd: number): void; - - export interface ReadStreamOptions { - flags?: string; - encoding?: buffer.Encoding; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - } - - /** - * Returns a new ReadStream object. - * - * Be aware that, unlike the default value set for `highWaterMark` on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter. - */ - export function createReadStream(path: string | Buffer, options?: ReadStreamOptions | null): ReadStream; - - export interface WriteStreamOptions { - flags?: string; - defaultEncoding?: buffer.Encoding; - fd?: number; - mode?: number; - autoClose?: boolean; - start: number; - end: number; - } - - /** - * Returns a new WriteStream object. - */ - export function createWriteStream(path: string | Buffer, options?: WriteStreamOptions | null): WriteStream; - - /** - * Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. - * - * @deprecated - */ - export function exists(path: string | Buffer, callback: (exists: boolean) => void): void; - - /** - * Synchronous version of `fs.exists()`. Returns true if the file exists, false otherwise. - */ - export function existsSync(path: string | Buffer): boolean; - - /** - * Asynchronous fchmod(2). - */ - export function fchmod(fd: number, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fchmod(2). - */ - export function fchmodSync(fd: number, mode: number): void; - - /** - * Asynchronous fchown(2). - */ - export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fchown(2). - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous fdatasync(2). - */ - export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fdatasync(2). - */ - export function fdatasyncSync(fd: number): void; - - /** - * Asynchronous fstat(2). - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous fstat(2). - */ - export function fstatSync(fd: number): Stats; - - /** - * Asynchronous fsync(2). - */ - export function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fsync(2). - */ - export function fsyncSync(fd: number): void; - - /** - * Asynchronous ftruncate(2). - * - * If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. - * - * If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes ('\0'). - */ - export function ftruncate(fd: number, len: number | null | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous ftruncate(2). - */ - export function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Change the file timestamps of a file referenced by the supplied file descriptor. - */ - export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.futimes()`. - */ - export function futimesSync(fd: number, atime: number, mtime: number): void; - - /** - * Asynchronous lchmod(2). - * - * Only available on Mac OS X. - * - * @deprecated - */ - export function lchmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous lchmod(2). - * - * @deprecated - */ - export function lchmodSync(path: string | Buffer, mode: number): void; - - /** - * Asynchronous lchown(2). - * - * @deprecated - */ - export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous lchown(2). - * - * @deprecated - */ - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - - /** - * Asynchronous link(2). - */ - export function link(existingPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous link(2). - */ - export function linkSync(existingPath: string | Buffer, newPath: string | Buffer): void; - - /** - * Asynchronous lstat(2). `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. - */ - export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous lstat(2). - */ - export function lstatSync(path: string | Buffer): Stats; - - /** - * Asynchronous mkdir(2). `mode` defaults to `0o777`. - */ - export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function mkdir(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous mkdir(2). - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - - export interface MkdtempOptions { - encoding: buffer.Encoding; - } - - /** - * Creates a unique temporary directory. - * - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; - export function mkdtemp(prefix: string, options: buffer.Encoding | MkdtempOptions | null, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; - - /** - * The synchronous version of fs.mkdtemp(). Returns the created folder path. - */ - export function mkdtempSync(prefix: string, options?: buffer.Encoding | MkdtempOptions | null): string; - - /** - * Asynchronous file open. See open(2). `flags` can be: - * - * 'r' - Open file for reading. An exception occurs if the file does not exist. - * - * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist. - * - * 'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. - * - * This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. - * - * Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()` - * - * 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). - * - * 'wx' - Like `'w'` but fails if `path` exists. - * - * 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). - * - * 'wx+' - Like `'w+'` but fails if `path` exists. - * - * 'a' - Open file for appending. The file is created if it does not exist. - * - * 'ax' - Like 'a' but fails if `path` exists. - * - * 'a+' - Open file for reading and appending. The file is created if it does not exist. - * - * 'ax+' - Like 'a+' but fails if `path` exists. - * - * `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writable. - */ - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Synchronous version of `fs.open()`. - */ - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - - /** - * Read data from the file specified by fd. - * - * @param buffer is the buffer that the data will be written to. - * @param offset is the offset in the buffer to start writing at. - * @param length is an integer specifying the number of bytes to read. - * @param position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. - */ - export function read(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; - - export interface ReaddirOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous readdir(3). Reads the contents of a directory. - * - * @param files is an array of the names of the files in the directory excluding '.' and '..'. - */ - export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - export function readdir(path: string | Buffer, options: 'buffer' | (ReadFileOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - export function readdir(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'. - */ - export function readdirSync(path: string | Buffer): string[]; - export function readdirSync(path: string | Buffer, options: 'buffer' | (ReaddirOptions & { encoding: 'buffer' })): Buffer[]; - export function readdirSync(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null): string[]; - - export interface ReadFileOptions { - encoding?: buffer.Encoding | 'buffer'; - flag?: string; - } - - /** - * Asynchronously reads the entire contents of a file. - */ - export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - export function readFile(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding }), callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - export function readFile(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Synchronous version of `fs.readFile`. - */ - export function readFileSync(file: string | Buffer | number): Buffer; - export function readFileSync(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding })): string; - export function readFileSync(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null): Buffer; - - export interface ReadlinkOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous readlink(2). - */ - export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - export function readlink(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - export function readlink(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Synchronous readlink(2). - */ - export function readlinkSync(path: string | Buffer): string; - export function readlinkSync(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' })): Buffer; - export function readlinkSync(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null): string; - - /** - * Synchronous version of `fs.read()`. - */ - export function readSync(fd: number, buffer: string | Buffer, offset: number, length: number, position: number): number; - - export interface RealpathOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous realpath(3). May use `process.cwd` to resolve relative paths. - * - * Only paths that can be converted to UTF8 strings are supported. - */ - export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - export function realpath(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - export function realpath(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Synchronous realpath(3). Returns the resolved path. - * - * Only paths that can be converted to UTF8 strings are supported. - */ - export function realpathSync(path: string | Buffer): string; - export function realpathSync(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' })): Buffer; - export function realpathSync(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null): string; - - /** - * Asynchronous rename(2). - */ - export function rename(oldPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous rename(2). - */ - export function renameSync(oldPath: string | Buffer, newPath: string | Buffer): void; - - /** - * Asynchronous rmdir(2). - */ - export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous rmdir(2). - */ - export function rmdirSync(path: string | Buffer): void; - - /** - * Asynchronous stat(2). - * - * In case of an error, the `err.code` will be one of Common System Errors. - * - * Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. - * - * To check if a file exists without manipulating it afterwards, `fs.access()` is recommended. - */ - export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous stat(2). - */ - export function statSync(path: string | Buffer): Stats; - - /** - * Asynchronous symlink(2). The type argument is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the target argument will automatically be normalized to absolute path. - */ - export function symlink(target: string | Buffer, path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function symlink(target: string | Buffer, path: string | Buffer, type: 'dir' | 'file' | 'junction', callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous symlink(2). - */ - export function symlinkSync(target: string | Buffer, path: string | Buffer, type?: 'dir' | 'file' | 'junction'): void; - - /** - * Asynchronous truncate(2). - */ - export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous truncate(2). - */ - export function truncateSync(path: string | Buffer, len?: number): void; - - /** - * Asynchronous unlink(2). - */ - export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous unlink(2). - */ - export function unlinkSync(path: string | Buffer): void; - - /** - * Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed and you have effectively stopped watching `filename`. - * - * Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. - * - * Note: `fs.watch()` is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. - */ - export function unwatchFile(filename: string | Buffer, listener?: WatchListener): void; - - /** - * Change file timestamps of the file referenced by the supplied path. - * - * Note: the arguments `atime` and `mtime` of the following related functions follow these rules: - * - * - The value should be a Unix timestamp in seconds. For example, `Date.now()` returns milliseconds, so it should be divided by 1000 before passing it in. - * If the value is a numeric string like `'123456789'`, the value will get converted to the corresponding number. - * If the value is `NaN` or `Infinity`, the value will get converted to `Date.now() / 1000`. - */ - export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.utimes()`. - */ - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - - export interface WatchOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched. default = `true`. + export function unlinkSync(path: string | Buffer): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - persistent?: boolean; - /** - * Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See Caveats). default = `false`. + export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path */ - recursive?: boolean; - /** - * Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`. + export function rmdirSync(path: string | Buffer): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - encoding?: buffer.Encoding; - } - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a `fs.FSWatcher`. - * - * Please note the listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but they are not the same thing. - */ - export function watch(filename: string | Buffer): FSWatcher; - export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null): FSWatcher; - export function watch(filename: string | Buffer, listener: WatchListener): FSWatcher; - export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null, listener: WatchListener): FSWatcher; - - export interface WatchFileOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched + export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. */ - persistent: boolean; - /** - * Indicates how often the target should be polled in milliseconds. The default is `5007`. + export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. */ - interval: number; - } + export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: string): void; + /* + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + /* + * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @returns Returns the created folder path. + */ + export function mkdtempSync(prefix: string): string; + export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string | Buffer): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; + export function existsSync(path: string | Buffer): boolean; - /** - * Watch for changes on filename. The callback listener will be called each time the file is accessed. - * - * Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. - * - * Note: `fs.watch()` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. - */ - export function watchFile(filename: string | Buffer, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string | Buffer, options: WatchFileOptions | null, listener: (curr: Stats, prev: Stats) => void): void; + export namespace constants { + // File Access Constants - /** - * Write `buffer` to the file specified by `fd`. - * - * `offset` and `length` determine the part of the buffer to be written. - * - * `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2). - * - * Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. - * - * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. - */ - export function write(fd: number, buffer: string | Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - export function write(fd: number, data: string | Buffer, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - export function write(fd: number, data: string | Buffer, position: number, encoding: buffer.Encoding, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + /** Constant for fs.access(). File is visible to the calling process. */ + export const F_OK: number; - export interface WriteFileOptions { - encoding?: buffer.Encoding; - mode?: number; - flag?: string; - } + /** Constant for fs.access(). File can be read by the calling process. */ + export const R_OK: number; - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * - * Note that it is unsafe to use `fs.writeFile` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. - * - * Note: If a file descriptor is specified as the `file`, it will not be closed automatically. - */ - export function writeFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function writeFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | WriteFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** Constant for fs.access(). File can be written by the calling process. */ + export const W_OK: number; - /** - * The synchronous version of `fs.writeFile()`. - */ - export function writeFileSync(file: string | Buffer | number, data: string | Buffer, options?: buffer.Encoding | WriteFileOptions | null): void; + /** Constant for fs.access(). File can be executed by the calling process. */ + export const X_OK: number; - /** - * Synchronous `fs.write`. - */ - export function writeSync(fd: number, buffer: string | Buffer, offset: number, length: number, position?: number): void; - export function writeSync(fd: number, data: string | Buffer, position?: number, encoding?: buffer.Encoding): void; + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + export const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + export const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + export const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + export const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + export const O_EXCL: number; + + /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ + export const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + export const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + export const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + export const O_DIRECTORY: number; + + /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ + export const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + export const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + export const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + export const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + export const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + export const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + export const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + export const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + export const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + export const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + export const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + export const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + export const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + export const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + export const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + export const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + export const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + export const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + export const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + export const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + export const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + export const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + export const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + export const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + export const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + export const S_IXOTH: number; + } + + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string | Buffer, mode?: number): void; + export function createReadStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + }): ReadStream; + export function createWriteStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + export function fdatasync(fd: number, callback: Function): void; + export function fdatasyncSync(fd: number): void; } declare module "path" { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - export interface ParsedPath { /** - * The root of the path such as '/' or 'c:\' + * A parsed path object generated by path.parse() or consumed by path.format(). */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ - export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ - export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; - - export module posix { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ export function join(...paths: string[]): string; - export function resolve(...pathSegments: string[]): string; - export function isAbsolute(p: string): boolean; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; - export module win32 { - export function normalize(p: string): string; - export function join(...paths: string[]): string; - export function resolve(...pathSegments: string[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { - import * as buffer from "buffer"; - - export class StringDecoder { - /** - * @param encoding The character encoding the `StringDecoder` will use. Defaults to `'utf8'`. - */ - constructor(encoding?: buffer.Encoding); - /** - * Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. - * - * @param buffer A `Buffer` containing the bytes to decode. - */ - write(buffer: Buffer): string; - /** - * Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding. - * - * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. - * - * @param buffer A `Buffer` containing the bytes to decode. - */ - end(buffer?: Buffer): string; - } + export interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + export var StringDecoder: { + new (encoding?: string): NodeStringDecoder; + }; } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; - export var CLIENT_RENEG_LIMIT: number; - export var CLIENT_RENEG_WINDOW: number; - export var SLAB_BUFFER_SIZE: number; - export var DEFAULT_CIPHERS: string; - export var DEFAULT_ECDH_CURVE: string; + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; - export class Server extends net.Server { - /** - * The `server.addContext()` method adds a secure context that will be used if the client request's SNS hostname matches the supplied `hostname` (or wildcard). - * - * @param hostname A SNI hostname or wildcard (e.g. `'*'`) - * @param options An object containing any of the possible properties from the `tls.createSecureContext()` options arguments - */ - addContext(hostName: string, options: SecureContextOptions): void; - /** - * Returns a `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets. - */ - getTicketKeys(): Buffer; - /** - * Updates the keys for encryption/decryption of the TLS Session Tickets. - * - * Note: The key's Buffer should be 48 bytes long. See ticketKeys option in tls.createServer for more information on how it is used. - * - * Note: Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys. - */ - setTicketKeys(keys: Buffer): void; - /** - * Returns the current number of concurrent connections on the server. - */ - connections: number; - } + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } - export interface Cipher { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } + export class TLSSocket extends stream.Duplex { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket:net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: Function, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + /** + * Returns the bound address, the address family name and port of the underlying socket as reported by + * the operating system. + * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + */ + address(): { port: number; family: string; address: string }; + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param {boolean} detailed - If true; the full chain with issuer property will be returned. + * @returns {any} - An object representing the peer's certificate. + */ + getPeerCertificate(detailed?: boolean): { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: any; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + }; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns {any} - TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * The string representation of the local IP address. + */ + localAddress: string; + /** + * The numeric representation of the local port. + */ + localPort: string; + /** + * The string representation of the remote IP address. + * For example, '74.125.127.100' or '2001:4860:a005::68'. + */ + remoteAddress: string; + /** + * The string representation of the remote IP family. 'IPv4' or 'IPv6'. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: TlsOptions, callback: (err: Error) => any): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns {boolean} - Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; - export interface EphemeralKeyInfo { - type: 'DH' | 'ECDH'; - name?: string; - size: number; - } + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; - export interface PeerCertificate { - subject: Certificate; - issuerInfo: Certificate; - issuer: Certificate; - raw: Buffer; - valid_from: string; - valid_to: string; - fingerprint: string; - serialNumber: string; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; - export interface TLSSocketOptions { - /** - * An optional TLS context object from `tls.createSecureContext()`. - */ - secureContext?: SecureContext; - /** - * If true the TLS socket will be instantiated in server-mode. Defaults to `false`. - */ - isServer?: boolean; - /** - * An optional net.Server instance. - */ - server?: net.Server; - /** - * Optional, see `tls.createServer()`. - */ - requestCert?: boolean; - /** - * Optional, see `tls.createServer()`. - */ - rejectUnauthorized?: boolean; - /** - * Optional, see `tls.createServer()`. - */ - NPNProtocols?: string[] | Buffer; - /** - * Optional, see `tls.createServer()`. - */ - ALPNProtocols?: string[] | Buffer; - /** - * Optional, see `tls.createServer()`. - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer; - /** - * If `true`, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean; - } + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; - export interface RenegotiateOptions { - rejectUnauthorized?: boolean; - requestCert?: boolean; - } + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; - export class TLSSocket extends net.Socket { - /** - * Construct a new `tls.TLSSocket` object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: TLSSocketOptions); - /** - * Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. - */ - authorized: boolean; - /** - * Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. - */ - authorizationError?: Error; - /** - * Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. - */ - encrypted: true; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version that first defined the cipher. - */ - getCipher(): Cipher; - /** - * Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in Perfect Forward Secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. - */ - getEphemeralKeyInfo(): EphemeralKeyInfo; - /** - * Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. - * - * @param detailed Specify `true` to request that the full certificate chain with the `issuer` property be returned; false to return only the top certificate without the `issuer` property. - */ - getPeerCertificate(detailed?: boolean): PeerCertificate; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. The value `null` will be returned for server sockets or disconnected client sockets. - */ - getProtocol(): string | null; - /** - * Returns the ASN.1 encoded TLS session or `undefined` if no session was negotiated. Can be used to speed up handshake establishment when reconnecting to the server. - */ - getSession(): Buffer | undefined; - /** - * Returns the TLS session ticket or `undefined` if no session was negotiated. - * - * Note: This only works with client TLS sockets. Useful only for debugging, for session reuse `provide` session option to `tls.connect()`. - */ - getTLSTicket(): Buffer | undefined; - /** - * Returns the string representation of the local IP address. - */ - localAddress: string; - /** - * Returns the numeric representation of the local port. - */ - localPort: number; - /** - * Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. - */ - remoteAddress: string; - /** - * Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. - */ - remoteFamily: string; - /** - * The numeric representation of the remote port. For example, 443. - */ - remotePort: number; - /** - * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. - * - * Note: This method can be used to request a peer's certificate after the secure connection has been established. - * - * Note: When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. - */ - renegotiate(options: RenegotiateOptions, callback: (err: Error | null) => any): any; - /** - * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. Returns `true` if setting the limit succeeded; false otherwise. - * - * Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. - * - * @param size The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. - */ - setMaxSendFragment(size: number): boolean; - } + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; - export interface ConnectOptions { - /** - * Host the client should connect to. - */ - host?: string; - /** - * Port the client should connect to. - */ - port?: number | string; - /** - * Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored. - */ - socket?: net.Socket; - /** - * Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - */ - path?: string; - /** - * A `string` or `Buffer` containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format. - */ - pfx?: string | Buffer; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s containing the private key of the client in PEM format. - */ - key?: string | Buffer | string[] | Buffer[]; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s containing the certificate key of the client in PEM format. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * A string describing the ciphers to use or exclude, separated by `:`. Uses the same default cipher suite as `tls.createServer()`. - */ - ciphers?: string; - /** - * If true, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. - */ - rejectUnauthorized?: boolean; - /** - * An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. - */ - NPNProtocols?: string[] | Buffer[]; - /** - * An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.) - */ - ALPNProtocols?: string[] | Buffer[]; - /** - * Server name for the SNI (Server Name Indication) TLS extension. - */ - servername?: string; - /** - * A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. - */ - checkServerIdentity?: (servername: string, cert: Buffer) => void; - /** - * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - /** - * An optional TLS context object as returned by from `tls.createSecureContext( ... )`. It can be used for caching client certificates, keys, and CA certificates. - */ - secureContext?: SecureContext; - /** - * A `Buffer` instance, containing TLS session. - */ - session?: Buffer; - /** - * Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. - */ - minDHSize?: number; - } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } - export interface SecureContextOptions { - /** - * A string or `Buffer` holding the PFX or PKCS12 encoded private key, certificate, and CA certificates. - */ - pfx?: string | Buffer; - /** - * The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as an array of key strings or as an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. - */ - key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string containing the PEM encoded certificate. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). - */ - crl?: string | string[]; - /** - * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. - */ - ciphers?: string; - /** - * If `true`, when a cipher is being selected, the server's preferences will be used instead of the client preferences. - */ - honorCipherOrder?: boolean; - } + export interface TlsOptions { + host?: string; + port?: number; + pfx?: string | Buffer[]; + key?: string | string[] | Buffer | any[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | string[] | Buffer | Buffer[]; + crl?: string | string[]; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; + ecdhCurve?: string; + dhparam?: string | Buffer; + handshakeTimeout?: number; + ALPNProtocols?: string[] | Buffer; + sessionTimeout?: number; + ticketKeys?: any; + sessionIdContext?: string; + secureProtocol?: string; + } - export interface CreateServerOptions { - /** - * A `string` or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert`, and `ca` options.) - */ - pfx?: string | Buffer; - /** - * The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. - */ - key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string containing the PEM encoded certificate. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). - */ - crl?: string | string[]; - /** - * A string describing the ciphers to use or exclude, separated by `:`. - */ - ciphers?: string; - /** - * A string describing a named curve to use for ECDH key agreement or false to disable ECDH. Defaults to `prime256v1` (NIST P-256). Use crypto.getCurves() to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. - */ - ecdhCurve?: string; - /** - * A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. - */ - dhparam?: string | Buffer; - /** - * Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. - */ - handshakeTimeout?: number; - /** - * When choosing a cipher, use the server's preferences instead of the client preferences. Defaults to `true`. - */ - honorCipherOrder?: boolean; - /** - * If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. - */ - requestCert?: boolean; - /** - * If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`. - */ - rejectUnauthorized?: boolean; - /** - * An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer; - /** - * An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. - */ - ALPNProtocols?: string[] | Buffer; - /** - * A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - /** - * An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See SSL_CTX_set_timeout for more details. - */ - sessionTimeout?: number; - /** - * A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. Note that this is automatically shared between `cluster` module workers. - */ - ticketKeys?: Buffer; - /** - * A string containing an opaque identifier for session resumption. If `requestCert` is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided. - */ - sessionIdContext?: string; - /** - * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - } + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: string | Buffer + key?: string | string[] | Buffer | Buffer[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | Buffer | (string | Buffer)[]; + rejectUnauthorized?: boolean; + NPNProtocols?: (string | Buffer)[]; + servername?: string; + path?: string; + ALPNProtocols?: (string | Buffer)[]; + checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; + secureProtocol?: string; + secureContext?: Object; + session?: Buffer; + minDHSize?: number; + } - export interface SecureContext { - context: any; - } + export interface Server extends net.Server { + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; - /** - * Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the `'secureConnection'` event. - */ - export function createServer(options: CreateServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - /** - * Creates a new client connection to the given `port` and `host` or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.) - */ - export function connect(options: ConnectOptions, callback?: () => void): TLSSocket; - export function connect(port: number, options?: ConnectOptions, callback?: () => void): TLSSocket; - export function connect(port: number, host?: string, options?: ConnectOptions, callback?: () => void): TLSSocket; + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - /** - * The `tls.createSecureContext()` method creates a credentials object. - * - * If the `'ca'` option is not given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. - */ - export function createSecureContext(options: SecureContextOptions): SecureContext; + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - /** - * Returns an array with the names of the supported SSL ciphers. - */ - export function getCiphers(): string[]; + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; } declare module "crypto" { - import * as stream from "stream"; + export interface Certificate { + exportChallenge(spkac: string | Buffer): Buffer; + exportPublicKey(spkac: string | Buffer): Buffer; + verifySpkac(spkac: Buffer): boolean; + } + export var Certificate: { + new (): Certificate; + (): Certificate; + } - export var constants: { - defaultCipherList: string; - defaultCoreCipherList: string; - [key: string]: string | number; - } + export var fips: boolean; - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string | Buffer): Hmac; - export class Certificate { - constructor(); - exportChallenge(spkac: string | Buffer, encoding?: string): string; - exportPublicKey(spkac: string | Buffer, encoding?: string): Buffer; - verifySpkac(spkac: Buffer): boolean; - } + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - export function createHash(algorithm: string): Hash; - - export class Hash extends stream.Transform { - update(data: string | Buffer, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): string; - digest(): Buffer; - } - - export function createHmac(algorithm: string, key: string | Buffer): Hmac; - - export class Hmac extends stream.Transform { - update(data: string | Buffer, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): string; - digest(): Buffer; - } - - export function createCipher(algorithm: string, password: string | Buffer): Cipher; - export function createCipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Cipher; - - export class Cipher extends stream.Transform { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary" | "latin1" | "base64" | "hex"): string; - update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1", output_encoding: "binary" | "latin1" | "base64" | "hex"): string; - final(): Buffer; - final(output_encoding: string): string; - setAAD(buffer: Buffer): void; - setAutoPadding(auto_padding: boolean): void; - getAuthTag(): Buffer; - } - - export function createDecipher(algorithm: string, password: string | Buffer): Decipher; - export function createDecipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Decipher; - - export class Decipher extends stream.Transform { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; - update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; - final(): Buffer; - final(output_encoding: string): string; - setAAD(buffer: Buffer): void; - setAutoPadding(auto_padding: boolean): void; - setAuthTag(tag: Buffer): void; - } - - export function createSign(algorithm: string): Signer; - - export class Signer extends stream.Writable { - update(data: string | Buffer): void; - sign(private_key: string): Buffer; - sign(private_key: string, output_format: string): string; - } - - export function createVerify(algorith: string): Verify; - - export class Verify extends stream.Writable { - update(data: string | Buffer): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - - export function createDiffieHellman(prime: number, prime_encoding?: string, generator?: number | string | Buffer, generator_encoding?: string): DiffieHellman; - export function createDiffieHellman(prime_length: number, generator?: number | string | Buffer): DiffieHellman; - export function getDiffieHellman(group_name: string): DiffieHellman; - - export class DiffieHellman { - verifyError: number; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - generateKeys(encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding?: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - - export function createECDH(curve_name: string): ECDH; - - export class ECDH { - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - generateKeys(encoding?: string, format?: string): string; - getPrivateKey(encoding?: string): string; - getPublicKey(encoding?: string, format?: string): string; - setPrivateKey(private_key: string, encoding?: string): void; - } - - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => void): void; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => void): void; - - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; - - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - - export interface RsaKey { - key: string; - passphrase?: string, - padding?: number; - } - - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export function publicEncrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; - export function privateEncrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; - export function publicDecrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; - export function privateDecrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; - - export function setEngine(engine: string, flags?: number): void; + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hash; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hmac; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + getAuthTag(): Buffer; + setAAD(buffer: Buffer): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + setAuthTag(tag: Buffer): void; + setAAD(buffer: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer): Signer; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string }): Buffer; + sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer): Verify; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string, signature: Buffer): boolean; + verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + } + export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; + export function createDiffieHellman(prime: Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + export interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export interface RsaPublicKey { + key: string; + padding?: number; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: number; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; + export interface ECDH { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export var DEFAULT_ENCODING: string; } declare module "stream" { - import * as events from "events"; + import * as events from "events"; - export class Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + namespace internal { - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (this: Readable, size?: number) => any; - } + export class Stream extends internal { } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - isPaused(): boolean; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + protected _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - setDefaultEncoding(encoding: string): this; - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements Writable { - writable: boolean; - constructor(opts?: DuplexOptions); - setDefaultEncoding(encoding: string): this; - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; - export interface TransformOptions extends ReadableOptions, WritableOptions { - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; - export class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - } + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; - export class PassThrough extends Transform { } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): this; + resume(): this; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends DuplexOptions { + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + protected _transform(chunk: any, encoding: string, callback: Function): void; + protected _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } + } + + export = internal; } declare module "util" { - /** - * The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` environment variable. If the `section` name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op. - */ - export function debuglog(section: string): (msg: any, ...args: any[]) => void; - - export interface InspectOptions { - /** - * If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. - */ - showHidden?: boolean; - /** - * Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. - */ - depth?: number | null; - /** - * If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see "Customizing util.inspect colors". - */ - colors?: boolean; - /** - * If `false`, then custom `inspect(depth, opts)` functions exported on the object being inspected will not be called. Defaults to `true`. - */ - customInspect?: boolean; - /** - * If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. - */ - showProxy?: boolean; - /** - * Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. - */ - maxArrayLength?: number | null; - /** - * The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to `60` for legacy compatibility. - */ - breakLength?: number; - } - - /** - * The `util.inspect()` method returns a string representation of object that is primarily useful for debugging. - */ - export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - - export namespace inspect { - export var colors: { - bold: [number, number]; - italic: [number, number]; - underline: [number, number]; - inverse: [number, number]; - white: [number, number]; - grey: [number, number]; - black: [number, number]; - blue: [number, number]; - cyan: [number, number]; - green: [number, number]; - magenta: [number, number]; - red: [number, number]; - yellow: [number, number]; + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; } - export var styles: { - special: string; - number: string; - boolean: string; - undefined: string; - null: string; - string: string; - symbol: string; - date: string; - regexp: string; - }; - - export var custom: symbol; - } - - /** - * The `util.deprecate()` method wraps the given function or class in such a way that it is marked as deprecated. - */ - export function deprecate(fn: T, string: string): T; - - /** - * The `util.format()` method returns a formatted string using the first argument as a printf-like format. - */ - export function format(format: any, ...param: any[]): string; - - /** - * Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor. - */ - export function inherits(constructor: any, superConstructor: any): void; - - /** - * Deprecated predecessor of `console.error`. - * - * @deprecated - */ - export function debug(string: string): void; - - /** - * Deprecated predecessor of `console.error`. - * - * @deprecated - */ - export function error(...strings: string[]): void; - - /** - * Internal alias for `Array.isArray`. - * - * @deprecated - */ - export function isArray(object: any): object is any[]; - - /** - * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isBoolean(object: any): object is boolean; - - /** - * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isBuffer(object: any): object is Buffer; - - /** - * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isDate(object: any): object is Date; - - /** - * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isError(object: any): object is Error; - - /** - * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isFunction(object: any): object is Function; - - /** - * Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNull(object: any): object is null; - - /** - * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNullOrUndefined(object: any): object is null | undefined; - - /** - * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNumber(object: any): object is number; - - /** - * Returns true if the given `object` is strictly an `Object` and not a `Function`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isObject(object: any): object is Object; - - /** - * Returns true if the given `object` is a primitive type. Otherwise, returns `false`. - * - * @deprecated - */ - export function isPrimitive(object: any): object is string | number | boolean | null | undefined; - - /** - * Returns true if the given `object` is a `RegExp`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isRegExp(object: any): object is RegExp; - - /** - * Returns true if the given `object` is a `String`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isString(object: any): object is string; - - /** - * Returns true if the given `object` is a `Symbol`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isSymbol(object: any): object is symbol; - - /** - * Returns true if the given `object` is `undefined`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isUndefined(object: any): object is symbol; - - /** - * The `util.log()` method prints the given `string` to `stdout` with an included timestamp. - * - * @deprecated - */ - export function log(string: string): void; - - /** - * Deprecated predecessor of `console.log`. - * - * @deprecated - */ - export function print(strings: string[]): void; - - /** - * Deprecated predecessor of `console.log`. - * - * @deprecated - */ - export function puts(strings: string[]): void; - - /** - * The `util._extend()` method was never intended to be used outside of internal Node.js modules. The community found and used it anyway. - * - * It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through `Object.assign()`. - * - * @deprecated - */ - export function _extend(target: T, source: U): T & U; + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + export function isBoolean(object: any): boolean; + export function isBuffer(object: any): boolean; + export function isFunction(object: any): boolean; + export function isNull(object: any): boolean; + export function isNullOrUndefined(object: any): boolean; + export function isNumber(object: any): boolean; + export function isObject(object: any): boolean; + export function isPrimitive(object: any): boolean; + export function isString(object: any): boolean; + export function isSymbol(object: any): boolean; + export function isUndefined(object: any): boolean; + export function deprecate(fn: Function, message: string): Function; } declare module "assert" { - function internal(value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function - }); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); + } + + export function fail(actual: any, expected: any, message: string, operator: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; - } - - export = internal; + export = internal; } declare module "tty" { - import * as net from "net"; + import * as net from "net"; - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } } declare module "domain" { - import * as events from "events"; + import * as events from "events"; - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - members: any[]; - enter(): void; - exit(): void; - } + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + members: any[]; + enter(): void; + exit(): void; + } - export function create(): Domain; + export function create(): Domain; } declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; -} - -declare module "module" { - export = NodeModule; + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; } declare module "process" { - export = process; + export = process; +} + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + const enum DoesZapCodeSpaceFlag { + Disabled = 0, + Enabled = 1 + } + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + export function getHeapStatistics(): HeapInfo; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; } declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function clearImmediate(immediateId: NodeJS.Immediate): void; + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} + +/** + * _debugger module is not documented. + * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js + */ +declare module "_debugger" { + export interface Packet { + raw: string; + headers: string[]; + body: Message; + } + + export interface Message { + seq: number; + type: string; + } + + export interface RequestInfo { + command: string; + arguments: any; + } + + export interface Request extends Message, RequestInfo { + } + + export interface Event extends Message { + event: string; + body?: any; + } + + export interface Response extends Message { + request_seq: number; + success: boolean; + /** Contains error message if success === false. */ + message?: string; + /** Contains message body if success === true. */ + body?: any; + } + + export interface BreakpointMessageBody { + type: string; + target: number; + line: number; + } + + export class Protocol { + res: Packet; + state: string; + execute(data: string): void; + serialize(rq: Request): string; + onResponse: (pkt: Packet) => void; + } + + export var NO_FRAME: number; + export var port: number; + + export interface ScriptDesc { + name: string; + id: number; + isNative?: boolean; + handle?: number; + type: string; + lineOffset?: number; + columnOffset?: number; + lineCount?: number; + } + + export interface Breakpoint { + id: number; + scriptId: number; + script: ScriptDesc; + line: number; + condition?: string; + scriptReq?: string; + } + + export interface RequestHandler { + (err: boolean, body: Message, res: Packet): void; + request_seq?: number; + } + + export interface ResponseBodyHandler { + (err: boolean, body?: any): void; + request_seq?: number; + } + + export interface ExceptionInfo { + text: string; + } + + export interface BreakResponse { + script?: ScriptDesc; + exception?: ExceptionInfo; + sourceLine: number; + sourceLineText: string; + sourceColumn: number; + } + + export function SourceInfo(body: BreakResponse): string; + + export interface ClientInstance extends NodeJS.EventEmitter { + protocol: Protocol; + scripts: ScriptDesc[]; + handles: ScriptDesc[]; + breakpoints: Breakpoint[]; + currentSourceLine: number; + currentSourceColumn: number; + currentSourceLineText: string; + currentFrame: number; + currentScript: string; + + connect(port: number, host: string): void; + req(req: any, cb: RequestHandler): void; + reqFrameEval(code: string, frame: number, cb: RequestHandler): void; + mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; + setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; + clearBreakpoint(rq: Request, cb: RequestHandler): void; + listbreakpoints(cb: RequestHandler): void; + reqSource(from: number, to: number, cb: RequestHandler): void; + reqScripts(cb: any): void; + reqContinue(cb: RequestHandler): void; + } + + export var Client : { + new (): ClientInstance + } } From 03e2e599c5c0781b383744d9b954f4a6b226ec35 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 02:00:20 +0300 Subject: [PATCH 05/85] node/node-test.ts Console testing update, mongodb reconciliation with node api --- mongodb/index.d.ts | 12 ++++++------ node/node-tests.ts | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index 26d1656baf..f96c699a6f 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1173,7 +1173,7 @@ export interface Cursor extends Readable { next(): Promise; next(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1202,7 +1202,7 @@ export interface Cursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1261,7 +1261,7 @@ export interface AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read @@ -1280,7 +1280,7 @@ export interface AggregationCursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind @@ -1306,7 +1306,7 @@ export interface CommandCursor extends Readable { next(): Promise; next(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind @@ -1319,7 +1319,7 @@ export interface CommandCursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 706e8b37f6..e34a67a41e 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1630,6 +1630,11 @@ namespace console_tests { var _c: Console = console; _c = c; } + { + var writeStream = fs.createWriteStream('./index.d.ts'); + var consoleInstance = new console.Console(writeStream) + + } } /////////////////////////////////////////////////// From 1e18f44d5c2f6d46c8ae5b9b6461d49fbdb254e9 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 03:09:50 +0300 Subject: [PATCH 06/85] mongodb/ methods duplication removal --- mongodb/index.d.ts | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index f96c699a6f..58b3d7aa0c 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1172,8 +1172,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1184,8 +1182,6 @@ export interface Cursor extends Readable { rewind(): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption setCursorOption(field: string, value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId @@ -1201,8 +1197,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1260,8 +1254,6 @@ export interface AggregationCursor extends Readable { next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read @@ -1271,16 +1263,12 @@ export interface AggregationCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): this; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort sort(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind @@ -1305,21 +1293,15 @@ export interface CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } From a0a9fe2efe4aa8a9c6ad765d6ccc471341964332 Mon Sep 17 00:00:00 2001 From: Rafael Salguero Iturrios Date: Sun, 8 Jan 2017 23:08:31 -0700 Subject: [PATCH 07/85] Update index.d.ts --- rx-lite/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rx-lite/index.d.ts b/rx-lite/index.d.ts index fb5056c478..7e085031aa 100644 --- a/rx-lite/index.d.ts +++ b/rx-lite/index.d.ts @@ -232,7 +232,7 @@ declare namespace Rx { withLatestFrom(souces: (Observable | IPromise)[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; concat(...sources: (Observable | IPromise)[]): Observable; concat(sources: (Observable | IPromise)[]): Observable; - concatAll(): Observable; + concatAll(): T; concatObservable(): Observable; // alias for concatAll concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat From 1c1fc8eea20aafce4605999732c282380d8cc1d9 Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:00:56 +0300 Subject: [PATCH 08/85] [Archiver] reconciliation with [node] --- archiver/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/archiver/index.d.ts b/archiver/index.d.ts index ea117239ac..665624143e 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -31,7 +31,6 @@ declare namespace archiver { } export interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; append(source: STREAM.Readable | Buffer | string, name: nameInterface): void; directory(dirpath: string, destpath: nameInterface | string): void; From b29bba797511449ee8f6bbd8fac2cdda56d0caef Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:44:29 +0300 Subject: [PATCH 09/85] [node] Rolled back node stream.readable.pipe() method according to official API Read here: https://github.com/nodejs/node/blob/master/lib/_stream_readable.js#L612 --- node/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index ea1c42aad9..606276e9a6 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -285,7 +285,7 @@ declare namespace NodeJS { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: string): void; unshift(chunk: Buffer): void; @@ -3341,7 +3341,7 @@ declare module "stream" { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; @@ -3531,7 +3531,7 @@ declare module "stream" { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; From 99a7b5915bc1dad725ef9759a68ba05b7633e798 Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:55:06 +0300 Subject: [PATCH 10/85] [bufferstream] reconciliation with [node] --- bufferstream/index.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts index 69a16d98e0..9b2b15d525 100644 --- a/bufferstream/index.d.ts +++ b/bufferstream/index.d.ts @@ -109,10 +109,6 @@ declare module 'bufferstream/postbuffer' { set a callback to get all post data from a http server request */ onEnd(callback: (data: any) => void): void; - /* - pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe - */ - pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; } export = PostBuffer; From 6de3e0630cd2bf63fd4b01b4d5d97931c3715ebf Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:23:25 +0100 Subject: [PATCH 11/85] updated Definitions for Raven-JS --- raven-js/index.d.ts | 393 +++++++++++++++++++++++++++++--------------- 1 file changed, 256 insertions(+), 137 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index 6ecb6a0cdd..fda465c30d 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,209 +1,302 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Original Definitions by: Santi Albo , Benjamin Pannell +// ; DefinitelyTyped +// Updated by: Ben Vinegar , Ilya Pirogov +// , Eli White , David Cramer +// , Connor Peet , comaz +// , Luca Vazzano + declare var Raven: RavenStatic; - -declare module 'raven-js' { - export default Raven; -} - -interface RavenOptions { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** The environment in which the application is running. */ - environment?: string; - - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** List of messages to be fitlered out before being sent to Sentry. */ - ignoreErrors?: string[]; - - /** Similar to ignoreErrors, but will ignore errors from whole urls patching a regex pattern. */ - ignoreUrls?: RegExp[]; - - /** The inverse of ignoreUrls. Only report errors from whole urls matching a regex pattern. */ - whitelistUrls?: RegExp[]; - - /** An array of regex patterns to indicate which urls are a part of your app. */ - includePaths?: RegExp[]; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; - - /** A callback function that allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** By default, Raven does not truncate messages. If you need to truncate characters for whatever reason, you may set this to limit the length. */ - maxMessageLength?: number; - - /** Enables/disables automatic collection of breadcrumbs. Default: true. */ - autoBreadcrumbs?: any; - - /** The max number of breadcrumb captures. Default: 100. */ - maxBreadcrumbs?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Allow the use of a Sentry DSN with a private key. Default: false. */ - allowSecretKey?: boolean; -} - -interface RavenAdditionalData { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - extra?: any; -} +export = Raven; interface RavenStatic { - /** Raven.js version. */ VERSION: string; + /** A list of currently active plugins. */ Plugins: { [id: string]: RavenPlugin }; - /* - * Allow Raven to be configured as soon as it is loaded + /** + * Allow Raven to be configured as soon as it is loaded. * It uses a global RavenConfig = {dsn: '...', config: {}} - * - * @return undefined */ afterLoad(): void; - /* + /** * Allow multiple versions of Raven to be installed. * Strip Raven from the global context and returns the instance. - * - * @return {Raven} */ noConflict(): RavenStatic; - /* + /** * Configure Raven with a DSN and extra options * - * @param {string} dsn The public Sentry DSN - * @param {object} options Optional set of of global options [optional] - * @return {Raven} + * @param dsn The public Sentry DSN + * @param options Optional set of of global options */ - config(dsn: string, options?: RavenOptions): RavenStatic; + config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - /* - * Installs a global window.onerror error handler - * to capture and report uncaught exceptions. - * At this point, install() is required to be called due - * to the way TraceKit is set up. + /** + * Set the DSN (can be called multiple times, unlike config) * - * @return {Raven} + * @param dsn The public Sentry DSN + */ + setDSN(dsn: string); + + /** + * Installs a global window.onerror error handler to capture and report uncaught exceptions. + * At this point, install() is required to be called due to the way TraceKit is set up. */ install(): RavenStatic; - /* + /** * Adds a plugin to Raven - * - * @return {Raven} */ addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - /* - * Wrap code within a context so Raven can capture errors - * reliably across domains that is executed immediately. + /** + * Wrap code within a context so Raven can capture errors reliably across domains that is + * executed immediately. * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The callback to be immediately executed within the context - * @param {array} args An array of arguments to be called with the callback [optional] + * @param options A specific set of options for this context + * @param func The callback to be immediately executed within the context + * @param args An array of arguments to be called with the callback */ context(func: Function, ...args: any[]): void; - context(options: RavenAdditionalData, func: Function, ...args: any[]): void; + context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - /* + /** * Wrap code within a context and returns back a new function to be executed * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The function to be wrapped in a new context - * @return {function} The newly wrapped functions with a context + * @param options A specific set of options for this context + * @param func The function to be wrapped in a new context + * @return The newly wrapped functions with a context */ wrap(func: Function): Function; - wrap(options: RavenAdditionalData, func: Function): Function; + wrap(options: RavenWrapOptions, func: Function): Function; wrap(func: T): T; - wrap(options: RavenAdditionalData, func: T): T; + wrap(options: RavenWrapOptions, func: T): T; - /* + /** * Uninstalls the global error handler. - * - * @return {Raven} */ uninstall(): RavenStatic; - /* + /** * Manually capture an exception and send it over to Sentry * - * @param {error} ex An exception to be logged - * @param {object} options A specific set of options for this error [optional] - * @return {Raven} + * @param ex An exception to be logged + * @param options A specific set of options for this error */ - captureException(ex: Error, options?: RavenAdditionalData): RavenStatic; + captureException(ex: Error, options?: RavenOptions): RavenStatic; /* * Manually send a message to Sentry * - * @param {string} msg A plain message to be captured in Sentry - * @param {object} options A specific set of options for this message [optional] - * @return {Raven} + * @param msg A plain message to be captured in Sentry + * @param options A specific set of options for this message */ - captureMessage(msg: string, options?: RavenAdditionalData): RavenStatic; + captureMessage(msg: string, options?: RavenOptions): RavenStatic; + + /** + * Add a breadcrumb + * @param crumb The trail which should be added to the trail + */ + captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; + + /** + * Set a user to be sent along with payloads. + * + * @param user The definition of the currently active user's unique identity + */ + setUserContext(user: RavenUserContext): RavenStatic; /** * Clear the user context, removing the user data that would be sent to Sentry. */ setUserContext(): RavenStatic; - /* - * Set a user to be sent along with the payload. - * - * @param {object} user An object representing user data [optional] - * @return {Raven} + /** + * Add arbitrary data to be sent along with the payload. + * @param extra data of an arbitrary, nested type which will be added */ - setUserContext(user: { - id?: string; - username?: string; - email?: string; - }): RavenStatic; + setExtraContext(extra: { [prop: string]: any }): RavenStatic; - /** Override the default HTTP data transport handler. */ - setTransport(transportFunction: (options: RavenTransportOptions) => void): RavenStatic; + /** + * Add additional tags to be sent along with payloads. + * @param tags A key/value-pair which will be added + */ + setTagsContext(tags: { [id: string]: string }): RavenStatic; - /** An event id is a globally unique id for the event that was just sent. This event id can be used to find the exact event from within Sentry. */ + /** + * Clear the whole currently set context. + */ + clearContext(): RavenStatic; + + /** + * Get a copy of the current context. + */ + getContext(): Object; + + /** + * Set environment of application + * @param environment Typically something like 'production' + */ + setEnvironment(environment: string): RavenStatic; + + /** + * Set release version of application + * @param release Typically something like a git SHA to identify the current version + */ + setRelease(release: string): RavenStatic; + + /** + * Specify a function that can mutate the payload right before it is being sent to Sentry. + * @param callback The function which can mutate the data + */ + setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that can mutate or filter breadcrumbs when they are captured. + * @param callback The function which applies the filter + */ + setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that determines if the given message should be sent to Sentry. + * @param callback The function which determines if the given blob should be sent + */ + setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; + + /** + * Override the default HTTP data transport handler. + * @param transport The function which will be invoked to handle the data transmission + */ + setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; + + /** + * Get the latest raw exception that was captured by Raven. + */ + lastException(): Error; + + /** + * Get the ID of the last Event captured by Raven. + */ lastEventId(): string; - /** If you need to conditionally check if raven needs to be initialized or not, you can use the isSetup function. It will return true if Raven is already initialized. */ + /** + * Determine if Raven is setup and ready to go. + */ isSetup(): boolean; - showReportDialog(options: RavenOptions): void; + /** + * Show the User Feedback Dialog of Sentry + * @param RavenReportDialogOptions Optional Options to set for the User Feedback + */ + showReportDialog(options?: RavenReportDialogOptions): void; +} - setTagsContext(tags: { [id: string]: string; }): void; - setExtraContext(context: any): void; +// --- Helper Interfaces for Options -------------- +interface RavenBreadcrumOptions { + /** Whether to collect XHR calls, defaults to true */ + xhr?: boolean; + + /** Whether to collect console logs, defaults to true */ + console?: boolean; + + /** Whether to collect dom events, defaults to true */ + dom?: boolean; + + /** Whether to record window location and navigation, defaults to true */ + location?: boolean; +} + +interface CommonRavenOptions { + /** The environment of the application you are monitoring with Sentry */ + environment?: string; + + /** The release version of the application you are monitoring with Sentry */ + release?: string; + + /** Additional key/value-data to be tagged onto the error. */ + tags?: { [id: string]: string }; + + /** Additional, arbitrary metadata to collect */ + extra?: { [prop: string]: any }; + + /** The name of the logger used by Sentry. Default: javascript */ + logger?: string; + + /** set to true to get the strack trace of your message */ + stacktrace?: boolean; +} + +interface RavenOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + server_name?: string; + + /** The log level associated with this event. Default: error */ + level?: string; + + /** In some cases you may see issues where Sentry groups multiple events together when they + * should be separate entities. In other cases, Sentry simply doesn’t group events together + * because they’re so sporadic that they never look the same. */ + fingerprint?: string[]; + + /** Number of frames to trim off the stacktrace. Default: 1 */ + trimHeadFrames?: number; + + /** The name of the device platform. Default: "javascript" */ + platform?: string; +} + +interface RavenGlobalOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + serverName?: string; + + /** Configures which breadcrumbs are collected automatically */ + autoBreadcrumbs?: boolean | RavenBreadcrumOptions; + + /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ + collectWindowErrors?: boolean; + + /** Max number of breadcrumbs to collect. Default: 100 */ + maxBreadcrumbs?: number; + + /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ + ignoreErrors?: (RegExp | string)[]; + + /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ + ignoreUrls?: (RegExp | string)[]; + + /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ + whitelistUrls?: (RegExp | string)[]; + + /** An array of RegEx patterns to indicate which urls are a part of your app. */ + includePaths?: (RegExp | string)[]; + + /** Maximum amount of stack frames to collect. Default: Infinity */ + stackTraceLimit?: number; + + /** Override the default HTTP data transport handler. */ + transport?: (options: RavenTransportOptions) => void; + + /** Limit the maxium length of a message to this number of characters. Default: Infinity */ + maxMessageLength?: number; + + /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ + shouldSendCallback?: (data: any) => boolean; + + /** A function which allows mutation of the data payload right before being sent to Sentry */ + dataCallback?: (data: any) => any; +} + +interface RavenWrapOptions extends RavenOptions { + /** Whether to run the wrap recursively. Default: false. */ + deep?: boolean; } interface RavenTransportOptions { @@ -218,6 +311,32 @@ interface RavenTransportOptions { onFailure: () => void; } +interface RavenReportDialogOptions { + eventId?: number, + dsn?: string, + user?: { + name?: string, + email?: string + } +} + + +// --- Helper Interfaces for complex Data Structures -------------- interface RavenPlugin { (raven: RavenStatic, ...args: any[]): RavenStatic; } + +interface RavenUserContext { + id?: string; + username?: string; + email?: string; + ip_address?: string; + extra?: { [prop: string]: any }; +} + +interface RavenBreadcrumb { + message: string; + data: { [id: string]: string }; + category: string; + level: string; +} From 861c2abc61efdc93cebc5387233e226dead003e3 Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:46:01 +0100 Subject: [PATCH 12/85] fixed tests --- raven-js/index.d.ts | 28 ++++++++-------- raven-js/raven-js-tests.ts | 67 +++++++++++++++++++++----------------- 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index fda465c30d..ddb5e8503d 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Raven.js +// Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js // Original Definitions by: Santi Albo , Benjamin Pannell // ; DefinitelyTyped @@ -8,8 +8,8 @@ // , Luca Vazzano -declare var Raven: RavenStatic; -export = Raven; +declare let Raven: RavenStatic; +export default Raven; interface RavenStatic { /** Raven.js version. */ @@ -43,7 +43,7 @@ interface RavenStatic { * * @param dsn The public Sentry DSN */ - setDSN(dsn: string); + setDSN(dsn: string): RavenStatic; /** * Installs a global window.onerror error handler to capture and report uncaught exceptions. @@ -200,7 +200,7 @@ interface RavenStatic { // --- Helper Interfaces for Options -------------- -interface RavenBreadcrumOptions { +export interface RavenBreadcrumOptions { /** Whether to collect XHR calls, defaults to true */ xhr?: boolean; @@ -214,7 +214,7 @@ interface RavenBreadcrumOptions { location?: boolean; } -interface CommonRavenOptions { +export interface CommonRavenOptions { /** The environment of the application you are monitoring with Sentry */ environment?: string; @@ -234,7 +234,7 @@ interface CommonRavenOptions { stacktrace?: boolean; } -interface RavenOptions extends CommonRavenOptions { +export interface RavenOptions extends CommonRavenOptions { /** The name of the server or device that the client is running on */ server_name?: string; @@ -253,7 +253,7 @@ interface RavenOptions extends CommonRavenOptions { platform?: string; } -interface RavenGlobalOptions extends CommonRavenOptions { +export interface RavenGlobalOptions extends CommonRavenOptions { /** The name of the server or device that the client is running on */ serverName?: string; @@ -294,12 +294,12 @@ interface RavenGlobalOptions extends CommonRavenOptions { dataCallback?: (data: any) => any; } -interface RavenWrapOptions extends RavenOptions { +export interface RavenWrapOptions extends RavenOptions { /** Whether to run the wrap recursively. Default: false. */ deep?: boolean; } -interface RavenTransportOptions { +export interface RavenTransportOptions { url: string; data: any; auth: { @@ -311,7 +311,7 @@ interface RavenTransportOptions { onFailure: () => void; } -interface RavenReportDialogOptions { +export interface RavenReportDialogOptions { eventId?: number, dsn?: string, user?: { @@ -322,11 +322,11 @@ interface RavenReportDialogOptions { // --- Helper Interfaces for complex Data Structures -------------- -interface RavenPlugin { +export interface RavenPlugin { (raven: RavenStatic, ...args: any[]): RavenStatic; } -interface RavenUserContext { +export interface RavenUserContext { id?: string; username?: string; email?: string; @@ -334,7 +334,7 @@ interface RavenUserContext { extra?: { [prop: string]: any }; } -interface RavenBreadcrumb { +export interface RavenBreadcrumb { message: string; data: { [id: string]: string }; category: string; diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts index 9608e41322..bbd3285e1e 100644 --- a/raven-js/raven-js-tests.ts +++ b/raven-js/raven-js-tests.ts @@ -1,24 +1,24 @@ - - import RavenJS from 'raven-js'; RavenJS.config('https://public@getsentry.com/1').install(); -var options: RavenOptions = { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] -}; -Raven.config('https://public@getsentry.com/1', options).install(); +RavenJS.config( + 'https://public@getsentry.com/1', + { + logger: 'my-logger', + ignoreUrls: [ + /graph\.facebook\.com/i + ], + ignoreErrors: [ + 'fb_xd_fragment' + ], + includePaths: [ + /https?:\/\/(www\.)?getsentry\.com/, + /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ + ] + } +).install(); var throwsError = () => { throw new Error('broken'); @@ -27,28 +27,35 @@ var throwsError = () => { try { throwsError(); } catch(e) { - Raven.captureException(e); - Raven.captureException(e, {tags: { key: "value" }}); + RavenJS.captureException(e); + RavenJS.captureException(e, {tags: { key: "value" }}); } -Raven.context(throwsError); -Raven.context({tags: { key: "value" }}, throwsError); -Raven.context({extra: {planet: {name: 'Earth'}}}, throwsError); +RavenJS.context(throwsError); +RavenJS.context({tags: { key: "value" }}, throwsError); +RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); -setTimeout(Raven.wrap(throwsError), 1000); -Raven.wrap({logger: "my.module"}, throwsError)(); -Raven.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); +setTimeout(RavenJS.wrap(throwsError), 1000); +RavenJS.wrap({logger: "my.module"}, throwsError)(); +RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); -Raven.setUserContext({ +RavenJS.setUserContext({ email: 'matt@example.com', id: '123' }); -Raven.captureMessage('Broken!'); -Raven.captureMessage('Broken!', {tags: { key: "value" }}); +RavenJS.captureMessage('Broken!'); +RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); -Raven.showReportDialog(options); +RavenJS.showReportDialog({ + eventId: 0815, + dsn:'1337asdf', + user: { + name: 'DefenitelyTyped', + email: 'df@ts.ms' + } +}); -Raven.setTagsContext({ key: "value" }); +RavenJS.setTagsContext({ key: "value" }); -Raven.setExtraContext({ foo: "bar" }); +RavenJS.setExtraContext({ foo: "bar" }); From 9ef1ed01256fc403e35fb4cb756310d3df2e658c Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:54:16 +0100 Subject: [PATCH 13/85] fixed BOM --- raven-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index ddb5e8503d..b264b9d786 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Raven.js +// Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js // Original Definitions by: Santi Albo , Benjamin Pannell // ; DefinitelyTyped From e1bd300cd1d205dbcf4709c0f3d25d2413123cd6 Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 01:20:04 +0100 Subject: [PATCH 14/85] fixed 'Definitions:'/'Definitions by:' comment at the top of raven-js/index.d.ts --- raven-js/index.d.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index b264b9d786..7b54ec7372 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,11 +1,7 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Original Definitions by: Santi Albo , Benjamin Pannell -// ; DefinitelyTyped -// Updated by: Ben Vinegar , Ilya Pirogov -// , Eli White , David Cramer -// , Connor Peet , comaz -// , Luca Vazzano +// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare let Raven: RavenStatic; From 771ef63514fb41176875407fb93a540c162e9e33 Mon Sep 17 00:00:00 2001 From: scippio Date: Sat, 14 Jan 2017 00:31:01 +0100 Subject: [PATCH 15/85] added new option parameter added new option parameter for new package version compatibility --- cron/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cron/index.d.ts b/cron/index.d.ts index e962a9eb27..79a5b96a01 100644 --- a/cron/index.d.ts +++ b/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.0.9 +// Type definitions for cron 1.2.1 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,9 @@ interface CronJobStatic { - new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; + new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean): CronJob; new (options: { - cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any + cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any; runOnInit?: boolean }): CronJob; } interface CronJob { From ee373b10745c1324ebc30d6c302ccc10cc6d6786 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:13:18 +0100 Subject: [PATCH 16/85] Add definitions for shipit, shipit-utils and express-rate-limit. --- .../express-rate-limit-tests.ts | 25 ++++++++ express-rate-limit/index.d.ts | 37 +++++++++++ express-rate-limit/tsconfig.json | 20 ++++++ shipit-utils/index.d.ts | 22 +++++++ shipit-utils/shipit-utils-tests.ts | 11 ++++ shipit-utils/tsconfig.json | 20 ++++++ shipit/index.d.ts | 61 +++++++++++++++++++ shipit/shipit-cli-tests.ts | 50 +++++++++++++++ shipit/tsconfig.json | 20 ++++++ 9 files changed, 266 insertions(+) create mode 100644 express-rate-limit/express-rate-limit-tests.ts create mode 100644 express-rate-limit/index.d.ts create mode 100644 express-rate-limit/tsconfig.json create mode 100644 shipit-utils/index.d.ts create mode 100644 shipit-utils/shipit-utils-tests.ts create mode 100644 shipit-utils/tsconfig.json create mode 100644 shipit/index.d.ts create mode 100644 shipit/shipit-cli-tests.ts create mode 100644 shipit/tsconfig.json diff --git a/express-rate-limit/express-rate-limit-tests.ts b/express-rate-limit/express-rate-limit-tests.ts new file mode 100644 index 0000000000..761a6d23f8 --- /dev/null +++ b/express-rate-limit/express-rate-limit-tests.ts @@ -0,0 +1,25 @@ +import RateLimit = require("express-rate-limit"); + +var apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +var createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour" +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + resetAll() { } + resetKey(key: string) { }; +}; + +var limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts new file mode 100644 index 0000000000..57eb003694 --- /dev/null +++ b/express-rate-limit/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for express-rate-limit 2.6.0 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + export interface Store { + incr: (key: string, cb: StoreIncrementCallback) => void; + resetAll: () => void; + resetKey: (key: string) => void; + } + + export interface Options { + delayAfter?: number; + delayMs?: number; + headers?: boolean; + keyGenerator?: Function; + max?: number; + message?: string; + statusCode?: number; + store?: Store; + windowMs?: number; + } +} + +interface RateLimitStatic { + new(options: RateLimit.Options): express.RequestHandler; +} + +declare var RateLimit: RateLimitStatic; +export = RateLimit; diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json new file mode 100644 index 0000000000..560edfef9d --- /dev/null +++ b/express-rate-limit/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] +} diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts new file mode 100644 index 0000000000..a66b681c37 --- /dev/null +++ b/shipit-utils/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for shipit-utils 1.4.0 +// Project: https://github.com/shipitjs/shipit-utils +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "shipit-utils" { + import shipit = require("shipit-cli"); + + type GruntOrShipit = typeof shipit | {}; + + export function equalValues(value: any[]): void; + + export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; + export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; + + export function registerTask(gruntOrShipit: GruntOrShipit, name: string, task: Function): typeof shipit; + export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependencies: string[]): typeof shipit; + + export function runTask(gruntOrShipit: {}): void; +} diff --git a/shipit-utils/shipit-utils-tests.ts b/shipit-utils/shipit-utils-tests.ts new file mode 100644 index 0000000000..15f0d5547b --- /dev/null +++ b/shipit-utils/shipit-utils-tests.ts @@ -0,0 +1,11 @@ +import shipit = require("shipit-cli"); +import utils = require("shipit-utils"); + +var originalShipit = utils.getShipit(shipit); + +var task = () => { + return shipit.local("sleep 10s"); +}; + +utils.registerTask(originalShipit, "myTask", task); +utils.registerTask(originalShipit, "myTask", ["some", "other", "tasks"]); diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json new file mode 100644 index 0000000000..fa4b1ce3b6 --- /dev/null +++ b/shipit-utils/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-utils-tests.ts" + ] +} diff --git a/shipit/index.d.ts b/shipit/index.d.ts new file mode 100644 index 0000000000..e0a528a2f2 --- /dev/null +++ b/shipit/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for shipit 1.5.1 +// Project: https://github.com/shipitjs/shipit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "shipit-cli" { + import shipit = require("shipit-cli"); + + import * as fs from "fs"; + import * as child_process from "child_process"; + + type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; + type TaskExecution = (name: string, depsOrFn: string[] | Function, fn: Function) => any; + + export interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + export interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + export interface Tasks { + [name: string]: Task; + } + + export interface Task { + blocking: boolean; + dep: string[]; + fn: Function; + name: string; + } + + export function blTask(name: string, depsOrFn: string[] | Function, fn?: Function): any; + export function emit(name: string): any; + export function initConfig(config: {}): typeof shipit; + export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function log(log: any): void; + export function log(...log: any[]): void; + export function on(name: string, callback: Function): any; + export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function start(tasks: string): typeof shipit; + export function start(tasks: string[]): typeof shipit; + export function start(...tasks: string[]): typeof shipit; + export function task(name: string, depsOrFn: string[] | Function, fn?: Function): typeof shipit; + + export var config: {}; + export var domain: any; + export var doneCallback: any; + export var environment: string; + export var seq: any[]; + export var tasks: Tasks; + export var isRunning: boolean; +} diff --git a/shipit/shipit-cli-tests.ts b/shipit/shipit-cli-tests.ts new file mode 100644 index 0000000000..50dff54978 --- /dev/null +++ b/shipit/shipit-cli-tests.ts @@ -0,0 +1,50 @@ +import shipit = require("shipit-cli"); + +shipit.initConfig({ + default: { + workspace: "/tmp/github-monitor", + deployTo: "/tmp/deploy_to", + repositoryUrl: "https://github.com/user/repo.git", + ignores: [".git", "node_modules"], + rsync: ["--del"], + keepReleases: 2, + key: "/path/to/key", + shallowClone: true + }, + staging: { + servers: "user@myserver.com" + } +}); + +shipit.task("build", () => { + shipit.emit("built"); +}); + +shipit.on("built", () => { + shipit.start("start-server"); +}); + +shipit.task("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.blTask("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.start("task"); +shipit.start("task1", "task2"); +shipit.start(["task1", "task2"]); + +shipit.local("ls -lah", {cwd: "/tmp/deploy/workspace"}).then((res: any) => { + console.log(res.stdout); + console.log(res.stderr); +}); + +shipit.remote("ls -lah").then((res: any) => { + console.log(res[0].stdout); + console.log(res[0].stderr); +}); + +shipit.remoteCopy("/tmp/workspace", "/opt/web/myapp").then(() => {}); +shipit.log("hello %s", "world"); diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json new file mode 100644 index 0000000000..da7bec35d8 --- /dev/null +++ b/shipit/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-cli-tests.ts" + ] +} From d4044f0ce56b80c6ed0403ff17305678a85423b2 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:18:20 +0100 Subject: [PATCH 17/85] Fix definition header for shipit-cli. --- shipit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shipit/index.d.ts b/shipit/index.d.ts index e0a528a2f2..ab44d7abd8 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit 1.5.1 +// Type definitions for shipit-cli 1.5.1 // Project: https://github.com/shipitjs/shipit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 6c7cd1ed7b83005c26891581f6cffb54eafa63d7 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:19:11 +0100 Subject: [PATCH 18/85] Rename "shipit-cli-tests" to "shipit-tests". --- shipit/{shipit-cli-tests.ts => shipit-tests.ts} | 0 shipit/tsconfig.json | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename shipit/{shipit-cli-tests.ts => shipit-tests.ts} (100%) diff --git a/shipit/shipit-cli-tests.ts b/shipit/shipit-tests.ts similarity index 100% rename from shipit/shipit-cli-tests.ts rename to shipit/shipit-tests.ts diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json index da7bec35d8..254ac2d9a5 100644 --- a/shipit/tsconfig.json +++ b/shipit/tsconfig.json @@ -15,6 +15,6 @@ }, "files": [ "index.d.ts", - "shipit-cli-tests.ts" + "shipit-tests.ts" ] } From 040c1365bc12314f7ce49799cd2cdcb8e6c295f5 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Tue, 17 Jan 2017 12:32:34 +0900 Subject: [PATCH 19/85] Update react-router-redux to user history 4.5.x --- react-router-redux/index.d.ts | 111 ++++++++---------- .../react-router-redux-tests.ts | 20 +++- react-router-redux/tsconfig.json | 17 ++- react-router-redux/tslint.json | 1 + 4 files changed, 76 insertions(+), 73 deletions(-) create mode 100644 react-router-redux/tslint.json diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 16438f9452..a6d3bd8c00 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -1,65 +1,58 @@ -// Type definitions for react-router-redux v4.0.0 +// Type definitions for react-router-redux 4.0 // Project: https://github.com/rackt/react-router-redux -// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg +// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Action, Middleware, Store } from "redux"; +import { History, Location, LocationDescriptor } from "history"; -import * as Redux from "redux"; -import * as History from "history"; +export const CALL_HISTORY_METHOD: string; +export const LOCATION_CHANGE: string; -export = ReactRouterRedux; - -declare namespace ReactRouterRedux { - import R = Redux; - - const CALL_HISTORY_METHOD: string; - const LOCATION_CHANGE: string; - - const push: PushAction; - const replace: ReplaceAction; - const go: GoAction; - const goBack: GoForwardAction; - const goForward: GoBackAction; - const routerActions: RouteActions; - - type LocationDescriptor = History.LocationDescriptor; - type PushAction = (nextLocation: LocationDescriptor) => RouterAction; - type ReplaceAction = (nextLocation: LocationDescriptor) => RouterAction; - type GoAction = (n: number) => RouterAction; - type GoForwardAction = () => RouterAction; - type GoBackAction = () => RouterAction; - - type RouterAction = { - type: string - payload?: LocationDescriptor - } - - interface RouteActions { - push: PushAction; - replace: ReplaceAction; - go: GoAction; - goForward: GoForwardAction; - goBack: GoBackAction; - } - interface ReactRouterReduxHistory extends History.History { - unsubscribe(): void; - } - - interface DefaultSelectLocationState extends Function { - (state: any): any; - } - - interface SyncHistoryWithStoreOptions { - selectLocationState?: DefaultSelectLocationState; - adjustUrlOnReplay?: boolean; - } - - interface RouterState { - locationBeforeTransitions: History.Location - } - - function routerReducer(state?: RouterState, action?: R.Action): RouterState; - function syncHistoryWithStore(history: History.History, store: R.Store, options?: SyncHistoryWithStoreOptions): ReactRouterReduxHistory; - function routerMiddleware(history: History.History): R.Middleware; +export interface LocationActionPayload { + method: string; + args?: any[]; } + +export interface RouterAction extends Action { + payload?: LocationActionPayload; +} + +type LocationAction = (nextLocation: LocationDescriptor) => RouterAction; +type GoAction = (n: number) => RouterAction; +type NavigateAction = () => RouterAction; + +export const push: LocationAction; +export const replace: LocationAction; +export const go: GoAction; +export const goBack: NavigateAction; +export const goForward: NavigateAction; + +interface RouteActions { + push: typeof push; + replace: typeof replace; + go: typeof go; + goForward: typeof goForward; + goBack: typeof goBack; +} + +export const routerActions: RouteActions; + +export interface RouterState { + locationBeforeTransitions: Location +} + +export type DefaultSelectLocationState = (state: any) => RouterState + +export interface SyncHistoryWithStoreOptions { + selectLocationState?: DefaultSelectLocationState; + adjustUrlOnReplay?: boolean; +} + +export interface HistoryUnsubscribe { + unsubscribe(): void; +} + +export function routerReducer(state?: RouterState, action?: Action): RouterState; +export function syncHistoryWithStore(history: History, store: Store, options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe; +export function routerMiddleware(history: History): Middleware; diff --git a/react-router-redux/react-router-redux-tests.ts b/react-router-redux/react-router-redux-tests.ts index 1d73706c4e..87b99b2a69 100644 --- a/react-router-redux/react-router-redux-tests.ts +++ b/react-router-redux/react-router-redux-tests.ts @@ -1,9 +1,16 @@ -/// -/// - import { createStore, combineReducers, applyMiddleware } from 'redux'; import { browserHistory } from 'react-router'; -import { syncHistoryWithStore, routerReducer, routerMiddleware, push, replace, go, goForward, goBack } from 'react-router-redux'; +import { + syncHistoryWithStore, + routerReducer, + routerMiddleware, + push, + replace, + go, + goForward, + goBack, + routerActions +} from 'react-router-redux'; const reducer = combineReducers({ routing: routerReducer }); @@ -25,3 +32,8 @@ store.dispatch(replace('/foo')); store.dispatch(go(1)); store.dispatch(goForward()); store.dispatch(goBack()); +store.dispatch(routerActions.push('/foo')); +store.dispatch(routerActions.replace('/foo')); +store.dispatch(routerActions.go(1)); +store.dispatch(routerActions.goForward()); +store.dispatch(routerActions.goBack()); diff --git a/react-router-redux/tsconfig.json b/react-router-redux/tsconfig.json index b2efdcc111..64b2c38849 100644 --- a/react-router-redux/tsconfig.json +++ b/react-router-redux/tsconfig.json @@ -1,23 +1,20 @@ { - "files": [ - "index.d.ts", - "react-router-redux-tests.ts" - ], "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ - "../" + "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "react-router-redux-tests.ts" + ] } diff --git a/react-router-redux/tslint.json b/react-router-redux/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-router-redux/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 69a9f6d6718fba210ab007541572ff8459c6d1ce Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Tue, 17 Jan 2017 18:29:47 +0900 Subject: [PATCH 20/85] Update react-router definitions to 3.0.x --- react-router/index.d.ts | 137 +++++------ react-router/lib/IndexLink.d.ts | 16 +- react-router/lib/IndexRedirect.d.ts | 25 +-- react-router/lib/IndexRoute.d.ts | 44 ++-- react-router/lib/Link.d.ts | 22 +- react-router/lib/PatternUtils.d.ts | 4 +- react-router/lib/PropTypes.d.ts | 35 +-- react-router/lib/Redirect.d.ts | 27 +-- react-router/lib/Route.d.ts | 50 +++-- react-router/lib/RouteUtils.d.ts | 9 +- react-router/lib/Router.d.ts | 212 +++++++++--------- react-router/lib/RouterContext.d.ts | 27 +-- react-router/lib/applyRouterMiddleware.d.ts | 12 +- react-router/lib/browserHistory.d.ts | 4 +- react-router/lib/createMemoryHistory.d.ts | 6 +- react-router/lib/hashHistory.d.ts | 4 +- react-router/lib/match.d.ts | 25 +-- react-router/lib/useRouterHistory.d.ts | 8 +- react-router/lib/withRouter.d.ts | 11 +- react-router/react-router-tests.tsx | 33 ++- react-router/tsconfig.json | 3 - react-router/v2/index.d.ts | 91 ++++++++ react-router/v2/lib/IndexLink.d.ts | 5 + react-router/v2/lib/IndexRedirect.d.ts | 17 ++ react-router/v2/lib/IndexRoute.d.ts | 20 ++ react-router/{ => v2}/lib/Lifecycle.d.ts | 0 react-router/v2/lib/Link.d.ts | 19 ++ react-router/v2/lib/PatternUtils.d.ts | 1 + react-router/v2/lib/PropTypes.d.ts | 19 ++ react-router/v2/lib/Redirect.d.ts | 19 ++ react-router/v2/lib/Route.d.ts | 25 +++ react-router/{ => v2}/lib/RouteContext.d.ts | 0 react-router/v2/lib/RouteUtils.d.ts | 8 + react-router/v2/lib/Router.d.ts | 116 ++++++++++ react-router/v2/lib/RouterContext.d.ts | 25 +++ .../v2/lib/applyRouterMiddleware.d.ts | 9 + react-router/v2/lib/browserHistory.d.ts | 3 + react-router/v2/lib/createMemoryHistory.d.ts | 3 + react-router/v2/lib/hashHistory.d.ts | 3 + react-router/v2/lib/match.d.ts | 17 ++ react-router/{ => v2}/lib/routerHistory.d.ts | 0 react-router/v2/lib/useRouterHistory.d.ts | 7 + react-router/{ => v2}/lib/useRoutes.d.ts | 0 react-router/v2/lib/withRouter.d.ts | 4 + 44 files changed, 749 insertions(+), 376 deletions(-) create mode 100644 react-router/v2/index.d.ts create mode 100644 react-router/v2/lib/IndexLink.d.ts create mode 100644 react-router/v2/lib/IndexRedirect.d.ts create mode 100644 react-router/v2/lib/IndexRoute.d.ts rename react-router/{ => v2}/lib/Lifecycle.d.ts (100%) create mode 100644 react-router/v2/lib/Link.d.ts create mode 100644 react-router/v2/lib/PatternUtils.d.ts create mode 100644 react-router/v2/lib/PropTypes.d.ts create mode 100644 react-router/v2/lib/Redirect.d.ts create mode 100644 react-router/v2/lib/Route.d.ts rename react-router/{ => v2}/lib/RouteContext.d.ts (100%) create mode 100644 react-router/v2/lib/RouteUtils.d.ts create mode 100644 react-router/v2/lib/Router.d.ts create mode 100644 react-router/v2/lib/RouterContext.d.ts create mode 100644 react-router/v2/lib/applyRouterMiddleware.d.ts create mode 100644 react-router/v2/lib/browserHistory.d.ts create mode 100644 react-router/v2/lib/createMemoryHistory.d.ts create mode 100644 react-router/v2/lib/hashHistory.d.ts create mode 100644 react-router/v2/lib/match.d.ts rename react-router/{ => v2}/lib/routerHistory.d.ts (100%) create mode 100644 react-router/v2/lib/useRouterHistory.d.ts rename react-router/{ => v2}/lib/useRoutes.d.ts (100%) create mode 100644 react-router/v2/lib/withRouter.d.ts diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 59f33e1960..8398838aef 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -1,91 +1,56 @@ -// Type definitions for react-router v2.0.0 +// Type definitions for react-router 3.0 // Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -export as namespace ReactRouter; - -import * as React from 'react'; - -export const routerShape: React.Requireable - -export const locationShape: React.Requireable - -import Router from "./lib/Router"; -import Link from "./lib/Link"; -import IndexLink from "./lib/IndexLink"; -import IndexRedirect from "./lib/IndexRedirect"; -import IndexRoute from "./lib/IndexRoute"; -import Redirect from "./lib/Redirect"; -import Route from "./lib/Route"; -import * as History from "./lib/routerHistory"; -import Lifecycle from "./lib/Lifecycle"; -import RouteContext from "./lib/RouteContext"; -import browserHistory from "./lib/browserHistory"; -import hashHistory from "./lib/hashHistory"; -import useRoutes from "./lib/useRoutes"; -import { createRoutes } from "./lib/RouteUtils"; -import { formatPattern } from "./lib/PatternUtils"; -import RouterContext from "./lib/RouterContext"; -import PropTypes from "./lib/PropTypes"; -import match from "./lib/match"; -import useRouterHistory from "./lib/useRouterHistory"; -import createMemoryHistory from "./lib/createMemoryHistory"; -import withRouter from "./lib/withRouter"; -import applyRouterMiddleware from "./lib/applyRouterMiddleware"; - -// PlainRoute is defined in the API documented at: -// https://github.com/rackt/react-router/blob/master/docs/API.md -// but not included in any of the .../lib modules above. -export type PlainRoute = Router.PlainRoute; - -// The following definitions are also very useful to export -// because by using these types lots of potential type errors -// can be exposed: -export type EnterHook = Router.EnterHook; -export type LeaveHook = Router.LeaveHook; -export type ParseQueryString = Router.ParseQueryString; -export type LocationDescriptor = Router.LocationDescriptor; -export type RedirectFunction = Router.RedirectFunction; -export type RouteComponent = Router.RouteComponent; -export type RouteComponentProps = Router.RouteComponentProps; -export type RouteConfig = Router.RouteConfig; -export type RouteHook = Router.RouteHook; -export type StringifyQuery = Router.StringifyQuery; -export type RouterListener = Router.RouterListener; -export type RouterState = Router.RouterState; -export type InjectedRouter = Router.InjectedRouter; - -export type HistoryBase = History.HistoryBase; -export type RouterOnContext = Router.RouterOnContext; -export type RouteProps = Route.RouteProps; -export type LinkProps = Link.LinkProps; - export { - Router, - Link, - IndexLink, - IndexRedirect, - IndexRoute, - Redirect, - Route, - History, - browserHistory, - hashHistory, - Lifecycle, - RouteContext, - useRoutes, - createRoutes, - formatPattern, - RouterContext, - PropTypes, - match, - useRouterHistory, - createMemoryHistory, - withRouter, - applyRouterMiddleware -}; + Basename, + ChangeHook, + EnterHook, + InjectedRouter, + LeaveHook, + Location, + LocationDescriptor, + ParseQueryString, + RouteComponent, + RouteComponents, + RouteComponentProps, + RouteConfig, + RoutePattern, + RouterProps, + RouterState, + StringifyQuery, + Query +} from "react-router/lib/Router"; +export { LinkProps } from "react-router/lib/Link"; +export { IndexLinkProps } from "react-router/lib/IndexLink"; +export { RouteProps, PlainRoute } from "react-router/lib/Route"; +export { IndexRouteProps } from "react-router/lib/IndexRoute"; +export { RedirectProps } from "react-router/lib/Redirect"; +export { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -export default Router; +/* components */ +export { default as Router } from "react-router/lib/Router"; +export { default as Link } from "react-router/lib/Link"; +export { default as IndexLink } from "react-router/lib/IndexLink"; +export { default as withRouter } from "react-router/lib/withRouter"; + +/* components (configuration) */ +export { default as IndexRedirect } from "react-router/lib/IndexRedirect"; +export { default as IndexRoute } from "react-router/lib/IndexRoute"; +export { default as Redirect } from "react-router/lib/Redirect"; +export { default as Route } from "react-router/lib/Route"; + +/* utils */ +export { createRoutes } from "react-router/lib/RouteUtils"; +export { default as RouterContext } from "react-router/lib/RouterContext"; +export { routerShape, locationShape } from "react-router/lib/PropTypes"; +export { default as match } from "react-router/lib/match"; +export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; +export { formatPattern } from "react-router/lib/PatternUtils"; +export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; + +/* histories */ +export { default as browserHistory } from "react-router/lib/browserHistory"; +export { default as hashHistory } from "react-router/lib/hashHistory"; +export { default as createMemoryHistory } from "react-router/lib/createMemoryHistory"; diff --git a/react-router/lib/IndexLink.d.ts b/react-router/lib/IndexLink.d.ts index 56ecf82c1d..0c62010262 100644 --- a/react-router/lib/IndexLink.d.ts +++ b/react-router/lib/IndexLink.d.ts @@ -1,5 +1,15 @@ -import Link from './Link'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { Location, LocationDescriptor } from "react-router/lib/Router"; + +type ToLocationFunction = (location: Location) => LocationDescriptor; + +export interface IndexLinkProps extends HTMLProps { + to: LocationDescriptor | ToLocationFunction; + activeClassName?: string; + activeStyle?: CSSProperties; +} + +type IndexLink = ComponentClass; +declare const IndexLink: IndexLink; -declare const IndexLink: Link; export default IndexLink; - diff --git a/react-router/lib/IndexRedirect.d.ts b/react-router/lib/IndexRedirect.d.ts index 41dab299c8..3b8187d09b 100644 --- a/react-router/lib/IndexRedirect.d.ts +++ b/react-router/lib/IndexRedirect.d.ts @@ -1,17 +1,12 @@ -import Router from './Router'; -import * as React from 'react'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; -declare const self: self.IndexRedirect; -type self = self.IndexRedirect; -export default self; - -declare namespace self { - interface IndexRedirectProps extends React.Props { - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface IndexRedirectElement extends React.ReactElement { } - interface IndexRedirect extends React.ComponentClass { } +export interface IndexRedirectProps extends ClassAttributes { + to: RoutePattern; + query?: Query; } + +type IndexRedirect = ComponentClass; +declare const IndexRedirect: IndexRedirect; + +export default IndexRedirect; diff --git a/react-router/lib/IndexRoute.d.ts b/react-router/lib/IndexRoute.d.ts index b11b16d0e2..b0574df26a 100644 --- a/react-router/lib/IndexRoute.d.ts +++ b/react-router/lib/IndexRoute.d.ts @@ -1,20 +1,28 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RouterState +} from "react-router"; -declare const self: self.IndexRoute; -type self = self.IndexRoute; -export default self; +type ComponentCallback = (err: any, component: RouteComponent) => void; +type ComponentsCallback = (err: any, components: RouteComponents) => void; -declare namespace self { - interface IndexRouteProps extends React.Props { - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - } - interface IndexRoute extends React.ComponentClass { } - interface IndexRouteElement extends React.ReactElement { } -} \ No newline at end of file +export interface IndexRouteProps { + component?: RouteComponent; + components?: RouteComponents; + getComponent?(nextState: RouterState, callback: ComponentCallback): void; + getComponents?(nextState: RouterState, callback: ComponentsCallback): void; + onEnter?: EnterHook; + onChange?: ChangeHook; + onLeave?: LeaveHook; +} + +type IndexRoute = ComponentClass; +declare const IndexRoute: IndexRoute; + +export default IndexRoute; diff --git a/react-router/lib/Link.d.ts b/react-router/lib/Link.d.ts index d90578b9f9..eca6e66abd 100644 --- a/react-router/lib/Link.d.ts +++ b/react-router/lib/Link.d.ts @@ -1,19 +1,11 @@ -import * as React from 'react'; -import Router from './Router'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; +export interface LinkProps extends IndexLinkProps { + onlyActiveOnIndex?: boolean; +} + +type Link = ComponentClass; declare const Link: Link; -type Link = Link.Link; export default Link; - -declare namespace Link { - interface LinkProps extends React.HTMLAttributes { - activeStyle?: React.CSSProperties; - activeClassName?: string; - onlyActiveOnIndex?: boolean; - to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); - } - - interface Link extends React.ComponentClass {} - interface LinkElement extends React.ReactElement {} -} diff --git a/react-router/lib/PatternUtils.d.ts b/react-router/lib/PatternUtils.d.ts index 50e90f6e49..2c32b2a286 100644 --- a/react-router/lib/PatternUtils.d.ts +++ b/react-router/lib/PatternUtils.d.ts @@ -1 +1,3 @@ -export function formatPattern(pattern: string, params: {}): string; +import { RoutePattern } from "react-router"; + +export function formatPattern(pattern: RoutePattern, params: any): string; diff --git a/react-router/lib/PropTypes.d.ts b/react-router/lib/PropTypes.d.ts index bbd6431070..c9140777cb 100644 --- a/react-router/lib/PropTypes.d.ts +++ b/react-router/lib/PropTypes.d.ts @@ -1,19 +1,22 @@ -import * as React from 'react'; +import { Requireable, Validator } from "react"; -export function falsy(props: any, propName: string, componentName: string): Error; -export const history: React.Requireable; -export const location: React.Requireable; -export const component: React.Requireable; -export const components: React.Requireable; -export const route: React.Requireable; -export const routes: React.Requireable; +export interface RouterShape extends Validator { + push: Requireable; + replace: Requireable; + go: Requireable; + goBack: Requireable; + goForward: Requireable; + setRouteLeaveHook: Requireable; + isActive: Requireable; +} -export default { - falsy, - history, - location, - component, - components, - route -}; +export interface LocationShape extends Validator { + pathname: Requireable; + search: Requireable; + state: any; + action: Requireable; + key: any; +} +export const routerShape: RouterShape; +export const locationShape: LocationShape; diff --git a/react-router/lib/Redirect.d.ts b/react-router/lib/Redirect.d.ts index e09b576d53..bb8254b4f5 100644 --- a/react-router/lib/Redirect.d.ts +++ b/react-router/lib/Redirect.d.ts @@ -1,19 +1,12 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; +import { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -declare const self: self.Redirect; -type self = typeof self; -export default self; - -declare namespace self { - interface RedirectProps extends React.Props { - path?: Router.RoutePattern; - from?: Router.RoutePattern; // alias for path - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface Redirect extends React.ComponentClass { } - interface RedirectElement extends React.ReactElement { } +export interface RedirectProps extends IndexRedirectProps { + from: RoutePattern; } + +type Redirect = ComponentClass; +declare const Redirect: Redirect; + +export default Redirect; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index 2f5425b55a..15aafebc75 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -1,25 +1,31 @@ -import * as React from 'react'; -import Router from './Router'; -import { Location } from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RoutePattern, + RouterState +} from "react-router"; +import { IndexRouteProps } from "react-router/lib/IndexRoute"; -declare const self: self.Route; -type self = self.Route; -export default self; +export interface RouteProps extends IndexRouteProps { + path?: RoutePattern; +} -declare namespace self { +type Route = ComponentClass; +declare const Route: Route; - interface RouteProps extends React.Props { - path?: Router.RoutePattern; - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - onChange?: Router.ChangeHook; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; - } - interface Route extends React.ComponentClass {} - interface RouteElement extends React.ReactElement {} -} \ No newline at end of file +export default Route; + +type RouteCallback = (err: any, route: PlainRoute) => void; +type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; + +export interface PlainRoute extends RouteProps { + childRoutes?: PlainRoute[]; + getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; + indexRoute?: PlainRoute; + getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; +} diff --git a/react-router/lib/RouteUtils.d.ts b/react-router/lib/RouteUtils.d.ts index 7065056ff5..6304f5d7bf 100644 --- a/react-router/lib/RouteUtils.d.ts +++ b/react-router/lib/RouteUtils.d.ts @@ -1,8 +1,3 @@ -import * as React from 'react'; -import Router from './Router'; +import { RouteConfig, PlainRoute } from "react-router"; -type E = React.ReactElement; -export function isReactChildren(object: E | E[]): boolean; -export function createRouteFromReactElement(element: E): Router.PlainRoute; -export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; -export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; +export function createRoutes(routes: RouteConfig): PlainRoute[]; diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index a9c5417f47..160694953f 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,116 +1,106 @@ -import * as React from 'react'; -import RouterContext from './RouterContext'; +import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { - QueryString, Query, - Location, LocationDescriptor, LocationState as HLocationState, - History, Href, - Pathname, Path } from 'history'; + Hash, + History, + Href, + LocationKey, + LocationState, + Path, + Pathname, + Search +} from "history"; +import { PlainRoute } from "react-router"; +export type Basename = string; +export type Query = any; +export type Action = "PUSH" | "REPLACE" | "POP"; +export interface Params { + [key: string]: string; +} +export type RoutePattern = string; +export type RouteComponent = ComponentClass | StatelessComponent; +export interface RouteComponents { + [name: string]: RouteComponent; +} +export type RouteConfig = ReactNode | PlainRoute | PlainRoute[]; + +export type ParseQueryString = (queryString: Search) => Query; +export type StringifyQuery = (queryObject: Query) => Search; + +type AnyFunction = (...args: any[]) => any; + +export type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type LeaveHook = (prevState: RouterState) => any; +export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type RouteHook = (nextLocation?: Location) => any; + +export interface Location { + patname: Pathname; + search: Search; + query: Query; + state: LocationState; + action: Action; + key: LocationKey; +} + +export interface LocationDescriptorObject { + pathname?: Pathname; + query?: Query; + hash?: Hash; + state?: LocationState; +} + +export type LocationDescriptor = Path | LocationDescriptorObject; + +export interface RedirectFunction { + (location: LocationDescriptor): void; + (state: LocationState, pathname: Pathname | Path, query?: Query): void; +} + +export interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; +} + +type LocationFunction = (location: LocationDescriptor) => void; +type GoFunction = (n: number) => void; +type NavigateFunction = () => void; +type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; +type LeaveHookFunction = (route: any, callback: RouteHook) => void; +type CreatePartFunction = (path: Path, query?: any) => Part; + +export interface InjectedRouter { + push: LocationFunction; + replace: LocationFunction; + go: GoFunction; + goBack: NavigateFunction; + goForward: NavigateFunction; + setRouteLeaveHook: LeaveHookFunction; + createPath: CreatePartFunction; + createHref: CreatePartFunction; + isActive: ActiveFunction; +} + +export interface RouteComponentProps { + location?: Location; + params?: P & R; + route?: PlainRoute; + router?: InjectedRouter; + routeParams?: R; +} + +export interface RouterProps extends ClassAttributes { + routes?: RouteConfig; + history?: History; + createElement?(component: RouteComponent, props: any): any; + onError?(error: any): any; + onUpdate?(): any; + render?(props: any): ReactNode; +} + +type Router = ComponentClass; declare const Router: Router; -interface Router extends React.ComponentClass { } export default Router; - -// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md - -declare namespace Router { - type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; - type RoutePattern = string; - type RouteComponents = { [key: string]: RouteComponent }; - - type ParseQueryString = (queryString: QueryString) => Query; - type StringifyQuery = (queryObject: Query) => QueryString; - - type Component = React.ReactType; - type RouteComponent = Component; - - type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; - type LeaveHook = () => void; - type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type RouteHook = (nextLocation?: Location) => any; - - type Params = { [param: string]: string }; - - type RouterListener = (error: Error, nextState: RouterState) => void; - - type LocationDescriptor = { - pathname?: Pathname - query?: Query - hash?: Href - state?: HLocationState - } - - interface RedirectFunction { - (location: LocationDescriptor): void; - /** - * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated - */ - (state: HLocationState, pathname: Pathname | Path, query?: Query): void; - } - - interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; - } - - interface RouterProps extends React.Props { - history?: History; - routes?: RouteConfig; // alias for children - createElement?: (component: RouteComponent, props: Object) => any; - onError?: (error: any) => any; - onUpdate?: () => any; - parseQueryString?: ParseQueryString; - stringifyQuery?: StringifyQuery; - basename?: string; - render?: (renderProps: React.Props<{}>) => RouterContext; - } - - interface PlainRoute { - path?: RoutePattern; - component?: RouteComponent; - components?: RouteComponents; - getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; - getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; - onEnter?: EnterHook; - onLeave?: LeaveHook; - indexRoute?: PlainRoute; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; - childRoutes?: PlainRoute[]; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; - } - - interface RouteComponentProps { - history?: History; - location?: Location; - params?: P; - route?: PlainRoute; - routeParams?: R; - routes?: PlainRoute[]; - children?: React.ReactElement; - } - - interface RouterOnContext extends History { - setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; - } - - // Wrap a component using withRouter(Component) to provide a router object - // to the Component's props, allowing the Component to programmatically call - // push and other functions. - // - // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - - interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void - replace: (pathOrLoc: Path | LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: History.Path, query?: History.Query): History.Path - createHref(path: History.Path, query?: History.Query): History.Href - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean - } -} diff --git a/react-router/lib/RouterContext.d.ts b/react-router/lib/RouterContext.d.ts index b6eab5831c..b04e6e01ae 100644 --- a/react-router/lib/RouterContext.d.ts +++ b/react-router/lib/RouterContext.d.ts @@ -1,25 +1,6 @@ -import * as React from 'react'; -import * as H from 'history'; -import Router from './Router'; +import { ComponentClass } from "react"; -declare const self: self.RouterContext; -type self = self.RouterContext; -export default self; +type RouterContext = ComponentClass; +declare const RouterContext: RouterContext; -declare namespace self { - interface RouterContextProps extends React.Props { - history?: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; - location: H.Location; - routes: Router.RouteConfig; - params: Router.Params; - components?: Router.RouteComponent[]; - } - interface RouterContext extends React.ComponentClass {} - interface RouterContextElement extends React.ReactElement { - history?: H.History; - location: H.Location; - router?: Router; - } -} \ No newline at end of file +export default RouterContext; diff --git a/react-router/lib/applyRouterMiddleware.d.ts b/react-router/lib/applyRouterMiddleware.d.ts index ed87d815db..e4d023a792 100644 --- a/react-router/lib/applyRouterMiddleware.d.ts +++ b/react-router/lib/applyRouterMiddleware.d.ts @@ -1,9 +1,9 @@ -import * as React from 'react'; -import Router from './Router'; -import RouterContext from './RouterContext'; +import { RouteComponent } from "react-router"; +import RouterContext from "react-router/lib/RouterContext"; export interface Middleware { - renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; - renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; + renderRouterContext?: (previous: RouterContext, props: any) => RouterContext; + renderRouteComponent?: (previous: RouteComponent, props: any) => RouteComponent; } -export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; + +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: any) => RouterContext; diff --git a/react-router/lib/browserHistory.d.ts b/react-router/lib/browserHistory.d.ts index aabbdc23f9..8f45db6412 100644 --- a/react-router/lib/browserHistory.d.ts +++ b/react-router/lib/browserHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const browserHistory: History; + export default browserHistory; diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index 5df481bfa1..bb2fed561b 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,3 +1,5 @@ -import * as H from 'history'; +import { History, CreateHistory } from "history"; -export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file +declare const createMemoryHistory: CreateHistory; + +export default createMemoryHistory; diff --git a/react-router/lib/hashHistory.d.ts b/react-router/lib/hashHistory.d.ts index 79f89c2f1a..6a17e65af9 100644 --- a/react-router/lib/hashHistory.d.ts +++ b/react-router/lib/hashHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const hashHistory: History; + export default hashHistory; diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index e311ea69df..bc5af4fda8 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -1,17 +1,16 @@ -import * as H from 'history'; -import Router from './Router'; +import { History } from "history"; +import { Basename, LocationDescriptor, ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; interface MatchArgs { - routes?: Router.RouteConfig; - history?: H.History; - location?: H.Location | string; - parseQueryString?: Router.ParseQueryString; - stringifyQuery?: Router.StringifyQuery; + routes: RouteConfig; + location: LocationDescriptor; + history?: History; + basename?: Basename; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; } -interface MatchState extends Router.RouterState { - history: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; -} -export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + +export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; + +export default function match(args: MatchArgs, cb: MatchCallback): void; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index d3e043b609..1371baa07b 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,7 +1,5 @@ -import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; +import { History, CreateHistoryEnhancer } from "history"; -interface CreateRouterHistory { - (options?: HistoryOptions): History & HistoryQueries; -} +declare const useRouterHistory: CreateHistoryEnhancer; -export default function useRouterHistory(createHistory: CreateHistory): CreateRouterHistory; +export default useRouterHistory; diff --git a/react-router/lib/withRouter.d.ts b/react-router/lib/withRouter.d.ts index f698d94fd0..25f9d357c7 100644 --- a/react-router/lib/withRouter.d.ts +++ b/react-router/lib/withRouter.d.ts @@ -1,4 +1,9 @@ -import * as React from 'react'; +import { ComponentClass, StatelessComponent } from "react"; -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C -export default withRouter; +interface Options { + withRef?: boolean; +} + +type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export default function withRouter

(component: ComponentConstructor

, options?: Options): ComponentClass

; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index 6c83ca180a..dda05ef9d8 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -1,22 +1,39 @@ -import * as React from "react" -import * as ReactDOM from "react-dom" -import {renderToString} from "react-dom/server"; +import * as React from "react"; +import { Component, ValidationMap } from "react"; +import * as ReactDOM from "react-dom"; +import { renderToString } from "react-dom/server"; -import { applyRouterMiddleware, browserHistory, hashHistory, match, createMemoryHistory, withRouter, routerShape, Router, Route, IndexRoute, InjectedRouter, Link, RouterOnContext, RouterContext, LinkProps} from "react-router"; +import { + applyRouterMiddleware, + browserHistory, + hashHistory, + match, + createMemoryHistory, + withRouter, + routerShape, + Router, + Route, + IndexRoute, + InjectedRouter, + Link, + RouterContext, + LinkProps +} from "react-router"; const NavLink = (props: LinkProps) => ( ) interface MasterContext { - router: RouterOnContext; + router: InjectedRouter; } -class Master extends React.Component, {}> { +class Master extends Component { - static contextTypes: React.ValidationMap = { - router: routerShape + static contextTypes: ValidationMap = { + "router": routerShape }; + context: MasterContext; navigate() { diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index d887e5e5ec..47b5b439bf 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -11,9 +11,6 @@ "strictNullChecks": false, "jsx": "react", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts new file mode 100644 index 0000000000..59f33e1960 --- /dev/null +++ b/react-router/v2/index.d.ts @@ -0,0 +1,91 @@ +// Type definitions for react-router v2.0.0 +// Project: https://github.com/rackt/react-router +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace ReactRouter; + +import * as React from 'react'; + +export const routerShape: React.Requireable + +export const locationShape: React.Requireable + +import Router from "./lib/Router"; +import Link from "./lib/Link"; +import IndexLink from "./lib/IndexLink"; +import IndexRedirect from "./lib/IndexRedirect"; +import IndexRoute from "./lib/IndexRoute"; +import Redirect from "./lib/Redirect"; +import Route from "./lib/Route"; +import * as History from "./lib/routerHistory"; +import Lifecycle from "./lib/Lifecycle"; +import RouteContext from "./lib/RouteContext"; +import browserHistory from "./lib/browserHistory"; +import hashHistory from "./lib/hashHistory"; +import useRoutes from "./lib/useRoutes"; +import { createRoutes } from "./lib/RouteUtils"; +import { formatPattern } from "./lib/PatternUtils"; +import RouterContext from "./lib/RouterContext"; +import PropTypes from "./lib/PropTypes"; +import match from "./lib/match"; +import useRouterHistory from "./lib/useRouterHistory"; +import createMemoryHistory from "./lib/createMemoryHistory"; +import withRouter from "./lib/withRouter"; +import applyRouterMiddleware from "./lib/applyRouterMiddleware"; + +// PlainRoute is defined in the API documented at: +// https://github.com/rackt/react-router/blob/master/docs/API.md +// but not included in any of the .../lib modules above. +export type PlainRoute = Router.PlainRoute; + +// The following definitions are also very useful to export +// because by using these types lots of potential type errors +// can be exposed: +export type EnterHook = Router.EnterHook; +export type LeaveHook = Router.LeaveHook; +export type ParseQueryString = Router.ParseQueryString; +export type LocationDescriptor = Router.LocationDescriptor; +export type RedirectFunction = Router.RedirectFunction; +export type RouteComponent = Router.RouteComponent; +export type RouteComponentProps = Router.RouteComponentProps; +export type RouteConfig = Router.RouteConfig; +export type RouteHook = Router.RouteHook; +export type StringifyQuery = Router.StringifyQuery; +export type RouterListener = Router.RouterListener; +export type RouterState = Router.RouterState; +export type InjectedRouter = Router.InjectedRouter; + +export type HistoryBase = History.HistoryBase; +export type RouterOnContext = Router.RouterOnContext; +export type RouteProps = Route.RouteProps; +export type LinkProps = Link.LinkProps; + +export { + Router, + Link, + IndexLink, + IndexRedirect, + IndexRoute, + Redirect, + Route, + History, + browserHistory, + hashHistory, + Lifecycle, + RouteContext, + useRoutes, + createRoutes, + formatPattern, + RouterContext, + PropTypes, + match, + useRouterHistory, + createMemoryHistory, + withRouter, + applyRouterMiddleware +}; + +export default Router; diff --git a/react-router/v2/lib/IndexLink.d.ts b/react-router/v2/lib/IndexLink.d.ts new file mode 100644 index 0000000000..56ecf82c1d --- /dev/null +++ b/react-router/v2/lib/IndexLink.d.ts @@ -0,0 +1,5 @@ +import Link from './Link'; + +declare const IndexLink: Link; +export default IndexLink; + diff --git a/react-router/v2/lib/IndexRedirect.d.ts b/react-router/v2/lib/IndexRedirect.d.ts new file mode 100644 index 0000000000..41dab299c8 --- /dev/null +++ b/react-router/v2/lib/IndexRedirect.d.ts @@ -0,0 +1,17 @@ +import Router from './Router'; +import * as React from 'react'; +import * as H from 'history'; + +declare const self: self.IndexRedirect; +type self = self.IndexRedirect; +export default self; + +declare namespace self { + interface IndexRedirectProps extends React.Props { + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface IndexRedirectElement extends React.ReactElement { } + interface IndexRedirect extends React.ComponentClass { } +} diff --git a/react-router/v2/lib/IndexRoute.d.ts b/react-router/v2/lib/IndexRoute.d.ts new file mode 100644 index 0000000000..b11b16d0e2 --- /dev/null +++ b/react-router/v2/lib/IndexRoute.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.IndexRoute; +type self = self.IndexRoute; +export default self; + +declare namespace self { + interface IndexRouteProps extends React.Props { + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + } + interface IndexRoute extends React.ComponentClass { } + interface IndexRouteElement extends React.ReactElement { } +} \ No newline at end of file diff --git a/react-router/lib/Lifecycle.d.ts b/react-router/v2/lib/Lifecycle.d.ts similarity index 100% rename from react-router/lib/Lifecycle.d.ts rename to react-router/v2/lib/Lifecycle.d.ts diff --git a/react-router/v2/lib/Link.d.ts b/react-router/v2/lib/Link.d.ts new file mode 100644 index 0000000000..d90578b9f9 --- /dev/null +++ b/react-router/v2/lib/Link.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; + +declare const Link: Link; +type Link = Link.Link; + +export default Link; + +declare namespace Link { + interface LinkProps extends React.HTMLAttributes { + activeStyle?: React.CSSProperties; + activeClassName?: string; + onlyActiveOnIndex?: boolean; + to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); + } + + interface Link extends React.ComponentClass {} + interface LinkElement extends React.ReactElement {} +} diff --git a/react-router/v2/lib/PatternUtils.d.ts b/react-router/v2/lib/PatternUtils.d.ts new file mode 100644 index 0000000000..50e90f6e49 --- /dev/null +++ b/react-router/v2/lib/PatternUtils.d.ts @@ -0,0 +1 @@ +export function formatPattern(pattern: string, params: {}): string; diff --git a/react-router/v2/lib/PropTypes.d.ts b/react-router/v2/lib/PropTypes.d.ts new file mode 100644 index 0000000000..bbd6431070 --- /dev/null +++ b/react-router/v2/lib/PropTypes.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +export function falsy(props: any, propName: string, componentName: string): Error; +export const history: React.Requireable; +export const location: React.Requireable; +export const component: React.Requireable; +export const components: React.Requireable; +export const route: React.Requireable; +export const routes: React.Requireable; + +export default { + falsy, + history, + location, + component, + components, + route +}; + diff --git a/react-router/v2/lib/Redirect.d.ts b/react-router/v2/lib/Redirect.d.ts new file mode 100644 index 0000000000..e09b576d53 --- /dev/null +++ b/react-router/v2/lib/Redirect.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.Redirect; +type self = typeof self; +export default self; + +declare namespace self { + interface RedirectProps extends React.Props { + path?: Router.RoutePattern; + from?: Router.RoutePattern; // alias for path + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface Redirect extends React.ComponentClass { } + interface RedirectElement extends React.ReactElement { } +} diff --git a/react-router/v2/lib/Route.d.ts b/react-router/v2/lib/Route.d.ts new file mode 100644 index 0000000000..2f5425b55a --- /dev/null +++ b/react-router/v2/lib/Route.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import Router from './Router'; +import { Location } from 'history'; + +declare const self: self.Route; +type self = self.Route; +export default self; + +declare namespace self { + + interface RouteProps extends React.Props { + path?: Router.RoutePattern; + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void + getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + onChange?: Router.ChangeHook; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; + } + interface Route extends React.ComponentClass {} + interface RouteElement extends React.ReactElement {} +} \ No newline at end of file diff --git a/react-router/lib/RouteContext.d.ts b/react-router/v2/lib/RouteContext.d.ts similarity index 100% rename from react-router/lib/RouteContext.d.ts rename to react-router/v2/lib/RouteContext.d.ts diff --git a/react-router/v2/lib/RouteUtils.d.ts b/react-router/v2/lib/RouteUtils.d.ts new file mode 100644 index 0000000000..7065056ff5 --- /dev/null +++ b/react-router/v2/lib/RouteUtils.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import Router from './Router'; + +type E = React.ReactElement; +export function isReactChildren(object: E | E[]): boolean; +export function createRouteFromReactElement(element: E): Router.PlainRoute; +export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; +export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; diff --git a/react-router/v2/lib/Router.d.ts b/react-router/v2/lib/Router.d.ts new file mode 100644 index 0000000000..a9c5417f47 --- /dev/null +++ b/react-router/v2/lib/Router.d.ts @@ -0,0 +1,116 @@ +import * as React from 'react'; +import RouterContext from './RouterContext'; +import { + QueryString, Query, + Location, LocationDescriptor, LocationState as HLocationState, + History, Href, + Pathname, Path } from 'history'; + +declare const Router: Router; +interface Router extends React.ComponentClass { } + +export default Router; + +// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md + +declare namespace Router { + type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; + type RoutePattern = string; + type RouteComponents = { [key: string]: RouteComponent }; + + type ParseQueryString = (queryString: QueryString) => Query; + type StringifyQuery = (queryObject: Query) => QueryString; + + type Component = React.ReactType; + type RouteComponent = Component; + + type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; + type LeaveHook = () => void; + type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; + type RouteHook = (nextLocation?: Location) => any; + + type Params = { [param: string]: string }; + + type RouterListener = (error: Error, nextState: RouterState) => void; + + type LocationDescriptor = { + pathname?: Pathname + query?: Query + hash?: Href + state?: HLocationState + } + + interface RedirectFunction { + (location: LocationDescriptor): void; + /** + * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated + */ + (state: HLocationState, pathname: Pathname | Path, query?: Query): void; + } + + interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; + } + + interface RouterProps extends React.Props { + history?: History; + routes?: RouteConfig; // alias for children + createElement?: (component: RouteComponent, props: Object) => any; + onError?: (error: any) => any; + onUpdate?: () => any; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; + basename?: string; + render?: (renderProps: React.Props<{}>) => RouterContext; + } + + interface PlainRoute { + path?: RoutePattern; + component?: RouteComponent; + components?: RouteComponents; + getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; + getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; + onEnter?: EnterHook; + onLeave?: LeaveHook; + indexRoute?: PlainRoute; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; + childRoutes?: PlainRoute[]; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; + } + + interface RouteComponentProps { + history?: History; + location?: Location; + params?: P; + route?: PlainRoute; + routeParams?: R; + routes?: PlainRoute[]; + children?: React.ReactElement; + } + + interface RouterOnContext extends History { + setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; + isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; + } + + // Wrap a component using withRouter(Component) to provide a router object + // to the Component's props, allowing the Component to programmatically call + // push and other functions. + // + // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md + + interface InjectedRouter { + push: (pathOrLoc: Path | LocationDescriptor) => void + replace: (pathOrLoc: Path | LocationDescriptor) => void + go: (n: number) => void + goBack: () => void + goForward: () => void + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void + createPath(path: History.Path, query?: History.Query): History.Path + createHref(path: History.Path, query?: History.Query): History.Href + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean + } +} diff --git a/react-router/v2/lib/RouterContext.d.ts b/react-router/v2/lib/RouterContext.d.ts new file mode 100644 index 0000000000..b6eab5831c --- /dev/null +++ b/react-router/v2/lib/RouterContext.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import * as H from 'history'; +import Router from './Router'; + +declare const self: self.RouterContext; +type self = self.RouterContext; +export default self; + +declare namespace self { + interface RouterContextProps extends React.Props { + history?: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; + location: H.Location; + routes: Router.RouteConfig; + params: Router.Params; + components?: Router.RouteComponent[]; + } + interface RouterContext extends React.ComponentClass {} + interface RouterContextElement extends React.ReactElement { + history?: H.History; + location: H.Location; + router?: Router; + } +} \ No newline at end of file diff --git a/react-router/v2/lib/applyRouterMiddleware.d.ts b/react-router/v2/lib/applyRouterMiddleware.d.ts new file mode 100644 index 0000000000..ed87d815db --- /dev/null +++ b/react-router/v2/lib/applyRouterMiddleware.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +import Router from './Router'; +import RouterContext from './RouterContext'; + +export interface Middleware { + renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; + renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; +} +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; diff --git a/react-router/v2/lib/browserHistory.d.ts b/react-router/v2/lib/browserHistory.d.ts new file mode 100644 index 0000000000..aabbdc23f9 --- /dev/null +++ b/react-router/v2/lib/browserHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const browserHistory: History; +export default browserHistory; diff --git a/react-router/v2/lib/createMemoryHistory.d.ts b/react-router/v2/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..5df481bfa1 --- /dev/null +++ b/react-router/v2/lib/createMemoryHistory.d.ts @@ -0,0 +1,3 @@ +import * as H from 'history'; + +export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file diff --git a/react-router/v2/lib/hashHistory.d.ts b/react-router/v2/lib/hashHistory.d.ts new file mode 100644 index 0000000000..79f89c2f1a --- /dev/null +++ b/react-router/v2/lib/hashHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const hashHistory: History; +export default hashHistory; diff --git a/react-router/v2/lib/match.d.ts b/react-router/v2/lib/match.d.ts new file mode 100644 index 0000000000..e311ea69df --- /dev/null +++ b/react-router/v2/lib/match.d.ts @@ -0,0 +1,17 @@ +import * as H from 'history'; +import Router from './Router'; + +interface MatchArgs { + routes?: Router.RouteConfig; + history?: H.History; + location?: H.Location | string; + parseQueryString?: Router.ParseQueryString; + stringifyQuery?: Router.StringifyQuery; +} +interface MatchState extends Router.RouterState { + history: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; +} +export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + diff --git a/react-router/lib/routerHistory.d.ts b/react-router/v2/lib/routerHistory.d.ts similarity index 100% rename from react-router/lib/routerHistory.d.ts rename to react-router/v2/lib/routerHistory.d.ts diff --git a/react-router/v2/lib/useRouterHistory.d.ts b/react-router/v2/lib/useRouterHistory.d.ts new file mode 100644 index 0000000000..d3e043b609 --- /dev/null +++ b/react-router/v2/lib/useRouterHistory.d.ts @@ -0,0 +1,7 @@ +import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; + +interface CreateRouterHistory { + (options?: HistoryOptions): History & HistoryQueries; +} + +export default function useRouterHistory(createHistory: CreateHistory): CreateRouterHistory; diff --git a/react-router/lib/useRoutes.d.ts b/react-router/v2/lib/useRoutes.d.ts similarity index 100% rename from react-router/lib/useRoutes.d.ts rename to react-router/v2/lib/useRoutes.d.ts diff --git a/react-router/v2/lib/withRouter.d.ts b/react-router/v2/lib/withRouter.d.ts new file mode 100644 index 0000000000..f698d94fd0 --- /dev/null +++ b/react-router/v2/lib/withRouter.d.ts @@ -0,0 +1,4 @@ +import * as React from 'react'; + +declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C +export default withRouter; From 61af45367251ddb146a5c483f4cb2e6e88883868 Mon Sep 17 00:00:00 2001 From: Hutson Betts Date: Tue, 17 Jan 2017 14:03:06 -0600 Subject: [PATCH 21/85] fix(mocha): add index definition Add index definition to IHookCallbackContext to support Mocha's built-in context shared between setup, tear-down, and test cases. Context is Mocha's support for Shared Behaviors (https://github.com/mochajs/mocha/wiki/Shared-Behaviours) --- mocha/index.d.ts | 2 ++ mocha/mocha-tests.ts | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 9ac84fa097..ec6fc5e142 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -118,6 +118,7 @@ declare namespace Mocha { interface IHookCallbackContext { skip(): void; timeout(ms: number): void; + [index: string]: any; } @@ -126,6 +127,7 @@ declare namespace Mocha { timeout(ms: number): void; retries(n: number): void; slow(ms: number): void; + [index: string]: any; } /** Partial interface for Mocha's `Runnable` class. */ diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index fc17a18221..8e8dc0d938 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -47,6 +47,8 @@ function test_it() { it('does something', () => { }); + it('does something', function () { this['sharedState'] = true; }); + it('does something', (done) => { done(); }); it.only('does something', () => { }); @@ -64,6 +66,8 @@ function test_test() { test('does something', () => { }); + test('does something', function () { this['sharedState'] = true; }); + test('does something', (done) => { done(); }); test.only('does something', () => { }); @@ -81,6 +85,8 @@ function test_specify() { specify('does something', () => { }); + specify('does something', function () { this['sharedState'] = true; }); + specify('does something', (done) => { done(); }); specify.only('does something', () => { }); @@ -97,6 +103,8 @@ function test_specify() { function test_before() { before(() => { }); + before(function () { this['sharedState'] = true; }); + before((done) => { done(); }); before("my description", () => { }); @@ -120,6 +128,17 @@ function test_setup() { string = this.currentTest.state; }); + setup(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + setup(function (done) { done(); boolean = this.currentTest.async; @@ -135,6 +154,8 @@ function test_setup() { function test_after() { after(() => { }); + after(function () { this['sharedState'] = true; }); + after((done) => { done(); }); after("my description", () => { }); @@ -153,6 +174,17 @@ function test_teardown() { string = this.currentTest.state; }); + teardown(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + teardown(function(done) { done(); boolean = this.currentTest.async; @@ -176,6 +208,17 @@ function test_beforeEach() { string = this.currentTest.state; }); + beforeEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + beforeEach(function (done) { done(); boolean = this.currentTest.async; @@ -212,6 +255,8 @@ function test_beforeEach() { function test_suiteSetup() { suiteSetup(() => { }); + suiteSetup(function () { this['sharedState'] = true; }); + suiteSetup((done) => { done(); }); } @@ -226,6 +271,17 @@ function test_afterEach() { string = this.currentTest.state; }); + afterEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + afterEach(function (done) { done(); boolean = this.currentTest.async; @@ -263,6 +319,8 @@ function test_afterEach() { function test_suiteTeardown() { suiteTeardown(() => { }); + suiteTeardown(function () { this['sharedState'] = true; }); + suiteTeardown((done) => { done(); }); } From 42e178120b56f2bd1ec20fb1075f9b709ca68f13 Mon Sep 17 00:00:00 2001 From: Marco Arruda Date: Tue, 17 Jan 2017 20:20:21 -0200 Subject: [PATCH 22/85] get actionlib servers --- roslib/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/roslib/index.d.ts b/roslib/index.d.ts index fbb6deff6e..14fe2c1e3e 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -66,6 +66,16 @@ declare namespace ROSLIB { */ callOnConnection(message:any):void; + /** + * Retrieves list of actionlib servers in ROS as an array. + * + * @param callback function with params: + * * action_servers - Array of actionlib servers names + * @param failedCallback - the callback function when the ros call failed (optional). Params: + * * error - the error message reported by ROS + */ + getActionServers(callback:(action_servers:string[]) => void, failedCallback?:(error:any)=>void):void; + /** * Retrieves list of topics in ROS as an array. * From 9f396a35febe9d229c876d8cbeca26627594a604 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Wed, 18 Jan 2017 17:09:27 +0100 Subject: [PATCH 23/85] Add "tslint.json" file. Replace "major.minor.build" by "major.minor". --- express-rate-limit/index.d.ts | 2 +- express-rate-limit/tsconfig.json | 38 +++++++++++++++++--------------- express-rate-limit/tslint.json | 1 + shipit-utils/index.d.ts | 2 +- shipit-utils/tsconfig.json | 38 +++++++++++++++++--------------- shipit-utils/tslint.json | 1 + shipit/index.d.ts | 2 +- shipit/tsconfig.json | 38 +++++++++++++++++--------------- shipit/tslint.json | 1 + 9 files changed, 66 insertions(+), 57 deletions(-) create mode 100644 express-rate-limit/tslint.json create mode 100644 shipit-utils/tslint.json create mode 100644 shipit/tslint.json diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts index 57eb003694..07cb5853a5 100644 --- a/express-rate-limit/index.d.ts +++ b/express-rate-limit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for express-rate-limit 2.6.0 +// Type definitions for express-rate-limit 2.6 // Project: https://github.com/nfriedly/express-rate-limit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json index 560edfef9d..ca3c32c3bb 100644 --- a/express-rate-limit/tsconfig.json +++ b/express-rate-limit/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "express-rate-limit-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] } diff --git a/express-rate-limit/tslint.json b/express-rate-limit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/express-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index a66b681c37..63df44974f 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit-utils 1.4.0 +// Type definitions for shipit-utils 1.4 // Project: https://github.com/shipitjs/shipit-utils // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json index fa4b1ce3b6..d2fdb45d17 100644 --- a/shipit-utils/tsconfig.json +++ b/shipit-utils/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "shipit-utils-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-utils-tests.ts" + ] } diff --git a/shipit-utils/tslint.json b/shipit-utils/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit-utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit/index.d.ts b/shipit/index.d.ts index ab44d7abd8..7b153ae197 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit-cli 1.5.1 +// Type definitions for shipit-cli 1.5 // Project: https://github.com/shipitjs/shipit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json index 254ac2d9a5..17049e7271 100644 --- a/shipit/tsconfig.json +++ b/shipit/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "shipit-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-tests.ts" + ] } diff --git a/shipit/tslint.json b/shipit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From b033ae77a87c91fb93f351a29088e3806aa55b12 Mon Sep 17 00:00:00 2001 From: Andrew Zheng Date: Wed, 18 Jan 2017 15:14:17 -0800 Subject: [PATCH 24/85] Add optional parameter to verifyNoOutstandingExpectation() --- angular-mocks/angular-mocks-tests.ts | 1 + angular-mocks/index.d.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/angular-mocks/angular-mocks-tests.ts b/angular-mocks/angular-mocks-tests.ts index 8ea42e4122..cabbf7c578 100644 --- a/angular-mocks/angular-mocks-tests.ts +++ b/angular-mocks/angular-mocks-tests.ts @@ -118,6 +118,7 @@ httpBackendService.flush(); httpBackendService.flush(1234); httpBackendService.resetExpectations(); httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingExpectation(false); httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index ddded4d0a8..767eb65f04 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -132,8 +132,9 @@ declare module 'angular' { /** * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything expect false to trigger digest. */ - verifyNoOutstandingExpectation(): void; + verifyNoOutstandingExpectation(digest?: boolean): void; /** * Verifies that there are no outstanding requests that need to be flushed. From d11a1c562bae120d910d3542552285e5a142fbb1 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 09:46:36 +0900 Subject: [PATCH 25/85] Update some definitions based on history v2 --- react-router/index.d.ts | 13 +++++++++++++ react-router/lib/Router.d.ts | 4 +++- react-router/lib/createMemoryHistory.d.ts | 3 ++- react-router/lib/useRouterHistory.d.ts | 5 +++-- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 8398838aef..2b10a4cbcb 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -3,6 +3,19 @@ // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/* Replacement from old history definitions */ +export interface HistoryOptions { + getCurrentLocation?(): Location; + getUserConfirmation?(message: string, callback: (result: boolean) => void): void; + pushLocation?(nextLocation: Location): void; + replaceLocation?(nextLocation: Location): void; + go?(n: number): void; + keyLength?: number; +} + +export type CreateHistory = (options?: HistoryOptions) => T; +export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; + export { Basename, ChangeHook, diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index 160694953f..dbd2d43fff 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,5 +1,6 @@ import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { + Action, Hash, History, Href, @@ -11,12 +12,13 @@ import { } from "history"; import { PlainRoute } from "react-router"; +/* Replacement from old history definitions */ export type Basename = string; export type Query = any; -export type Action = "PUSH" | "REPLACE" | "POP"; export interface Params { [key: string]: string; } + export type RoutePattern = string; export type RouteComponent = ComponentClass | StatelessComponent; export interface RouteComponents { diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index bb2fed561b..038e707e6b 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,4 +1,5 @@ -import { History, CreateHistory } from "history"; +import { History } from "history"; +import { CreateHistory } from "react-router"; declare const createMemoryHistory: CreateHistory; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index 1371baa07b..7dc2bdd3ab 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,5 +1,6 @@ -import { History, CreateHistoryEnhancer } from "history"; +import { History } from "history"; +import { CreateHistoryEnhancer } from "react-router"; -declare const useRouterHistory: CreateHistoryEnhancer; +declare const useRouterHistory: CreateHistoryEnhancer; export default useRouterHistory; From 5ce5e784689f0ddccc1e7cdba6df700f2f435cef Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 10:15:36 +0900 Subject: [PATCH 26/85] Remove unnecessary files, add tsconfig for old version --- react-router/index.d.ts.orig | 109 ---------- react-router/lib/Route.d.ts.orig | 49 ----- react-router/lib/Router.d.ts.orig | 213 -------------------- react-router/lib/useRouterHistory.d.ts.orig | 10 - react-router/lib/withRouter.d.ts.orig | 14 -- react-router/v2/tsconfig.json | 27 +++ 6 files changed, 27 insertions(+), 395 deletions(-) delete mode 100644 react-router/index.d.ts.orig delete mode 100644 react-router/lib/Route.d.ts.orig delete mode 100644 react-router/lib/Router.d.ts.orig delete mode 100644 react-router/lib/useRouterHistory.d.ts.orig delete mode 100644 react-router/lib/withRouter.d.ts.orig create mode 100644 react-router/v2/tsconfig.json diff --git a/react-router/index.d.ts.orig b/react-router/index.d.ts.orig deleted file mode 100644 index 52227f4d95..0000000000 --- a/react-router/index.d.ts.orig +++ /dev/null @@ -1,109 +0,0 @@ -<<<<<<< HEAD -// Type definitions for react-router 3.0 -======= -// Type definitions for react-router 2.0 ->>>>>>> upstream/master -// Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* Replacement from old history definitions */ -export interface HistoryOptions { - getCurrentLocation?(): Location; - getUserConfirmation?(message: string, callback: (result: boolean) => void): void; - pushLocation?(nextLocation: Location): void; - replaceLocation?(nextLocation: Location): void; - go?(n: number): void; - keyLength?: number; -} - -export type CreateHistory = (options?: HistoryOptions) => T; -export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; - -<<<<<<< HEAD -export { - Basename, - ChangeHook, - EnterHook, - InjectedRouter, - LeaveHook, - Location, - LocationDescriptor, - ParseQueryString, - RouteComponent, - RouteComponents, - RouteComponentProps, - RouteConfig, - RoutePattern, - RouterProps, - RouterState, - StringifyQuery, - Query -} from "react-router/lib/Router"; -export { LinkProps } from "react-router/lib/Link"; -export { IndexLinkProps } from "react-router/lib/IndexLink"; -export { RouteProps, PlainRoute } from "react-router/lib/Route"; -export { IndexRouteProps } from "react-router/lib/IndexRoute"; -export { RedirectProps } from "react-router/lib/Redirect"; -export { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -======= -import * as React from 'react'; - -export const routerShape: React.Requireable; - -export const locationShape: React.Requireable; - -import Router from "./lib/Router"; -import Link from "./lib/Link"; -import IndexLink from "./lib/IndexLink"; -import IndexRedirect from "./lib/IndexRedirect"; -import IndexRoute from "./lib/IndexRoute"; -import Redirect from "./lib/Redirect"; -import Route from "./lib/Route"; -import * as History from "./lib/routerHistory"; -import Lifecycle from "./lib/Lifecycle"; -import RouteContext from "./lib/RouteContext"; -import browserHistory from "./lib/browserHistory"; -import hashHistory from "./lib/hashHistory"; -import useRoutes from "./lib/useRoutes"; -import { createRoutes } from "./lib/RouteUtils"; -import { formatPattern } from "./lib/PatternUtils"; -import RouterContext from "./lib/RouterContext"; -import PropTypes from "./lib/PropTypes"; -import match from "./lib/match"; -import useRouterHistory from "./lib/useRouterHistory"; -import createMemoryHistory from "./lib/createMemoryHistory"; -import withRouter from "./lib/withRouter"; -import applyRouterMiddleware from "./lib/applyRouterMiddleware"; - -// PlainRoute is defined in the API documented at: -// https://github.com/rackt/react-router/blob/master/docs/API.md -// but not included in any of the .../lib modules above. -export type PlainRoute = Router.PlainRoute; ->>>>>>> upstream/master - -/* components */ -export { default as Router } from "react-router/lib/Router"; -export { default as Link } from "react-router/lib/Link"; -export { default as IndexLink } from "react-router/lib/IndexLink"; -export { default as withRouter } from "react-router/lib/withRouter"; - -/* components (configuration) */ -export { default as IndexRedirect } from "react-router/lib/IndexRedirect"; -export { default as IndexRoute } from "react-router/lib/IndexRoute"; -export { default as Redirect } from "react-router/lib/Redirect"; -export { default as Route } from "react-router/lib/Route"; - -/* utils */ -export { createRoutes } from "react-router/lib/RouteUtils"; -export { default as RouterContext } from "react-router/lib/RouterContext"; -export { routerShape, locationShape } from "react-router/lib/PropTypes"; -export { default as match } from "react-router/lib/match"; -export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; -export { formatPattern } from "react-router/lib/PatternUtils"; -export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; - -/* histories */ -export { default as browserHistory } from "react-router/lib/browserHistory"; -export { default as hashHistory } from "react-router/lib/hashHistory"; -export { default as createMemoryHistory } from "react-router/lib/createMemoryHistory"; diff --git a/react-router/lib/Route.d.ts.orig b/react-router/lib/Route.d.ts.orig deleted file mode 100644 index c8a211517c..0000000000 --- a/react-router/lib/Route.d.ts.orig +++ /dev/null @@ -1,49 +0,0 @@ -import { ComponentClass, ClassAttributes } from "react"; -import { LocationState } from "history"; -import { - EnterHook, - ChangeHook, - LeaveHook, - RouteComponent, - RouteComponents, - RoutePattern, - RouterState -} from "react-router"; -import { IndexRouteProps } from "react-router/lib/IndexRoute"; - -export interface RouteProps extends IndexRouteProps { - path?: RoutePattern; -} - -type Route = ComponentClass; -declare const Route: Route; - -<<<<<<< HEAD -export default Route; - -type RouteCallback = (err: any, route: PlainRoute) => void; -type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; - -export interface PlainRoute extends RouteProps { - childRoutes?: PlainRoute[]; - getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; - indexRoute?: PlainRoute; - getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; -} -======= - interface RouteProps extends React.Props { - path?: Router.RoutePattern; - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - onChange?: Router.ChangeHook; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; - } - interface Route extends React.ComponentClass {} - interface RouteElement extends React.ReactElement {} -} ->>>>>>> upstream/master diff --git a/react-router/lib/Router.d.ts.orig b/react-router/lib/Router.d.ts.orig deleted file mode 100644 index 8b77e41bdf..0000000000 --- a/react-router/lib/Router.d.ts.orig +++ /dev/null @@ -1,213 +0,0 @@ -import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; -import { - Action, - Hash, - History, - Href, - LocationKey, - LocationState, - Path, - Pathname, - Search -} from "history"; -import { PlainRoute } from "react-router"; - -/* Replacement from old history definitions */ -export type Basename = string; -export type Query = any; -export interface Params { - [key: string]: string; -} - -export type RoutePattern = string; -export type RouteComponent = ComponentClass | StatelessComponent; -export interface RouteComponents { - [name: string]: RouteComponent; -} -export type RouteConfig = ReactNode | PlainRoute | PlainRoute[]; - -export type ParseQueryString = (queryString: Search) => Query; -export type StringifyQuery = (queryObject: Query) => Search; - -type AnyFunction = (...args: any[]) => any; - -export type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; -export type LeaveHook = (prevState: RouterState) => any; -export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; -export type RouteHook = (nextLocation?: Location) => any; - -<<<<<<< HEAD -export interface Location { - patname: Pathname; - search: Search; - query: Query; - state: LocationState; - action: Action; - key: LocationKey; -======= -// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md - -declare namespace Router { - type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; - type RoutePattern = string; - interface RouteComponents { [key: string]: RouteComponent; } - - type ParseQueryString = (queryString: QueryString) => Query; - type StringifyQuery = (queryObject: Query) => QueryString; - - type Component = React.ReactType; - type RouteComponent = Component; - - type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; - type LeaveHook = () => void; - type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type RouteHook = (nextLocation?: Location) => any; - - interface Params { [param: string]: string; } - - type RouterListener = (error: Error, nextState: RouterState) => void; - - interface LocationDescriptor { - pathname?: Pathname; - query?: Query; - hash?: Href; - state?: HLocationState; - } - - interface RedirectFunction { - (location: LocationDescriptor): void; - /** - * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated - */ - (state: HLocationState, pathname: Pathname | Path, query?: Query): void; - } - - interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; - } - - interface RouterProps extends React.Props { - history?: History; - routes?: RouteConfig; // alias for children - createElement?: (component: RouteComponent, props: Object) => any; - onError?: (error: any) => any; - onUpdate?: () => any; - parseQueryString?: ParseQueryString; - stringifyQuery?: StringifyQuery; - basename?: string; - render?: (renderProps: React.Props<{}>) => RouterContext; - } - - interface PlainRoute { - path?: RoutePattern; - component?: RouteComponent; - components?: RouteComponents; - getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; - getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; - onEnter?: EnterHook; - onLeave?: LeaveHook; - indexRoute?: PlainRoute; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; - childRoutes?: PlainRoute[]; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; - } - - interface RouteComponentProps { - history?: History; - location?: Location; - params?: P; - route?: PlainRoute; - routeParams?: R; - routes?: PlainRoute[]; - children?: React.ReactElement; - } - - interface RouterOnContext extends History { - setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; - } - - // Wrap a component using withRouter(Component) to provide a router object - // to the Component's props, allowing the Component to programmatically call - // push and other functions. - // - // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - - interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void; - replace: (pathOrLoc: Path | LocationDescriptor) => void; - go: (n: number) => void; - goBack: () => void; - goForward: () => void; - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; - createPath(path: History.Path, query?: History.Query): History.Path; - createHref(path: History.Path, query?: History.Query): History.Href; - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; - } ->>>>>>> upstream/master -} - -export interface LocationDescriptorObject { - pathname?: Pathname; - query?: Query; - hash?: Hash; - state?: LocationState; -} - -export type LocationDescriptor = Path | LocationDescriptorObject; - -export interface RedirectFunction { - (location: LocationDescriptor): void; - (state: LocationState, pathname: Pathname | Path, query?: Query): void; -} - -export interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; -} - -type LocationFunction = (location: LocationDescriptor) => void; -type GoFunction = (n: number) => void; -type NavigateFunction = () => void; -type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; -type LeaveHookFunction = (route: any, callback: RouteHook) => void; -type CreatePartFunction = (path: Path, query?: any) => Part; - -export interface InjectedRouter { - push: LocationFunction; - replace: LocationFunction; - go: GoFunction; - goBack: NavigateFunction; - goForward: NavigateFunction; - setRouteLeaveHook: LeaveHookFunction; - createPath: CreatePartFunction; - createHref: CreatePartFunction; - isActive: ActiveFunction; -} - -export interface RouteComponentProps { - location?: Location; - params?: P & R; - route?: PlainRoute; - router?: InjectedRouter; - routeParams?: R; -} - -export interface RouterProps extends ClassAttributes { - routes?: RouteConfig; - history?: History; - createElement?(component: RouteComponent, props: any): any; - onError?(error: any): any; - onUpdate?(): any; - render?(props: any): ReactNode; -} - -type Router = ComponentClass; -declare const Router: Router; - -export default Router; diff --git a/react-router/lib/useRouterHistory.d.ts.orig b/react-router/lib/useRouterHistory.d.ts.orig deleted file mode 100644 index 01609c5a48..0000000000 --- a/react-router/lib/useRouterHistory.d.ts.orig +++ /dev/null @@ -1,10 +0,0 @@ -import { History } from "history"; -import { CreateHistoryEnhancer } from "react-router"; - -<<<<<<< HEAD -declare const useRouterHistory: CreateHistoryEnhancer; - -export default useRouterHistory; -======= -export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; ->>>>>>> upstream/master diff --git a/react-router/lib/withRouter.d.ts.orig b/react-router/lib/withRouter.d.ts.orig deleted file mode 100644 index ab51b2111e..0000000000 --- a/react-router/lib/withRouter.d.ts.orig +++ /dev/null @@ -1,14 +0,0 @@ -import { ComponentClass, StatelessComponent } from "react"; - -<<<<<<< HEAD -interface Options { - withRef?: boolean; -} - -type ComponentConstructor

= ComponentClass

| StatelessComponent

; - -export default function withRouter

(component: ComponentConstructor

, options?: Options): ComponentClass

; -======= -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; -export default withRouter; ->>>>>>> upstream/master diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json new file mode 100644 index 0000000000..7cc347abc4 --- /dev/null +++ b/react-router/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "history": ["history/v2"], + "react-router": ["react-router/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-router-redux-tests.ts" + ] +} From f49ca4f7ab7ee036e3aa1deab3558758c70326f0 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:13:06 +0900 Subject: [PATCH 27/85] Update react-router-bootstrap definitions --- react-router-bootstrap/index.d.ts | 44 ++----------------- .../lib/IndexLinkContainer.d.ts | 7 +++ react-router-bootstrap/lib/LinkContainer.d.ts | 7 +++ react-router-bootstrap/tsconfig.json | 3 -- 4 files changed, 18 insertions(+), 43 deletions(-) create mode 100644 react-router-bootstrap/lib/IndexLinkContainer.d.ts create mode 100644 react-router-bootstrap/lib/LinkContainer.d.ts diff --git a/react-router-bootstrap/index.d.ts b/react-router-bootstrap/index.d.ts index b4b36006ec..c414d8f3b0 100644 --- a/react-router-bootstrap/index.d.ts +++ b/react-router-bootstrap/index.d.ts @@ -1,43 +1,7 @@ -// Type definitions for react-router-bootstrap +// Type definitions for react-router-bootstrap 0.23 // Project: https://github.com/react-bootstrap/react-router-bootstrap -// Definitions by: Vincent Lesierse +// Definitions by: Vincent Lesierse , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - -declare namespace ReactRouterBootstrap { - interface LinkContainerProps extends ReactRouter.LinkProps { - disabled?: boolean - } - interface LinkContainer extends React.ComponentClass {} - interface LinkContainerElement extends React.ReactElement {} - const LinkContainer: LinkContainer - - const IndexLinkContainer: LinkContainer -} - -declare module "react-router-bootstrap/lib/LinkContainer" { - - export default ReactRouterBootstrap.LinkContainer - -} - -declare module "react-router-bootstrap/lib/IndexLinkContainer" { - - export default ReactRouterBootstrap.IndexLinkContainer - -} - -declare module "react-router-bootstrap" { - - import LinkContainer from "react-router-bootstrap/lib/LinkContainer" - - import IndexLinkContainer from "react-router-bootstrap/lib/IndexLinkContainer" - - export { - LinkContainer, - IndexLinkContainer - } - -} +export { default as LinkContainer } from "react-router-bootstrap/lib/LinkContainer" +export { default as IndexLinkContainer } from "react-router-bootstrap/lib/IndexLinkContainer" diff --git a/react-router-bootstrap/lib/IndexLinkContainer.d.ts b/react-router-bootstrap/lib/IndexLinkContainer.d.ts new file mode 100644 index 0000000000..045edc1fde --- /dev/null +++ b/react-router-bootstrap/lib/IndexLinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; + +type IndexLinkContainer = ComponentClass; +declare const IndexLinkContainer: IndexLinkContainer; + +export default IndexLinkContainer; diff --git a/react-router-bootstrap/lib/LinkContainer.d.ts b/react-router-bootstrap/lib/LinkContainer.d.ts new file mode 100644 index 0000000000..df5ac3cbdb --- /dev/null +++ b/react-router-bootstrap/lib/LinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { LinkProps } from "react-router/lib/Link"; + +type LinkContainer = ComponentClass; +declare const LinkContainer: LinkContainer; + +export default LinkContainer; diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 7e111b1004..ecee2cb765 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -10,9 +10,6 @@ "strictNullChecks": false, "jsx": "preserve", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], From 4b89363df8ae1f1da5edba6f365c8c0a50d2d3f5 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:17:58 +0900 Subject: [PATCH 28/85] Fix tsconfig files --- react-router-bootstrap/tsconfig.json | 3 +++ react-router/tsconfig.json | 13 ++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index ecee2cb765..2fc57383ed 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -17,6 +17,9 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, + "include": [ + "lib/*.d.ts" + ], "files": [ "index.d.ts", "react-router-bootstrap-tests.tsx" diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index 8e5f5d47b6..e06f11b4a3 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "react-router-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -20,5 +16,12 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "include": [ + "lib/*.d.ts" + ], + "files": [ + "index.d.ts", + "react-router-tests.tsx" + ], } From 2bef57bed0b9d40a708e845f52ca30cb2374b9c2 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:22:18 +0900 Subject: [PATCH 29/85] Fix react-router tsconfig --- react-router/tsconfig.json | 2 +- react-router/tslint.json | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index e06f11b4a3..d13560189e 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -23,5 +23,5 @@ "files": [ "index.d.ts", "react-router-tests.tsx" - ], + ] } diff --git a/react-router/tslint.json b/react-router/tslint.json index e050abdce9..f9e30021f4 100644 --- a/react-router/tslint.json +++ b/react-router/tslint.json @@ -1,7 +1,3 @@ { - "extends": "../tslint.json", - "rules": { - "forbidden-types": false, - "no-empty-interface": false - } -} \ No newline at end of file + "extends": "../tslint.json" +} From 3ce2018675b0606bd4149c59e602f64219f2535a Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 12:12:31 +0900 Subject: [PATCH 30/85] Change include to files in tsconfig --- react-router-bootstrap/tsconfig.json | 5 ++--- react-router/tsconfig.json | 21 ++++++++++++++++++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 2fc57383ed..1760fc3f1a 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -17,11 +17,10 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ - "lib/*.d.ts" - ], "files": [ "index.d.ts", + "lib/IndexLinkContainer.d.ts", + "lib/LinkContainer.d.ts", "react-router-bootstrap-tests.tsx" ] } diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index d13560189e..c013e2c959 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -17,11 +17,26 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ - "lib/*.d.ts" - ], "files": [ "index.d.ts", + "lib/applyRouterMiddleware.d.ts", + "lib/browserHistory.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/hashHistory.d.ts", + "lib/IndexLink.d.ts", + "lib/IndexRedirect.d.ts", + "lib/IndexRoute.d.ts", + "lib/Link.d.ts", + "lib/match.d.ts", + "lib/PatternUtils.d.ts", + "lib/PropTypes.d.ts", + "lib/Redirect.d.ts", + "lib/Route.d.ts", + "lib/Router.d.ts", + "lib/RouterContext.d.ts", + "lib/RouteUtils.d.ts", + "lib/useRouterHistory.d.ts", + "lib/withRouter.d.ts", "react-router-tests.tsx" ] } From ab95e31c3f86178515ec6450b50f5d80feaef881 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 12:40:16 +0900 Subject: [PATCH 31/85] Remove test file from v2 tsconfig --- react-router/v2/tsconfig.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json index 7cc347abc4..c92402947c 100644 --- a/react-router/v2/tsconfig.json +++ b/react-router/v2/tsconfig.json @@ -21,7 +21,6 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "react-router-redux-tests.ts" + "index.d.ts" ] } From 2b5726e1b8f69514afd202e78c967e5cc6bac54a Mon Sep 17 00:00:00 2001 From: karak Date: Thu, 19 Jan 2017 15:19:50 +0900 Subject: [PATCH 32/85] [material-ui] Fixed muiThemeable on decorator usage #9843 --- material-ui/index.d.ts | 5 ++++- material-ui/material-ui-tests.tsx | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 716505987d..f60bb7e7ae 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -452,7 +452,10 @@ declare namespace __MaterialUI { var lightBaseTheme: RawTheme; var darkBaseTheme: RawTheme; - export function muiThemeable, P, S>(): (component: TComponent) => TComponent; + export function muiThemeable(): < + TComponent extends React.ComponentClass

| React.StatelessComponent

, + P extends {muiTheme?: MuiTheme} + >(component: TComponent) => TComponent; interface MuiThemeProviderProps { muiTheme?: Styles.MuiTheme; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 04b8f0ec32..8dcc0fe07e 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -7,6 +7,7 @@ import * as React from 'react'; import {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import {muiThemeable} from 'material-ui/styles/muiThemeable'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import {MuiTheme} from 'material-ui/styles'; @@ -321,6 +322,35 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { } +const MuiThemeableFunction = muiThemeable()((props: {label: string, muiTheme?: MuiTheme}) => { + return ( + + Applied the Theme to functional component: {props.label}. + + ); +}); + +@muiThemeable() +class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}, {}> { + render() { + return ( + + Applied the Theme to class component decorated: {this.props.label}. + + ); + } +} + +const MuiThemeableContainer = (props: {}) => ( + +

+ + +
+ +); + + // "http://www.material-ui.com/#/customization/inline-styles" const InlineStylesCheckbox = () => ( Date: Thu, 19 Jan 2017 11:23:27 +0100 Subject: [PATCH 33/85] Add user object to Express.Request The JWT authentication middleware authenticates callers using a JWT. If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control. --- express-jwt/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index e721094edc..edffeb9632 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -37,3 +37,10 @@ declare namespace jwt { unless?: typeof unless; } } +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} From a4dec0334cc80b0f943f114770945bb154f9364d Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 20 Jan 2017 09:03:18 +0900 Subject: [PATCH 34/85] Fix react-breadcrumbs --- react-breadcrumbs/index.d.ts | 23 +++++++++-------------- react-breadcrumbs/tsconfig.json | 3 ++- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/react-breadcrumbs/index.d.ts b/react-breadcrumbs/index.d.ts index 1d247f215d..67f1a89090 100644 --- a/react-breadcrumbs/index.d.ts +++ b/react-breadcrumbs/index.d.ts @@ -1,13 +1,17 @@ -// Type definitions for react-breadcrumbs 1.3.16 +// Type definitions for react-breadcrumbs 1.3 // Project: https://github.com/svenanders/react-breadcrumbs // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +import * as React from "react"; +import * as ReactRouter from "react-router"; -declare namespace ReactBreadcrumbs { - interface BreadcrumbsProps extends React.Props { +export = Breadcrumbs; +type Breadcrumbs = React.ComponentClass; +declare const Breadcrumbs: Breadcrumbs; + +declare namespace Breadcrumbs { + interface Props extends React.ClassAttributes { separator?: string | JSX.Element; displayMissing?: boolean; prettify?: boolean; @@ -26,13 +30,4 @@ declare namespace ReactBreadcrumbs { setDocumentTitle?: boolean; params?: any; // todo make it compatible with params of the ReactRouter.RouteComponentProps } - - interface Breadcrumbs extends React.ComponentClass {} - const Breadcrumbs: Breadcrumbs; -} - -declare module 'react-breadcrumbs' { - import Breadcrumbs = ReactBreadcrumbs.Breadcrumbs; - - export = Breadcrumbs; } diff --git a/react-breadcrumbs/tsconfig.json b/react-breadcrumbs/tsconfig.json index 0092616bce..d1a0ccc542 100644 --- a/react-breadcrumbs/tsconfig.json +++ b/react-breadcrumbs/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" From 848999f5764d0a4af62ad49ee12ea6de80bcde51 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 20 Jan 2017 09:28:08 +0900 Subject: [PATCH 35/85] Add path mapping to react-i18next --- react-i18next/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/react-i18next/tsconfig.json b/react-i18next/tsconfig.json index bba519bbd3..5936e04b91 100644 --- a/react-i18next/tsconfig.json +++ b/react-i18next/tsconfig.json @@ -11,7 +11,8 @@ "baseUrl": "../", "paths": { "history": ["history/v2"], - "history/*": ["history/v2/*"] + "history/*": ["history/v2/*"], + "react-router": ["react-router/v2"], }, "typeRoots": [ "../" From 6b1b8e745c79db044dc53eef44c6587113d03a60 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 20 Jan 2017 10:58:59 -0600 Subject: [PATCH 36/85] Fix props callbacks. Type dates as moment.Moment. --- react-datepicker/index.d.ts | 21 +++++++++++---------- react-datepicker/react-datepicker-tests.tsx | 6 +++--- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index aec8b61b72..109e47626c 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -3,9 +3,10 @@ // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-datepicker" { + import * as React from "react"; + import * as moment from "moment"; + interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; @@ -14,7 +15,7 @@ declare module "react-datepicker" { dateFormat?: string; dateFormatCalendar?: string; disabled?: boolean; - endDate?: {}; + endDate?: moment.Moment; excludeDates?: any[]; filterDate?(): any; fixedHeight?: boolean; @@ -22,12 +23,12 @@ declare module "react-datepicker" { includeDates?: any[]; isClearable?: boolean; locale?: string; - maxDate?: {}; - minDate?: {}; + maxDate?: moment.Moment; + minDate?: moment.Moment; name?: string; - onBlur?(handler: (e: any) => void): any; - onChange(handler: (date?: any, e?: any) => void): any; - onFocus?(handler: (e: any) => void): any; + onBlur?(event: React.FocusEvent): void; + onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): any; + onFocus?(event: React.FocusEvent): void; peekNextMonth?: boolean; placeholderText?: string; popoverAttachment?: string; @@ -37,13 +38,13 @@ declare module "react-datepicker" { renderCalendarTo?: any; required?: boolean; scrollableYearDropdown?: boolean; - selected?: {}; + selected?: moment.Moment | null; selectsEnd?: boolean; selectsStart?: boolean; showMonthDropdown?: boolean; showYearDropdown?: boolean; showWeekNumbers?: boolean; - startDate?: {}; + startDate?: moment.Moment; tabIndex?: number; tetherConstraints?: any[]; title?: string; diff --git a/react-datepicker/react-datepicker-tests.tsx b/react-datepicker/react-datepicker-tests.tsx index 53cd4723b5..df1b02dacf 100644 --- a/react-datepicker/react-datepicker-tests.tsx +++ b/react-datepicker/react-datepicker-tests.tsx @@ -2,8 +2,8 @@ import * as React from "react"; import * as moment from 'moment'; import * as DatePicker from 'react-datepicker'; -class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:string}> { - constructor(props:any) { +class ReactDatePicker extends React.Component<{}, { startDate: moment.Moment; displayName:string; }> { + constructor(props: {}) { super(); this.state = { startDate: moment(), @@ -12,7 +12,7 @@ class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:str this.handleChange = this.handleChange.bind(this); } - handleChange = function(date?:any) { + handleChange = function(date?: moment.Moment | null) { this.setState({ startDate: date }); From 0c26a340bb4b5f0c1f93ad66348cf72818d1302e Mon Sep 17 00:00:00 2001 From: John Date: Fri, 20 Jan 2017 11:05:05 -0600 Subject: [PATCH 37/85] Update version number --- react-datepicker/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index 109e47626c..3ba6f91386 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker v0.28.1 +// Type definitions for react-datepicker v0.40.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 1e4d93b30843687a5e88ebb5b1574d0a94eb6d92 Mon Sep 17 00:00:00 2001 From: Joel Date: Fri, 20 Jan 2017 17:50:22 -0500 Subject: [PATCH 38/85] fix seek(...) function so that it can return either a Howl object or a number --- howler/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/howler/index.d.ts b/howler/index.d.ts index 1b6604b1aa..df3f6a363b 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -66,7 +66,7 @@ interface Howl { rate(idOrSetRate: number): this | number; rate(rate: number, id: number): this; - seek(seek?: number, id?: number): this; + seek(seek?: number, id?: number): this | number; loop(loop?: boolean, id?: number): this; playing(id?: number): boolean; duration(id?: number): number; From cb95e528e74d728691e0a14482b5634685553893 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 19:49:48 -0500 Subject: [PATCH 39/85] Add ArrayBuffer parameter to js-md5 --- js-md5/index.d.ts | 4 ++++ js-md5/js-md5-tests.ts | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 32ef8b30ff..d635a58a6c 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -9,24 +9,28 @@ interface JQuery { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } interface JQueryStatic { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } interface md5 { (value: string): string; (value: Array): string; (value: Uint8Array): string; + (value: ArrayBuffer): string; } interface String { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } declare module "js-md5" { diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index 984a919ec3..77b10c09ce 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -5,6 +5,7 @@ md5(''); md5('中文'); md5([]); md5(new Uint8Array([])); +md5(new ArrayBuffer(0)); $.md5('message'); $.md5('Message to hash'); @@ -12,9 +13,11 @@ $.md5(''); $.md5('中文'); $.md5([]); $.md5(new Uint8Array([])); +$.md5(new ArrayBuffer(0)); 'message'.md5('Message to hash'); 'message'.md5(''); 'message'.md5('中文'); 'message'.md5([]); -'message'.md5(new Uint8Array([])); \ No newline at end of file +'message'.md5(new Uint8Array([])); +'message'.md5(new ArrayBuffer(0)); \ No newline at end of file From bccb2cadc334c36fc262838879d51a9646de3627 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 19:54:19 -0500 Subject: [PATCH 40/85] Add ArrayBuffer parameter to js-md5 --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index d635a58a6c..7292463815 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for js-md5 v0.3.0 // Project: https://github.com/emn178/js-md5 -// Definitions by: Roland Greim +// Definitions by: Roland Greim , Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ /// From f96596fa4efa2156052e8a98f4da302d8918fcac Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 20:02:09 -0500 Subject: [PATCH 41/85] Increase version number in header --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 7292463815..db202ed628 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-md5 v0.3.0 +// Type definitions for js-md5 v0.3.1 // Project: https://github.com/emn178/js-md5 // Definitions by: Roland Greim , Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ From ab1d41bcd4200fb0e57995c534ddf5ea2bf95da4 Mon Sep 17 00:00:00 2001 From: Eiji Kitamura Date: Sat, 21 Jan 2017 15:50:12 +0900 Subject: [PATCH 42/85] Follow Payment Request spec updates --- paymentrequest/index.d.ts | 69 ++++++++++++++++---------- paymentrequest/paymentrequest-tests.ts | 15 ++++-- 2 files changed, 53 insertions(+), 31 deletions(-) diff --git a/paymentrequest/index.d.ts b/paymentrequest/index.d.ts index 50ef94e1e6..5231f53bc3 100644 --- a/paymentrequest/index.d.ts +++ b/paymentrequest/index.d.ts @@ -1,26 +1,33 @@ // Type definitions for PaymentRequest // Project: https://www.w3.org/TR/payment-request/ -// Definitions by: Adam Cmiel +// Definitions by: Adam Cmiel , Eiji Kitamura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface PaymentRequest extends EventTarget { new (methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; show(): PromiseLike; abort(): PromiseLike; - shippingAddress?: PaymentAddress; - shippingOption?: string; + canMakePayment(): Promise; + readonly paymentRequestID: string; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly shippingType?: string; onshippingaddresschange: PaymentUpdateEventListener; onshippingoptionchange: PaymentUpdateEventListener; } interface PaymentMethodData { supportedMethods: string[]; - data?: Object; + data?: { + supportedNetworks: string[]; + supportedTypes: string[]; + }; } interface PaymentCurrencyAmount { currency: string; value: string; + currencySystem?:string; } interface PaymentDetails { @@ -28,55 +35,63 @@ interface PaymentDetails { displayItems?: PaymentItem[]; shippingOptions?: PaymentShippingOption[]; modifiers?: PaymentDetailsModifier[]; + error?: string; } interface PaymentDetailsModifier { supportedMethods: string[]; total?: PaymentItem; - additionalDisplayItems: PaymentItem[]; + additionalDisplayItems?: PaymentItem[]; + data?: Object; } interface PaymentOptions { - requestShipping: boolean; - requestPayerEmail: boolean; - requestPayerPhone: boolean; + requestShipping?: boolean; + requestPayerEmail?: boolean; + requestPayerPhone?: boolean; + requestPayerName?: boolean; + shippingType?: 'shipping' | 'delivery' | 'pickup'; } interface PaymentItem { label: string; - amount: PaymentCurrencyAmount + amount: PaymentCurrencyAmount; + pending?: boolean; } interface PaymentAddress { - country: string; - addressLine: string[]; - region: string; - city: string; - dependentLocality: string; - postalCode: string; - sortingCode: string; - languageCode: string; - organization: string; - recipient: string; - careOf: string; - phone: string; + readonly country: string; + readonly addressLine: string[]; + readonly region: string; + readonly city: string; + readonly dependentLocality: string; + readonly postalCode: string; + readonly sortingCode: string; + readonly languageCode: string; + readonly organization: string; + readonly recipient: string; + readonly phone: string; } interface PaymentShippingOption { id: string; label: string; amount: PaymentCurrencyAmount; + selected?: boolean; } interface PaymentResponse { - methodName: string; - details: Object; - shippingAddress?: PaymentAddress; - shippingOption?: string; - payerEmail?: string; - payerPhone?: string; + readonly paymentRequestID: string; + readonly methodName: string; + readonly details: Object; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly payerEmail?: string; + readonly payerPhone?: string; + readonly payerName?: string; complete(result?: '' | 'success' | 'fail'): PromiseLike; + toJSON(): Object; } interface PaymentUpdateEventListener extends EventListener { diff --git a/paymentrequest/paymentrequest-tests.ts b/paymentrequest/paymentrequest-tests.ts index 4c36c3ff76..62c2721bfb 100644 --- a/paymentrequest/paymentrequest-tests.ts +++ b/paymentrequest/paymentrequest-tests.ts @@ -3,7 +3,7 @@ /// Code examples derived from /// https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/ -function makeRequest() { +async function makeRequest() { if (!window.PaymentRequest) { return Promise.reject(new Error("PaymentRequest not available")) } @@ -31,10 +31,12 @@ function makeRequest() { } } - const options = { + const options: PaymentOptions = { requestShipping: true, requestPayerEmail: true, - requestPayerPhone: true + requestPayerPhone: true, + requestPayerName: true, + shippingType: 'delivery' } const request = new window.PaymentRequest(methodData, details, options) @@ -72,7 +74,12 @@ function makeRequest() { })(details, request.shippingAddress)); }) - return request.show() + let canMakePayment = await request.canMakePayment() + if (canMakePayment) { + return request.show() + } else { + throw 'can not make payment on this environment.' + } } async function processPayment(): Promise { From 453ffc9e8a24c7404ca2951fa28e9e54da42f20d Mon Sep 17 00:00:00 2001 From: "Angus.Fenying" Date: Sun, 22 Jan 2017 16:17:37 +0800 Subject: [PATCH 43/85] Added methods cork and uncork for RedisClient. --- redis/index.d.ts | 10 ++++++++++ redis/redis-tests.ts | 8 +++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/redis/index.d.ts b/redis/index.d.ts index 75745b99f4..0e7e2ec4de 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -94,6 +94,16 @@ export interface RedisClient extends NodeJS.EventEmitter { end(): void; unref(): void; + /** + * Stop sending commands and queue the commands. + */ + cork(): void; + + /** + * Resume and send the queued commands at once. + */ + uncork(): void; + // Low level command execution send_command(command: string, ...args: any[]): boolean; diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index d98979f256..e0315a809f 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -112,4 +112,10 @@ client.monitor(resCallback); // Send command client.send_command(str, args, resCallback); // Duplicate -client.duplicate(); \ No newline at end of file +client.duplicate(); + +// Pipeline +client.cork(); +client.set("abc", "fff", strCallback); +client.get("abc", resCallback); +client.uncork(); From ef8a64d27c4036fe9e1103736aaedd5890aa347d Mon Sep 17 00:00:00 2001 From: Oleg Solomka Date: Mon, 23 Jan 2017 16:14:41 -0600 Subject: [PATCH 44/85] rename `createBrowserHistory` to `createHistory ` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `createBrowserHistory ` was only introduced in the `history@4.0.0-1` prior to that the `createHistory` was used. So if you will install `@types/history@^2.0.0` and `history@^2.0.0`(or even `^3.x.x`) it will break with the next error: ``` ./src/client/history.ts (1,10): error TS2305: Module ‘”/@types/history/index"' has no exported member 'createHistory'. ``` This commit brings the `createHistory` back thus solves the issue for `history@^2.x.x` and `history@^3.x.x`. --- history/v2/history-tests.ts | 20 ++++++++++---------- history/v2/index.d.ts | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/history/v2/history-tests.ts b/history/v2/history-tests.ts index 454b223e09..598d934e8d 100644 --- a/history/v2/history-tests.ts +++ b/history/v2/history-tests.ts @@ -1,4 +1,4 @@ -import { createBrowserHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' +import { createHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' import { getUserConfirmation } from 'history/lib/DOMUtils' @@ -10,7 +10,7 @@ let doSomethingAsync: () => Promise; let input = { value: "" }; { - let history = createBrowserHistory() + let history = createHistory() // Listen for changes to the current location. The // listener is called once immediately. @@ -46,7 +46,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() // Pushing a path string. history.push('/the/path') @@ -63,7 +63,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() history.listenBefore(function(location) { if (input.value !== '') return 'Are you sure you want to leave this page?' @@ -75,7 +75,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory({ + let history = createHistory({ getUserConfirmation(message, callback) { callback(window.confirm(message)) // The default behavior } @@ -83,7 +83,7 @@ let input = { value: "" }; } { - let history = useBeforeUnload(createBrowserHistory)() + let history = useBeforeUnload(createHistory)() history.listenBeforeUnload(function() { return 'Are you sure you want to leave this page?' @@ -91,7 +91,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)() + let history = useQueries(createHistory)() history.listen(function(location) { console.log(location.query) @@ -99,7 +99,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)({ + let history = useQueries(createHistory)({ parseQueryString: function(queryString) { // TODO: return a parsed version of queryString return {}; @@ -116,7 +116,7 @@ let input = { value: "" }; { // Run our app under the /base URL. - let history = useBasename(createBrowserHistory)({ + let history = useBasename(createHistory)({ basename: '/base' }) @@ -128,4 +128,4 @@ let input = { value: "" }; history.createPath('/the/path') // /base/the/path history.push('/the/path') // push /base/the/path -} \ No newline at end of file +} diff --git a/history/v2/index.d.ts b/history/v2/index.d.ts index 5f719c2f0b..6b61fa1b77 100644 --- a/history/v2/index.d.ts +++ b/history/v2/index.d.ts @@ -127,7 +127,7 @@ export interface Module { }; } -export { default as createBrowserHistory } from "./lib/createBrowserHistory"; +export { default as createHistory } from "./lib/createBrowserHistory"; export { default as createHashHistory } from "./lib/createHashHistory"; export { default as createMemoryHistory } from "./lib/createMemoryHistory"; export { default as createLocation } from "./lib/createLocation"; From 59b9f7939c60302143d6d499392260a09315e46c Mon Sep 17 00:00:00 2001 From: Eiji Kitamura Date: Tue, 24 Jan 2017 10:23:47 +0900 Subject: [PATCH 45/85] [paymentrequest] Added `target: "es6"` --- paymentrequest/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/paymentrequest/tsconfig.json b/paymentrequest/tsconfig.json index 221e0618af..e5754a139a 100644 --- a/paymentrequest/tsconfig.json +++ b/paymentrequest/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, From 8829f99d006174525b8e4d00f7720722690cbda5 Mon Sep 17 00:00:00 2001 From: Steven Liekens Date: Tue, 24 Jan 2017 10:43:42 +0100 Subject: [PATCH 46/85] Mark optional properties as such --- jquery.datatables/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index c7c4bd8682..5d1bbd50c9 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -908,7 +908,7 @@ declare namespace DataTables { * @param d Data to use for the row. */ data(d: any[] | Object): DataTable; - + /** * Get the id of the selected row. Since: 1.10.8 @@ -1456,9 +1456,9 @@ declare namespace DataTables { } export interface AjaxData { - draw: number; - recordsTotal: number; - recordsFiltered: number; + draw?: number; + recordsTotal?: number; + recordsFiltered?: number; data: any; error?: string; } From 6d81c90395104ca52bfd30e3574bd13f4b39861a Mon Sep 17 00:00:00 2001 From: denis Date: Tue, 24 Jan 2017 15:18:31 +0100 Subject: [PATCH 47/85] MetisMenu: add missing types for 2.6.1 Add events types, preventDefault properties, and 'dispose' option. --- metismenu/index.d.ts | 8 ++++++-- metismenu/metismenu-tests.ts | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index 43faa279c7..1816090f87 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for metisMenu 2.0.3 +// Type definitions for metisMenu 2.6.1 // Project: http://github.com/onokumus/metisMenu // Definitions by: onokums // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,8 +12,12 @@ interface MetisMenuOptions { collapseClass?: string; collapseInClass?: string; collapsingClass?: string; + preventDefault?: boolean; } +type MetisMenuEvents = "show.metisMenu" | "shown.metisMenu" | "hide.metisMenu" | "hidden.metisMenu"; + interface JQuery { - metisMenu(options?: MetisMenuOptions): JQuery; + metisMenu(options?: MetisMenuOptions | "dispose"): JQuery; + on(events: MetisMenuEvents, handler: (eventObject: JQueryEventObject) => any): JQuery; } diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index b2e36f1d53..625a4877ab 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -1,12 +1,29 @@ /// $('#menu').metisMenu(); + $('.metismenu').metisMenu({toggle: false}); + $('.test').metisMenu({ toggle: false, doubleTapToGo: true, activeClass: 'active', collapseClass: 'collapse', collapseInClass: 'in', - collapsingClass: 'collapsing' + collapsingClass: 'collapsing', + preventDefault: true }); + +$('.metismenu').metisMenu('dispose'); + +$('.metismenu') + .metisMenu() + .on('show.metisMenu', function(e) { + // empty logic + }).on('shown.metisMenu', function(e) { + // empty logic + }).on('hide.metisMenu', function(e) { + // empty logic + }).on('hidden.metisMenu', function(e) { + // empty logic + }); From fbbdd4fa3c62077b1829fe1850c20ffb50c7044c Mon Sep 17 00:00:00 2001 From: Chris Scribner Date: Tue, 24 Jan 2017 10:41:26 -0800 Subject: [PATCH 48/85] Add promise-based interceptor definitions --- axios/axios-tests.ts | 20 +++++++++++++++++++- axios/index.d.ts | 20 ++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts index eb98e2710c..2587222b36 100644 --- a/axios/axios-tests.ts +++ b/axios/axios-tests.ts @@ -13,6 +13,13 @@ interface Issue { title: string; } +function makePromise(val: any) { + return >{ + then: () => val, + catch: () => val + }; +} + axios.interceptors.request.use(config => { console.log("Method:" + config.method + " Url:" +config.url); return config; @@ -30,12 +37,23 @@ const requestId: number = axios.interceptors.request.use( axios.interceptors.request.eject(requestId); axios.interceptors.request.eject(7); +const requestId2: number = axios.interceptors.request.use( + (config) => { + console.log("Method:" + config.method + " Url:" +config.url); + return makePromise(config); + }, + (error: any) => error); axios.interceptors.response.use(config => { console.log("Status:" + config.status); return config; }); +axios.interceptors.response.use(config => { + console.log("Status:" + config.status); + return makePromise(config); +}); + const responseId: number = axios.interceptors.response.use( config => { console.log("Status:" + config.status); @@ -104,4 +122,4 @@ axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; -axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; \ No newline at end of file +axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; diff --git a/axios/index.d.ts b/axios/index.d.ts index 681fefc806..b32a78ebe0 100644 --- a/axios/index.d.ts +++ b/axios/index.d.ts @@ -99,10 +99,10 @@ declare namespace Axios { * change the response data to be made before it is passed to then/catch */ transformResponse?: (data: T) => U; - - /** - * defines whether to resolve or reject the promise for a given HTTP response status code. - * If returns `true` (or is set to `null` or `undefined`), the promise will be resolved; + + /** + * defines whether to resolve or reject the promise for a given HTTP response status code. + * If returns `true` (or is set to `null` or `undefined`), the promise will be resolved; * otherwise, the promise will be rejected */ validateStatus?: (status: number) => boolean | undefined; @@ -199,6 +199,12 @@ declare namespace Axios { rejectedFn: (error: any) => any) : InterceptorId; + use(fulfilledFn: (config: AxiosXHRConfig) => IPromise>): InterceptorId; + + use(fulfilledFn: (config: AxiosXHRConfig) => IPromise>, + rejectedFn: (error: any) => any) + : InterceptorId; + eject(interceptorId: InterceptorId): void; } @@ -209,10 +215,16 @@ declare namespace Axios { use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR): InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => IPromise>): InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR, rejectedFn: (error: any) => any) : InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => IPromise>, + rejectedFn: (error: any) => any) + : InterceptorId; + eject(interceptorId: InterceptorId): void; } From b435dd3c8bfa4ad23cb34246c777e7d0f8db39dd Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Mon, 23 Jan 2017 18:14:36 -0600 Subject: [PATCH 49/85] auth0-js v8.1.3 --- auth0-js/auth0-js-tests.ts | 160 +++++++++- auth0-js/index.d.ts | 584 ++++++++++++++++++++++++++-------- auth0-js/v7/auth0-js-tests.ts | 22 ++ auth0-js/v7/index.d.ts | 136 ++++++++ auth0-js/v7/tsconfig.json | 28 ++ 5 files changed, 782 insertions(+), 148 deletions(-) create mode 100644 auth0-js/v7/auth0-js-tests.ts create mode 100644 auth0-js/v7/index.d.ts create mode 100644 auth0-js/v7/tsconfig.json diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 197256ddd5..68d4e1797b 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,23 +1,151 @@ /// -var auth0 = new Auth0({ +let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true + clientID: 'dsa7d77dsa7d7' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 +webAuth.authorize({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + responseType: 'token', + redirectUri: 'https://example.com/auth/callback' +}); + +webAuth.parseHash(window.location.hash, (err, authResult) => { + if (err) { + return console.log(err); } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); + + // The contents of authResult depend on which authentication parameters were used. + // It can include the following: + // authResult.accessToken - access token for the API specified by `audience` + // authResult.expiresIn - string with the access token's expiration time in seconds + // authResult.idToken - ID token JWT containing user profile information + + webAuth.client.userInfo(authResult.accessToken, (err, user) => { + // Now you have the user's information }); +}); + +webAuth.renewAuth({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + + // this will use postMessage to comunicate between the silent callback + // and the SPA. When false the SDK will attempt to parse the url hash + // should ignore the url hash and no extra behaviour is needed. + usePostMessage: true +}, function (err, authResult) { + // Renewed tokens or error +}); + +webAuth.changePassword({connection: 'the_connection', + email: 'me@example.com', + password: '123456' +}, (err) => {}); + +webAuth.passwordlessStart({ + connection: 'the_connection', + email: 'me@example.com', + send: 'code' +}, (err, data) => {}); + +webAuth.signupAndAuthorize({ + connection: 'the_connection', + email: 'me@example.com', + password: '123456', + scope: 'openid' +}, function (err, data) { + +}); + + + +webAuth.client.login({ + ealm: 'Username-Password-Authentication', //connection name or HRD domain + username: 'info@auth0.com', + password: 'areallystrongpassword', + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', +}, function(err, authResult) { + // Auth tokens in the result or an error +}); + +let authentication = new auth0.Authentication({ + domain: 'me.auth0.com', + clientID: '...', + redirectUri: 'http://page.com/callback', + responseType: 'code', + _sendTelemetry: false +}); + +authentication.buildAuthorizeUrl({state:'1234'}); +authentication.buildAuthorizeUrl({ + responseType: 'token', + redirectUri: 'http://anotherpage.com/callback2', + prompt: 'none', + state: '1234', + connection_scope: 'scope1,scope2' +}); + +authentication.buildLogoutUrl('asdfasdfds'); +authentication.buildLogoutUrl(); +authentication.userInfo('abcd1234', (err, data) => { + //user info retrieved +}); + +authentication.delegation({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + refresh_token: 'your_refresh_token', + api_type: 'app' +}, (err, data) => { + +}); + +authentication.loginWithDefaultDirectory({ + username: 'someUsername', + password: '123456' +}, (err, data) => { + +}); + +authentication.oauthToken({ + username: 'someUsername', + password: '123456', + grantType: 'password' +}, (err, data) => { + +}); + +authentication.getUserCountry((err, data) => { + +}); + +authentication.getSSOData(); +authentication.getSSOData(true, (err, data) => {}); + +authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); +authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); + +authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {}); +authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {}); + +authentication.loginWithResourceOwner({ + username: 'the username', + password: 'the password', + connection: 'the_connection', + scope: 'openid' +}, (err, data) => {}); + +let management = new auth0.Management({ + domain: 'me.auth0.com', + token: 'token' +}); + +management.getUser('asd', (err, user) => {}); + +management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {}); + +management.linkUser('asd', 'eqwe', (err, user) => {}); diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index bd97fed1cc..6def04ab89 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,136 +1,456 @@ -// Type definitions for Auth0.js +// Type definitions for Auth0.js v8.1.3 // Project: https://github.com/auth0/auth0.js -// Definitions by: Robert McLaws +// Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ - token: string; -} - -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - responseType?: string; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - email_verified: boolean; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; - connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - idToken: string; - profile: Auth0UserProfile; - state: any; - error: string; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - responseType?: string; - connection?: string; - email?: string; - username?: string; - password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} - -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} - -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} - -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} - -declare const Auth0: Auth0Static; - -declare module "auth0-js" { - export = Auth0 +declare namespace auth0 { + + export class Authentication { + constructor(options: AuthOptions); + + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; + + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; + + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; + + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } + + export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } + + export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } + + export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } + + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } + + export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + export class Popup { + constructor(client: any, options: any); + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } + + interface Auth0Error { + error: any; + errorDescription: string + } + + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } + + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } + + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } + + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string, + authParams?: any; + } + + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } + } diff --git a/auth0-js/v7/auth0-js-tests.ts b/auth0-js/v7/auth0-js-tests.ts new file mode 100644 index 0000000000..d5ca0250d4 --- /dev/null +++ b/auth0-js/v7/auth0-js-tests.ts @@ -0,0 +1,22 @@ +/// +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/v7/index.d.ts b/auth0-js/v7/index.d.ts new file mode 100644 index 0000000000..ee834d5c61 --- /dev/null +++ b/auth0-js/v7/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Auth0.js v7.x +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + responseType?: string; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + idToken: string; + profile: Auth0UserProfile; + state: any; + error: string; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + responseType?: string; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare const Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0-js/v7/tsconfig.json b/auth0-js/v7/tsconfig.json new file mode 100644 index 0000000000..7413e97f44 --- /dev/null +++ b/auth0-js/v7/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "auth0-js": [ + "auth0-js/v7" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auth0-js-tests.ts" + ] +} From 961480480b66dc34420b8f997e97d79d9d6ef899 Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Tue, 24 Jan 2017 14:21:46 -0600 Subject: [PATCH 50/85] Update references to auth0-js/v7 --- auth0-lock/auth0-lock-tests.ts | 2 +- auth0-lock/index.d.ts | 2 +- auth0.widget/auth0.widget-tests.ts | 2 +- auth0.widget/index.d.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index deb046f3e7..4b72edcfa1 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index fc9a047115..09c3f4fedd 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index ec5502ca7e..6277d4cc3a 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts index 1c30d83b6f..cdefd9e0fd 100644 --- a/auth0.widget/index.d.ts +++ b/auth0.widget/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { From da84c6d42b1b7c9d28de48c7115767682b513c8f Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Tue, 24 Jan 2017 14:50:59 -0600 Subject: [PATCH 51/85] Convert tab to spaces for consistency --- auth0-js/index.d.ts | 790 ++++++++++++++++++++++---------------------- 1 file changed, 395 insertions(+), 395 deletions(-) diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 6def04ab89..0a0e004303 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -5,452 +5,452 @@ declare namespace auth0 { - export class Authentication { - constructor(options: AuthOptions); + export class Authentication { + constructor(options: AuthOptions); - passwordless: PasswordlessAuthentication; - dbConnection: DBConnection; + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; - /** - * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction - * - * @method buildAuthorizeUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - buildAuthorizeUrl(options: any): string; + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; - /** - * Builds and returns the Logout url in order to initialize a new authN/authZ transaction - * - * @method buildLogoutUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - buildLogoutUrl(options?: any): string; + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; - /** - * Makes a call to the `oauth/token` endpoint with `password` grant type - * - * @method loginWithDefaultDirectory - * @param {Object} options: https://auth0.com/docs/api-auth/grant/password - * @param {Function} callback - */ - loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ro` endpoint - * @param {any} options - * @param {Function} callback - * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. - */ - loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint with `password-realm` grant type - * @param {any} options - * @param {Function} callback - */ - login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint - * @param {any} options - * @param {Function} callback - */ - oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/userinfo` endpoint and returns the user profile - * - * @method userInfo - * @param {String} accessToken - * @param {Function} callback - */ - userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Makes a call to the `/delegation` endpoint - * - * @method delegation - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation - * @param {Function} callback - * @deprecated `delegation` will be soon deprecated. - */ - delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; - /** - * Fetches the user country based on the ip. - * - * @method getUserCountry - * @param {Function} callback - */ - getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; - } + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } - export class PasswordlessAuthentication { - constructor(request: any, option: any); + export class PasswordlessAuthentication { + constructor(request: any, option: any); - /** - * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - buildVerifyUrl(options: any): string; + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; - /** - * Initializes a new passwordless authN/authZ transaction - * - * @method start - * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless - * @param {Function} callback - */ - start(options: PasswordlessStartOptions, callback: any): void; + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; - /** - * Verifies the passwordless TOTP and returns an error if any. - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - verify(options: any, callback: any): void; - } + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } - export class DBConnection { - constructor(request: any, option: any); + export class DBConnection { + constructor(request: any, option: any); - /** - * Signup a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} calback - */ - signup(options: any, callback: any): void; + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; - /** - * Initializes the change password flow - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: ChangePasswordOptions, callback: any): void; - } + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } - export class Management { - constructor(options: ManagementOptions); + export class Management { + constructor(options: ManagementOptions); - /** - * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id - * - * @method getUser - * @param {String} userId - * @param {Function} callback - */ - getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Updates the user metdata. It will patch the user metdata with the attributes sent. - * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id - * - * @method patchUserMetadata - * @param {String} userId - * @param {Object} userMetadata - * @param {Function} callback - */ - patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities - * - * @method linkUser - * @param {String} userId - * @param {String} secondaryUserToken - * @param {Function} callback - */ - linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; - } + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } - export class WebAuth { - constructor(options: AuthOptions); - client: Authentication; - popup: Popup; - redirect: Redirect; + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; - /** - * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - authorize(options: any): void; + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; - /** - * Parse the url hash and extract the returned tokens depending on the transaction. - * - * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed - * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be - * accepted. - * - * @method parseHash - * @param {Object} options: - * @param {String} options.state [OPTIONAL] to verify the response - * @param {String} options.nonce [OPTIONAL] to verify the id_token - * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash - * @param {Function} callback: any(err, token_payload) - */ - parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Decodes the id_token and verifies the nonce. - * - * @method validateToken - * @param {String} token - * @param {String} state - * @param {String} nonce - * @param {Function} callback: function(err, {payload, transaction}) - */ - validateToken(token: string, state: string, nonce: string, callback: any): void; + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; - /** - * Executes a silent authentication transaction under the hood in order to fetch a new token. - * - * @method renewAuth - * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint - * @param {Function} callback - */ - renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Initialices a change password transaction - * - * @method changePassword - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Signs up a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signup(options: any, callback: any): void; + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; - /** - * Signs up a new user, automatically logs the user in after the signup and returns the user token. - * The login will be done using /oauth/token with password-realm grant type. - * - * @method signupAndAuthorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Redirects to the auth0 logout page - * - * @method logout - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - logout(options: any): void; + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; - passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; - /** - * Verifies the passwordless TOTP and redirects to finish the passwordless transaction - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - } + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } - export class Redirect { - constructor(client: any, options: any); + export class Redirect { + constructor(client: any, options: any); - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } - export class Popup { - constructor(client: any, options: any); + export class Popup { + constructor(client: any, options: any); - /** - * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. - * - * @method preload - * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open - */ - preload(options: any): any; + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; - /** - * Internal use. - * - * @method getPopupHandler - */ - getPopupHandler(options: any, preload: boolean): any; - /** - * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - * @param {Function} callback - */ - authorize(options: any, callback: any): void; + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; - /** - * Verifies the passwordless TOTP and returns the requested token - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } - interface ManagementOptions { - domain: string; - token: string; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } - interface AuthOptions { - domain: string; - clientID: string; - responseType?: string; - responseMode?: string; - redirectUri?: string; - scope?: string; - audience?: string; - leeway?: number; - _disableDeprecationWarnings?: boolean; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } - interface PasswordlessAuthOptions { - connection: string; - verificationCode: string; - phoneNumber: string; - email: string; - } + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } - interface Auth0Error { - error: any; - errorDescription: string - } + interface Auth0Error { + error: any; + errorDescription: string + } - interface Auth0DecodedHash { - accessToken?: string; - idToken?: string; - idTokenPayload?: any; - refreshToken?: string; - state?: string; - expiresIn?: number; - tokenType?: string; - } + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } - /** Represents the response from an API Token Delegation request. */ - interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - ExpiresIn: number; - /** The JWT for delegated access. */ - idToken: string; - /** The type of token being returned. Possible values: "Bearer" */ - tokenType: string; - } + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } - interface ChangePasswordOptions { - connection: string; - email: string; - password?: string; - } + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } - interface PasswordlessStartOptions { - connection: string; - send: string; - phoneNumber?: string; - email?: string, - authParams?: any; - } + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string, + authParams?: any; + } - interface PasswordlessVerifyOptions { - connection: string; - verificationCode: string; - phoneNumber?: string; - email?: string; - } + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } } From 256eff0c62072a301fd3ce8c17bcd386da1427fe Mon Sep 17 00:00:00 2001 From: Justin Leider Date: Wed, 25 Jan 2017 13:35:41 -0500 Subject: [PATCH 52/85] Update card and bank account interfaces, rename for consistency. --- stripe/index.d.ts | 31 +++++++++++++++---------------- stripe/stripe-tests.ts | 4 ++-- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/stripe/index.d.ts b/stripe/index.d.ts index a7d887c747..918f5c8551 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -12,13 +12,13 @@ interface StripeStatic { validateExpiry(month: string, year: string): boolean; validateCVC(cardCVC: string): boolean; cardType(cardNumber: string): StripeCardDataBrand; - getToken(token: string, responseHandler: (status: number, response: StripeTokenResponse) => void): void; - card: StripeCardData; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + card: StripeCard; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; bankAccount: StripeBankAccount; } -interface StripeTokenData { +interface StripeCardTokenData { number: string; exp_month?: number; exp_year?: number; @@ -35,7 +35,6 @@ interface StripeTokenData { interface StripeTokenResponse { id: string; - card: StripeCardData; created: number; livemode: boolean; object: string; @@ -44,6 +43,10 @@ interface StripeTokenResponse { error?: StripeError; } +interface StripeCardTokenResponse extends StripeTokenResponse { + card: StripeCard; +} + interface StripeError { type: string; code: string; @@ -53,7 +56,7 @@ interface StripeError { type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; -interface StripeCardData { +interface StripeCard { object: string; last4: string; exp_month: number; @@ -67,7 +70,10 @@ interface StripeCardData { address_zip?: string; address_country?: string; brand?: StripeCardDataBrand; - createToken(data: StripeTokenData, responseHandler: (status: number, response: StripeTokenResponse) => void): void; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; } interface StripeBankAccount { @@ -85,8 +91,7 @@ interface StripeBankTokenParams { account_holder_type: string; } -interface StripeBankTokenResponse { - id: string; +interface StripeBankTokenResponse extends StripeTokenResponse { bank_account: { country: string; bank_name: string; @@ -94,12 +99,6 @@ interface StripeBankTokenResponse { validated: boolean; object: string; }; - created: number; - livemode: boolean; - type: string; - object: string; - used: boolean; - error?: StripeError; } interface StripeApplePay { @@ -134,7 +133,7 @@ interface StripeApplePayLineItem { } interface StripeApplePaySessionResult { - token: StripeTokenResponse; + token: StripeCardTokenResponse; shippingContact?: StripeApplePayPaymentContact; shippingMethod?: StripeApplePayShippingMethod; } diff --git a/stripe/stripe-tests.ts b/stripe/stripe-tests.ts index 44aa09d216..56e6343f5c 100644 --- a/stripe/stripe-tests.ts +++ b/stripe/stripe-tests.ts @@ -1,4 +1,4 @@ -function success(card: StripeCardData) { +function success(card: StripeCard) { console.log(card.brand && card.brand.toString()); } @@ -6,7 +6,7 @@ const cardNumber = '4242424242424242'; const isValid = Stripe.validateCardNumber(cardNumber); if (isValid) { - const tokenData: StripeTokenData = { + const tokenData: StripeCardTokenData = { number: cardNumber, exp_month: 1, exp_year: 2100, From 842692a5bd25af26d5d9855804f5aad475d05222 Mon Sep 17 00:00:00 2001 From: Justin Leider Date: Wed, 25 Jan 2017 13:51:39 -0500 Subject: [PATCH 53/85] Update attribution and version --- stripe/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stripe/index.d.ts b/stripe/index.d.ts index 918f5c8551..78092b8b1e 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for stripe 0.0 +// Type definitions for stripe.js v2.x // Project: https://stripe.com/ -// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel +// Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel , Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const Stripe: StripeStatic; From da9dee33353a7eaef280df64616441af52d2462c Mon Sep 17 00:00:00 2001 From: Justin Leider Date: Wed, 25 Jan 2017 13:56:06 -0500 Subject: [PATCH 54/85] Fix package and version --- stripe/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stripe/index.d.ts b/stripe/index.d.ts index 78092b8b1e..2563af9882 100644 --- a/stripe/index.d.ts +++ b/stripe/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stripe.js v2.x +// Type definitions for stripe 2.x // Project: https://stripe.com/ // Definitions by: Andy Hawkins , Eric J. Smith , Amrit Kahlon , Adam Cmiel , Justin Leider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From f81b13123cfe681d066c39835685b730a74154be Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Wed, 25 Jan 2017 15:38:11 -0500 Subject: [PATCH 55/85] Rewrite definitions and tests, add tslint. --- js-md5/index.d.ts | 61 +++++++++++++++++++----------------------- js-md5/js-md5-tests.ts | 44 +++++++++++++++++------------- js-md5/tsconfig.json | 7 +++-- js-md5/tslint.json | 3 +++ 4 files changed, 58 insertions(+), 57 deletions(-) create mode 100644 js-md5/tslint.json diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index db202ed628..9f6d7abc09 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,40 +1,33 @@ -// Type definitions for js-md5 v0.3.1 +// Type definitions for js-md5 v0.4.2 // Project: https://github.com/emn178/js-md5 -// Definitions by: Roland Greim , Michael McCarthy +// Definitions by: Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ -/// +declare namespace md5 { + type message = string | any[] | Uint8Array | ArrayBuffer; -interface JQuery { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; - md5(value: ArrayBuffer): string; + interface Md5 { + array: () => number[]; + arrayBuffer: () => ArrayBuffer; + buffer: () => ArrayBuffer; + digest: () => number[]; + finalize: () => void; + hex: () => string; + toString: () => string; + update: (message: message) => Md5; + } + + interface md5 { + (message: message): string; + hex: (message: message) => string; + array: (message: message) => number[]; + digest: (message: message) => number[]; + arrayBuffer: (message: message) => ArrayBuffer; + buffer: (message: message) => ArrayBuffer; + create: () => Md5; + update: (message: message) => Md5; + } } -interface JQueryStatic { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; - md5(value: ArrayBuffer): string; -} - -interface md5 { - (value: string): string; - (value: Array): string; - (value: Uint8Array): string; - (value: ArrayBuffer): string; -} - -interface String { - md5(value: string): string; - md5(value: Array): string; - md5(value: Uint8Array): string; - md5(value: ArrayBuffer): string; -} - -declare module "js-md5" { - export = md5; -} - -declare var md5: md5; +declare const md5: md5.md5; +export = md5; diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index 77b10c09ce..e77ed82d8e 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -1,23 +1,29 @@ +import * as md5 from "js-md5"; +let str: string = md5.hex('The quick brown fox jumps over the lazy dog'); +str = md5('The quick brown fox jumps over the lazy dog'); +let arr: number[] = md5.digest('The quick brown fox jumps over the lazy dog'); +arr = md5.array('The quick brown fox jumps over the lazy dog'); +let buf: ArrayBuffer = md5.arrayBuffer('The quick brown fox jumps over the lazy dog'); +buf = md5.buffer('The quick brown fox jumps over the lazy dog'); -md5('Message to hash'); -md5(''); -md5('中文'); -md5([]); -md5(new Uint8Array([])); -md5(new ArrayBuffer(0)); +const hash1 = md5.create(); +hash1.update('The quick brown fox jumps over the lazy dog'); +str = hash1.hex(); +str = hash1.toString(); +arr = hash1.digest(); +arr = hash1.array(); +buf = hash1.arrayBuffer(); +buf = hash1.buffer(); -$.md5('message'); -$.md5('Message to hash'); -$.md5(''); -$.md5('中文'); -$.md5([]); -$.md5(new Uint8Array([])); -$.md5(new ArrayBuffer(0)); +const hash2 = md5.update('The quick brown fox jumps over the lazy dog'); +str = hash2.hex(); +str = hash2.toString(); +arr = hash2.digest(); +arr = hash2.array(); +buf = hash2.arrayBuffer(); +buf = hash2.buffer(); -'message'.md5('Message to hash'); -'message'.md5(''); -'message'.md5('中文'); -'message'.md5([]); -'message'.md5(new Uint8Array([])); -'message'.md5(new ArrayBuffer(0)); \ No newline at end of file +str = md5([]); +str = md5(new Uint8Array([])); +str = md5(new ArrayBuffer(0)); diff --git a/js-md5/tsconfig.json b/js-md5/tsconfig.json index eceeb1fb3d..f0ae291e30 100644 --- a/js-md5/tsconfig.json +++ b/js-md5/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +19,4 @@ "index.d.ts", "js-md5-tests.ts" ] -} \ No newline at end of file +} diff --git a/js-md5/tslint.json b/js-md5/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/js-md5/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From cf15d34bc47ea7a7b4e553ebb749e76e91bf36b7 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Wed, 25 Jan 2017 15:44:52 -0500 Subject: [PATCH 56/85] Replace stray tab with spaces --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 9f6d7abc09..f28a3eef80 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -22,7 +22,7 @@ declare namespace md5 { hex: (message: message) => string; array: (message: message) => number[]; digest: (message: message) => number[]; - arrayBuffer: (message: message) => ArrayBuffer; + arrayBuffer: (message: message) => ArrayBuffer; buffer: (message: message) => ArrayBuffer; create: () => Md5; update: (message: message) => Md5; From 0b4f4a2538fcae6fd25fd4c4e99e3b576cbf8746 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Wed, 25 Jan 2017 16:09:28 -0500 Subject: [PATCH 57/85] Edit import to use require, fix version number --- js-md5/index.d.ts | 2 +- js-md5/js-md5-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index f28a3eef80..4f1a1b351e 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-md5 v0.4.2 +// Type definitions for js-md5 v0.4 // Project: https://github.com/emn178/js-md5 // Definitions by: Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index e77ed82d8e..231b12ebf2 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -1,4 +1,4 @@ -import * as md5 from "js-md5"; +import md5 = require("js-md5"); let str: string = md5.hex('The quick brown fox jumps over the lazy dog'); str = md5('The quick brown fox jumps over the lazy dog'); From cfdd4d3496b96711bc9fa2600213a9dd244875a2 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Wed, 25 Jan 2017 16:13:11 -0500 Subject: [PATCH 58/85] Remove v from version number --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 4f1a1b351e..41f19fba42 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-md5 v0.4 +// Type definitions for js-md5 0.4 // Project: https://github.com/emn178/js-md5 // Definitions by: Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ From 82634e7bfbc82d4224e20fc3561fc91b91875672 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Wed, 25 Jan 2017 16:27:38 -0500 Subject: [PATCH 59/85] Remove finalize from Md5 interface --- js-md5/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 41f19fba42..690279bbe4 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -11,7 +11,6 @@ declare namespace md5 { arrayBuffer: () => ArrayBuffer; buffer: () => ArrayBuffer; digest: () => number[]; - finalize: () => void; hex: () => string; toString: () => string; update: (message: message) => Md5; From 227e85833925be724fa847d1acc9ad1a75b2eac2 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 20 Jan 2017 09:44:32 +0900 Subject: [PATCH 60/85] Fix typings that depend on old version --- react-i18next/tsconfig.json | 2 +- react-router/tsconfig.json | 4 +-- react-router/v2/tsconfig.json | 3 ++- redux-bootstrap/index.d.ts | 46 +++++++++++++++++------------------ redux-bootstrap/tsconfig.json | 3 --- 5 files changed, 27 insertions(+), 31 deletions(-) diff --git a/react-i18next/tsconfig.json b/react-i18next/tsconfig.json index 5936e04b91..c64579c2e8 100644 --- a/react-i18next/tsconfig.json +++ b/react-i18next/tsconfig.json @@ -12,7 +12,7 @@ "paths": { "history": ["history/v2"], "history/*": ["history/v2/*"], - "react-router": ["react-router/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index c013e2c959..e2a4e054ad 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -10,9 +10,7 @@ "strictNullChecks": false, "jsx": "react", "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json index c92402947c..d9c384bdcf 100644 --- a/react-router/v2/tsconfig.json +++ b/react-router/v2/tsconfig.json @@ -14,7 +14,8 @@ ], "paths": { "history": ["history/v2"], - "react-router": ["react-router/v2"] + "react-router": ["react-router/v2"], + "react-router/*": ["react-router/v2/*"] }, "types": [], "noEmit": true, diff --git a/redux-bootstrap/index.d.ts b/redux-bootstrap/index.d.ts index 6a539853b7..a4dc46fcfc 100644 --- a/redux-bootstrap/index.d.ts +++ b/redux-bootstrap/index.d.ts @@ -1,29 +1,29 @@ -// Type definitions for react-bootstrap v1.0.0 +// Type definitions for react-bootstrap 1.0 // Project: https://github.com/remojansen/redux-bootstrap // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "redux-bootstrap" { - import * as Redux from "redux"; - import ReactRouterRedux = require("react-router-redux"); +import * as React from "react"; +import { Middleware, Reducer, Store } from "redux"; +import { History } from "history"; - interface BootstrapOptions { - routes: JSX.Element; - reducers: ReducersOption; - middlewares?: Redux.Middleware[]; - initialState?: any; - container?: string; - } - - interface BootstrapResult { - store: Redux.Store; - history: ReactRouterRedux.ReactRouterReduxHistory; - root: JSX.Element; - } - - interface ReducersOption { - [index: string]: Redux.Reducer; - } - - export default function bootstrap(options: BootstrapOptions): BootstrapResult; +export interface BootstrapOptions { + routes: JSX.Element; + reducers: ReducersOption; + middlewares?: Middleware[]; + initialState?: any; + container?: string; } + +export interface BootstrapResult { + store: Store; + history: History; + root: JSX.Element; +} + +export interface ReducersOption { + [index: string]: Reducer; +} + +export default function bootstrap(options: BootstrapOptions): BootstrapResult; + diff --git a/redux-bootstrap/tsconfig.json b/redux-bootstrap/tsconfig.json index a5c0900ca4..cca0524f9c 100644 --- a/redux-bootstrap/tsconfig.json +++ b/redux-bootstrap/tsconfig.json @@ -9,9 +9,6 @@ "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], From 44dec616d0bb9d56e3a06c93d6d403586024b72b Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 27 Jan 2017 11:27:16 +0900 Subject: [PATCH 61/85] Remove inline types references --- react-router-redux/v3/react-router-redux-tests.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/react-router-redux/v3/react-router-redux-tests.ts b/react-router-redux/v3/react-router-redux-tests.ts index b92af315b2..c719fb8459 100644 --- a/react-router-redux/v3/react-router-redux-tests.ts +++ b/react-router-redux/v3/react-router-redux-tests.ts @@ -1,9 +1,3 @@ - -/// -/// - - - import { createStore, combineReducers, applyMiddleware } from 'redux'; import { browserHistory } from 'react-router'; import { syncHistory, routeReducer } from 'react-router-redux'; From f4f285ee2f21ae2ca980bc105b4b5564b0ec6667 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 27 Jan 2017 11:42:19 +0900 Subject: [PATCH 62/85] Set target compiler to 2.1, add old react-router reference for react-router-redux tests --- react-router-redux/index.d.ts | 1 + react-router-redux/v3/index.d.ts | 1 + react-router-redux/v3/tsconfig.json | 2 ++ react-router/index.d.ts | 1 + react-router/v2/index.d.ts | 3 +-- 5 files changed, 6 insertions(+), 2 deletions(-) diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index db1f8d5f24..226b3152e3 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rackt/react-router-redux // Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import { Action, Middleware, Store } from "redux"; import { History } from "history"; diff --git a/react-router-redux/v3/index.d.ts b/react-router-redux/v3/index.d.ts index d11b7826f4..90e884a221 100644 --- a/react-router-redux/v3/index.d.ts +++ b/react-router-redux/v3/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rackt/react-router-redux // Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as Redux from "redux"; import * as History from "history"; diff --git a/react-router-redux/v3/tsconfig.json b/react-router-redux/v3/tsconfig.json index ee406e1759..98e20b8d42 100644 --- a/react-router-redux/v3/tsconfig.json +++ b/react-router-redux/v3/tsconfig.json @@ -14,6 +14,8 @@ ], "paths": { "history": ["history/v2"], + "react-router": ["react-router/v2"], + "react-router/*": ["react-router/v2/*"], "react-router-redux": ["react-router-redux/v3"] }, "types": [], diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 2b10a4cbcb..1e9770938c 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rackt/react-router // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /* Replacement from old history definitions */ export interface HistoryOptions { diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts index 80b1b97154..b0a96487bf 100644 --- a/react-router/v2/index.d.ts +++ b/react-router/v2/index.d.ts @@ -2,8 +2,7 @@ // Project: https://github.com/rackt/react-router // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.1 export as namespace ReactRouter; From 80e8e768c2bd958af29859581ab6f3c3e63c59d8 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 27 Jan 2017 11:50:09 +0900 Subject: [PATCH 63/85] Remove wildcard path mapping --- react-router-redux/v3/tsconfig.json | 1 - 1 file changed, 1 deletion(-) diff --git a/react-router-redux/v3/tsconfig.json b/react-router-redux/v3/tsconfig.json index 98e20b8d42..240e09923e 100644 --- a/react-router-redux/v3/tsconfig.json +++ b/react-router-redux/v3/tsconfig.json @@ -15,7 +15,6 @@ "paths": { "history": ["history/v2"], "react-router": ["react-router/v2"], - "react-router/*": ["react-router/v2/*"], "react-router-redux": ["react-router-redux/v3"] }, "types": [], From c068a82a50914328790a6f0fcaadd900a19eb899 Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Fri, 27 Jan 2017 16:58:47 +0100 Subject: [PATCH 64/85] Add contributor --- express-jwt/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index edffeb9632..4b6883a258 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for express-jwt // Project: https://www.npmjs.org/package/express-jwt -// Definitions by: Wonshik Kim +// Definitions by: Wonshik Kim , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); From 1764c825a30f370341214a5305636697921d3979 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Fri, 27 Jan 2017 18:23:12 +0100 Subject: [PATCH 65/85] Fix errors. Rename "shipit" to "shipit-cli". --- express-rate-limit/index.d.ts | 6 ++--- {shipit => shipit-cli}/index.d.ts | 24 +++++++++---------- .../shipit-cli-tests.ts | 0 {shipit => shipit-cli}/tsconfig.json | 2 +- {shipit => shipit-cli}/tslint.json | 0 shipit-utils/index.d.ts | 3 +-- 6 files changed, 17 insertions(+), 18 deletions(-) rename {shipit => shipit-cli}/index.d.ts (77%) rename shipit/shipit-tests.ts => shipit-cli/shipit-cli-tests.ts (100%) rename {shipit => shipit-cli}/tsconfig.json (93%) rename {shipit => shipit-cli}/tslint.json (100%) diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts index 07cb5853a5..38ef8f8b29 100644 --- a/express-rate-limit/index.d.ts +++ b/express-rate-limit/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import express = require("express"); declare namespace RateLimit { @@ -19,10 +17,12 @@ declare namespace RateLimit { export interface Options { delayAfter?: number; delayMs?: number; + handlers?: () => any; headers?: boolean; - keyGenerator?: Function; + keyGenerator?: () => string; max?: number; message?: string; + skip?: () => boolean; statusCode?: number; store?: Store; windowMs?: number; diff --git a/shipit/index.d.ts b/shipit-cli/index.d.ts similarity index 77% rename from shipit/index.d.ts rename to shipit-cli/index.d.ts index 7b153ae197..d438300df3 100644 --- a/shipit/index.d.ts +++ b/shipit-cli/index.d.ts @@ -5,14 +5,13 @@ /// -declare module "shipit-cli" { - import shipit = require("shipit-cli"); - - import * as fs from "fs"; - import * as child_process from "child_process"; +import * as fs from "fs"; +import * as child_process from "child_process"; +declare module shipit { type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; - type TaskExecution = (name: string, depsOrFn: string[] | Function, fn: Function) => any; + type TaskExecution = (name: string, depsOrFn: string[] | Function, fn: () => void) => any; + type EmptyCallback = () => void; export interface Options { environment: string; @@ -33,23 +32,22 @@ declare module "shipit-cli" { export interface Task { blocking: boolean; dep: string[]; - fn: Function; + fn: () => void; name: string; } - export function blTask(name: string, depsOrFn: string[] | Function, fn?: Function): any; + export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; export function emit(name: string): any; export function initConfig(config: {}): typeof shipit; export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; export function log(log: any): void; export function log(...log: any[]): void; - export function on(name: string, callback: Function): any; + export function on(name: string, callback: (e: any) => void): any; export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function start(tasks: string): typeof shipit; - export function start(tasks: string[]): typeof shipit; + export function start(tasks: string | string[]): typeof shipit; export function start(...tasks: string[]): typeof shipit; - export function task(name: string, depsOrFn: string[] | Function, fn?: Function): typeof shipit; + export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; export var config: {}; export var domain: any; @@ -59,3 +57,5 @@ declare module "shipit-cli" { export var tasks: Tasks; export var isRunning: boolean; } + +export = shipit; diff --git a/shipit/shipit-tests.ts b/shipit-cli/shipit-cli-tests.ts similarity index 100% rename from shipit/shipit-tests.ts rename to shipit-cli/shipit-cli-tests.ts diff --git a/shipit/tsconfig.json b/shipit-cli/tsconfig.json similarity index 93% rename from shipit/tsconfig.json rename to shipit-cli/tsconfig.json index 17049e7271..dccd637a84 100644 --- a/shipit/tsconfig.json +++ b/shipit-cli/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "shipit-tests.ts" + "shipit-cli-tests.ts" ] } diff --git a/shipit/tslint.json b/shipit-cli/tslint.json similarity index 100% rename from shipit/tslint.json rename to shipit-cli/tslint.json diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index 63df44974f..28f13a3fc5 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -15,8 +15,7 @@ declare module "shipit-utils" { export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; - export function registerTask(gruntOrShipit: GruntOrShipit, name: string, task: Function): typeof shipit; - export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependencies: string[]): typeof shipit; + export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependenciesOrTask: string[]|Function): typeof shipit; export function runTask(gruntOrShipit: {}): void; } From 11b98355561d791446e98120a664da9c824801a2 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Fri, 27 Jan 2017 18:51:58 +0100 Subject: [PATCH 66/85] Fix errors. --- shipit-cli/index.d.ts | 61 ------------------- shipit-utils/index.d.ts | 2 +- shipit/index.d.ts | 61 +++++++++++++++++++ .../shipit-tests.ts | 2 +- {shipit-cli => shipit}/tsconfig.json | 2 +- {shipit-cli => shipit}/tslint.json | 0 6 files changed, 64 insertions(+), 64 deletions(-) delete mode 100644 shipit-cli/index.d.ts create mode 100644 shipit/index.d.ts rename shipit-cli/shipit-cli-tests.ts => shipit/shipit-tests.ts (96%) rename {shipit-cli => shipit}/tsconfig.json (93%) rename {shipit-cli => shipit}/tslint.json (100%) diff --git a/shipit-cli/index.d.ts b/shipit-cli/index.d.ts deleted file mode 100644 index d438300df3..0000000000 --- a/shipit-cli/index.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Type definitions for shipit-cli 1.5 -// Project: https://github.com/shipitjs/shipit -// Definitions by: Cyril Schumacher -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import * as fs from "fs"; -import * as child_process from "child_process"; - -declare module shipit { - type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; - type TaskExecution = (name: string, depsOrFn: string[] | Function, fn: () => void) => any; - type EmptyCallback = () => void; - - export interface Options { - environment: string; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - export interface ShipitLocal { - child: child_process.ChildProcess; - stderr: fs.WriteStream; - stdout: fs.WriteStream; - } - - export interface Tasks { - [name: string]: Task; - } - - export interface Task { - blocking: boolean; - dep: string[]; - fn: () => void; - name: string; - } - - export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; - export function emit(name: string): any; - export function initConfig(config: {}): typeof shipit; - export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function log(log: any): void; - export function log(...log: any[]): void; - export function on(name: string, callback: (e: any) => void): any; - export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - export function start(tasks: string | string[]): typeof shipit; - export function start(...tasks: string[]): typeof shipit; - export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; - - export var config: {}; - export var domain: any; - export var doneCallback: any; - export var environment: string; - export var seq: any[]; - export var tasks: Tasks; - export var isRunning: boolean; -} - -export = shipit; diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index 28f13a3fc5..28a00c2aad 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "shipit-utils" { import shipit = require("shipit-cli"); diff --git a/shipit/index.d.ts b/shipit/index.d.ts new file mode 100644 index 0000000000..f0c00d8d2d --- /dev/null +++ b/shipit/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for shipit-cli 1.5 +// Project: https://github.com/shipitjs/shipit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as fs from "fs"; +import * as child_process from "child_process"; + +declare namespace shipit { + type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; + type EmptyCallback = () => void; + type TaskExecution = (name: string, depsOrFn: string[] | EmptyCallback, fn: () => void) => any; + + interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + interface Tasks { + [name: string]: Task; + } + + interface Task { + blocking: boolean; + dep: string[]; + fn: () => void; + name: string; + } + + function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; + function emit(name: string): any; + function initConfig(config: {}): typeof shipit; + function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + function log(log: any): void; + function log(...log: any[]): void; + function on(name: string, callback: (e: any) => void): any; + function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + function start(tasks: string | string[]): typeof shipit; + function start(...tasks: string[]): typeof shipit; + function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + + var config: {}; + var domain: any; + var doneCallback: any; + var environment: string; + var seq: any[]; + var tasks: Tasks; + var isRunning: boolean; +} + +export = shipit; diff --git a/shipit-cli/shipit-cli-tests.ts b/shipit/shipit-tests.ts similarity index 96% rename from shipit-cli/shipit-cli-tests.ts rename to shipit/shipit-tests.ts index 50dff54978..a256f87e07 100644 --- a/shipit-cli/shipit-cli-tests.ts +++ b/shipit/shipit-tests.ts @@ -1,4 +1,4 @@ -import shipit = require("shipit-cli"); +import shipit = require("shipit"); shipit.initConfig({ default: { diff --git a/shipit-cli/tsconfig.json b/shipit/tsconfig.json similarity index 93% rename from shipit-cli/tsconfig.json rename to shipit/tsconfig.json index dccd637a84..17049e7271 100644 --- a/shipit-cli/tsconfig.json +++ b/shipit/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "shipit-cli-tests.ts" + "shipit-tests.ts" ] } diff --git a/shipit-cli/tslint.json b/shipit/tslint.json similarity index 100% rename from shipit-cli/tslint.json rename to shipit/tslint.json From 3ba808f9cea9c4f18e915b15d581dbc5ae9294b2 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Fri, 27 Jan 2017 18:52:20 +0100 Subject: [PATCH 67/85] Fix errors. --- shipit-utils/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index 28a00c2aad..fa29e53609 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -3,10 +3,10 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "shipit-utils" { - import shipit = require("shipit-cli"); + import shipit = require("shipit"); type GruntOrShipit = typeof shipit | {}; From 3757f74794a0ec0ca01a89088001bdaef0a658a5 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Fri, 27 Jan 2017 19:09:38 +0100 Subject: [PATCH 68/85] Fix tslint errors. --- shipit-utils/index.d.ts | 22 ++++++---------- shipit-utils/shipit-utils-tests.ts | 2 +- shipit/index.d.ts | 40 ++++++++++++++++-------------- 3 files changed, 30 insertions(+), 34 deletions(-) diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index fa29e53609..aec379f5f2 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -3,19 +3,13 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import shipit = require("shipit"); -declare module "shipit-utils" { - import shipit = require("shipit"); +type GruntOrShipit = typeof shipit | {}; +type EmptyCallback = () => void; - type GruntOrShipit = typeof shipit | {}; - - export function equalValues(value: any[]): void; - - export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; - export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; - - export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependenciesOrTask: string[]|Function): typeof shipit; - - export function runTask(gruntOrShipit: {}): void; -} +export function equalValues(value: any[]): void; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; +export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependenciesOrTask: string[] | EmptyCallback): typeof shipit; +export function runTask(gruntOrShipit: {}): void; diff --git a/shipit-utils/shipit-utils-tests.ts b/shipit-utils/shipit-utils-tests.ts index 15f0d5547b..81cb741054 100644 --- a/shipit-utils/shipit-utils-tests.ts +++ b/shipit-utils/shipit-utils-tests.ts @@ -1,4 +1,4 @@ -import shipit = require("shipit-cli"); +import shipit = require("shipit"); import utils = require("shipit-utils"); var originalShipit = utils.getShipit(shipit); diff --git a/shipit/index.d.ts b/shipit/index.d.ts index f0c00d8d2d..8c614f1627 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -36,26 +36,28 @@ declare namespace shipit { name: string; } - function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; - function emit(name: string): any; - function initConfig(config: {}): typeof shipit; - function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - function log(log: any): void; - function log(...log: any[]): void; - function on(name: string, callback: (e: any) => void): any; - function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; - function start(tasks: string | string[]): typeof shipit; - function start(...tasks: string[]): typeof shipit; - function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; + export function blTask(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): any; + export function emit(name: string): any; + export function initConfig(config: {}): typeof shipit; + export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function log(log: any): void; + export function log(...log: any[]): void; + export function on(name: string, callback: (e: any) => void): any; + export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function start(tasks: string | string[]): typeof shipit; + export function start(...tasks: string[]): typeof shipit; + export function task(name: string, depsOrFn: string[] | EmptyCallback, fn?: () => void): typeof shipit; - var config: {}; - var domain: any; - var doneCallback: any; - var environment: string; - var seq: any[]; - var tasks: Tasks; - var isRunning: boolean; + export var config: {}; + export var domain: any; + export var doneCallback: any; + export var environment: string; + export var seq: any[]; + export var tasks: Tasks; + export var isRunning: boolean; } +//tslint:disable-next-line:export-just-namespace export = shipit; +export as namespace shipit; From 3b90b20748aff91fbc4d008d42e4052743ffbd73 Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Sat, 28 Jan 2017 15:58:37 +0100 Subject: [PATCH 69/85] Rename old definitions --- needle/v0/index.d.ts | 92 +++++++++++++++++++++++++++++++++ needle/v0/needle-tests.ts | 106 ++++++++++++++++++++++++++++++++++++++ needle/v0/tsconfig.json | 27 ++++++++++ 3 files changed, 225 insertions(+) create mode 100644 needle/v0/index.d.ts create mode 100644 needle/v0/needle-tests.ts create mode 100644 needle/v0/tsconfig.json diff --git a/needle/v0/index.d.ts b/needle/v0/index.d.ts new file mode 100644 index 0000000000..fbeb349c33 --- /dev/null +++ b/needle/v0/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for needle 0.7.8 +// Project: https://github.com/tomas/needle +// Definitions by: San Chen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "needle" { + import * as http from 'http'; + import * as Buffer from 'buffer'; + module Needle { + interface NeedleResponse extends http.IncomingMessage { + body: any; + raw: Buffer; + bytes: number; + } + + interface ReadableStream extends NodeJS.ReadableStream { + } + + interface Callback { + (error: Error, response: NeedleResponse, body: any): void; + } + + interface RequestOptions { + timeout?: number; + follow?: number; + follow_max?: number; + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: Object; + auth?: string; // auto | digest | basic (default) + json?: boolean; + + // These properties are overwritten by those in the 'headers' field + compressed?: boolean; + cookies?: { [name: string]: any; }; + // Overwritten if present in the URI + username?: string; + password?: string; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string): ReadableStream; + head(url: string, callback?: Callback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + get(url: string): ReadableStream; + get(url: string, callback?: Callback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + post(url: string, data: any): ReadableStream; + post(url: string, data: any, callback?: Callback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + put(url: string, data: any): ReadableStream; + put(url: string, data: any, callback?: Callback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + delete(url: string, data: any): ReadableStream; + delete(url: string, data: any, callback?: Callback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + request(method: string, url: string, data: any): ReadableStream; + request(method: string, url: string, data: any, callback?: Callback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + } + } + + var needle: Needle.NeedleStatic; + export = needle; +} diff --git a/needle/v0/needle-tests.ts b/needle/v0/needle-tests.ts new file mode 100644 index 0000000000..5a849ec204 --- /dev/null +++ b/needle/v0/needle-tests.ts @@ -0,0 +1,106 @@ +import needle = require("needle"); + +function Usage() { + // using callback + needle.get('http://ifconfig.me/all.json', function (error, response) { + if (!error) + console.log(response.body.ip_addr); // JSON decoding magic. :) + }); + + // using streams + var out: any; // = fs.createWriteStream('logo.png'); + needle.get('https://google.com/images/logo.png').pipe(out); +} + +function ResponsePipeline() { + needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { + console.log(resp.body); // this little guy won't be a Gzipped binary blob + // but a nice object containing all the latest entries + }); + + var options = { + compressed: true, + follow: 5, + rejectUnauthorized: true + }; + + // in this case, we'll ask Needle to follow redirects (disabled by default), + // but also to verify their SSL certificates when connecting. + var stream = needle.get('https://backend.server.com/everything.html', options); + + stream.on('readable', function () { + var data: any; + while (data = stream.read()) { + console.log(data.toString()); + } + }); +} + +function API_head() { + var options = { + timeout: 5000 // if we don't get a response in 5 seconds, boom. + }; + + needle.head('https://my.backend.server.com', function (err, resp) { + if (err) { + console.log('Shoot! Something is wrong: ' + err.message); + } + else { + console.log('Yup, still alive.'); + } + }); +} + +function API_get() { + needle.get('google.com/search?q=syd+barrett', function (err, resp) { + // if no http:// is found, Needle will automagically prepend it. + }); +} + +function API_post() { + var options = { + headers: { 'X-Custom-Header': 'Bumbaway atuna' } + }; + + needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) { + // you can pass params as a string or as an object. + }); +} + +function API_put() { + var nested = { + params: { + are: { + also: 'supported' + } + } + }; + + needle.put('https://api.app.com/v2', nested, function (err, resp) { + console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. + }); +} + +function API_delete() { + var options = { + username: 'fidelio', + password: 'x' + }; + + needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) { + // in this case, data may be null, but you need to explicity pass it. + }); +} + +function API_request() { + var data = { + q: 'a very smart query', + page: 2, + format: 'json' + }; + + needle.request('get', 'forum.com/search', data, function (err, resp) { + if (!err && resp.statusCode == 200) + console.log(resp.body); // here you go, mister. + }); +} diff --git a/needle/v0/tsconfig.json b/needle/v0/tsconfig.json new file mode 100644 index 0000000000..44c8b59654 --- /dev/null +++ b/needle/v0/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../../" + ], + "paths": { + "needle": [ + "needle/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "needle-tests.ts" + ] +} From f2189422605944f5acc5ee840b21d952c26f138f Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Sat, 28 Jan 2017 16:22:21 +0100 Subject: [PATCH 70/85] Add updated/rewritten definitions for v1 --- needle/index.d.ts | 114 ++++++++++++++++++++------------- needle/needle-tests.ts | 139 ++++++++++++++++++++++++++++++++++++++--- needle/tsconfig.json | 6 +- needle/v0/index.d.ts | 43 +++++-------- 4 files changed, 221 insertions(+), 81 deletions(-) diff --git a/needle/index.d.ts b/needle/index.d.ts index 7607fdfc78..f7e3bc275c 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for needle 0.7.8 +// Type definitions for needle 1.4 // Project: https://github.com/tomas/needle -// Definitions by: San Chen +// Definitions by: San Chen , Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,85 +8,111 @@ declare module "needle" { import * as http from 'http'; import * as Buffer from 'buffer'; - module Needle { + import * as https from 'https'; + namespace Needle { interface NeedleResponse extends http.IncomingMessage { body: any; raw: Buffer; bytes: number; } - interface ReadableStream extends NodeJS.ReadableStream { + type ReadableStream = NodeJS.ReadableStream; + + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; + + interface Cookies { + [name: string]: any; } - interface Callback { - (error: Error, response: NeedleResponse, body: any): void; - } + type NeedleOptions = RequestOptions & ResponseOptions & RedirectOptions & https.RequestOptions; interface RequestOptions { + open_timeout?: number; + read_timeout?: number; + /** + * Alias for open_timeout + */ timeout?: number; - follow?: number; + follow_max?: number; + /** + * Alias for follow_max + */ + follow?: number; + multipart?: boolean; + agent?: http.Agent | boolean; proxy?: string; - agent?: string; - headers?: Object; - auth?: string; // auto | digest | basic (default) + headers?: {}; + auth?: "auto" | "digest" | "basic"; json?: boolean; // These properties are overwritten by those in the 'headers' field + cookies?: Cookies; compressed?: boolean; - cookies?: { [name: string]: any; }; // Overwritten if present in the URI username?: string; password?: string; + accept?: string; + connection?: string; + user_agent?: string; } interface ResponseOptions { + decode_response?: boolean; + /** + * Alias for decode_response + */ decode?: boolean; + parse_response?: boolean; + /** + * Alias for parse_response + */ parse?: boolean; - output?: any; + + parse_cookies?: boolean; + output?: string; } - interface TLSOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: any; - rejectUnauthorized?: boolean; - secureProtocol?: any; + interface RedirectOptions { + follow_set_cookie?: boolean; + follow_set_referer?: boolean; + follow_keep_method?: boolean; + follow_if_same_host?: boolean; + follow_if_same_protocol?: boolean; } + interface KeyValue { + [key: string]: any; + } + + type BodyData = Buffer | KeyValue | NodeJS.ReadableStream | string | null; + interface NeedleStatic { - defaults(options?: any): void; + defaults(options: NeedleOptions): void; - head(url: string): ReadableStream; - head(url: string, callback?: Callback): ReadableStream; - head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - get(url: string): ReadableStream; - get(url: string, callback?: Callback): ReadableStream; - get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - post(url: string, data: any): ReadableStream; - post(url: string, data: any, callback?: Callback): ReadableStream; - post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + post(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + post(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - put(url: string, data: any): ReadableStream; - put(url: string, data: any, callback?: Callback): ReadableStream; - put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + put(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + put(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - delete(url: string, data: any): ReadableStream; - delete(url: string, data: any, callback?: Callback): ReadableStream; - delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + patch(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + patch(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - request(method: string, url: string, data: any): ReadableStream; - request(method: string, url: string, data: any, callback?: Callback): ReadableStream; - request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + delete(url: string, data: BodyData, callback ?: NeedleCallback): ReadableStream; + delete(url: string, data: BodyData, options ?: NeedleOptions, callback ?: NeedleCallback): ReadableStream; + + request(method: string, url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; } } - - var needle: Needle.NeedleStatic; + const needle: Needle.NeedleStatic; export = needle; -} \ No newline at end of file +} diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 3df14952c3..1c5090027a 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -1,4 +1,5 @@ -import needle = require("needle"); +import * as needle from "needle"; +import * as fs from "fs"; function Usage() { // using callback @@ -14,7 +15,7 @@ function Usage() { function ResponsePipeline() { needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) { - console.log(resp.body); // this little guy won't be a Gzipped binary blob + console.log(resp.body); // this little guy won't be a Gzipped binary blob // but a nice object containing all the latest entries }); @@ -24,21 +25,26 @@ function ResponsePipeline() { rejectUnauthorized: true }; - // in this case, we'll ask Needle to follow redirects (disabled by default), + // in this case, we'll ask Needle to follow redirects (disabled by default), // but also to verify their SSL certificates when connecting. var stream = needle.get('https://backend.server.com/everything.html', options); stream.on('readable', function () { var data: any; - while (data = this.read()) { + while (data = stream.read()) { console.log(data.toString()); } }); + + stream.on('end', function(err: any) { + // if our request had an error, our 'end' event will tell us. + if (!err) console.log('Great success!'); + }) } function API_head() { var options = { - timeout: 5000 // if we don't get a response in 5 seconds, boom. + open_timeout: 5000 // if we don't get a response in 5 seconds, boom. }; needle.head('https://my.backend.server.com', function (err, resp) { @@ -93,14 +99,131 @@ function API_delete() { } function API_request() { - var data = { + var params = { q: 'a very smart query', page: 2, - format: 'json' }; - needle.request('get', 'forum.com/search', data, function (err, resp) { + needle.request('get', 'forum.com/search', params, function (err, resp) { if (!err && resp.statusCode == 200) console.log(resp.body); // here you go, mister. }); + + needle.request('get', 'forum.com/search', params, { json: true }, function(err, resp) { + if (resp.statusCode == 200) console.log('It worked!'); + }); +} + +function HttpGetWithBasicAuth() { + needle.get('https://api.server.com', { username: 'you', password: 'secret' }, function(err, resp) { + // used HTTP auth + }); + needle.get('https://username:password@api.server.com', function(err, resp) { + // used HTTP auth from URL + }); +} + +function DigestAuth() { + needle.get('other.server.com', { username: 'you', password: 'secret', auth: 'digest' }, function(err, resp, body) { + // needle prepends 'http://' to your URL, if missing + }); +} + +function CustomAcceptHeaderDeflate() { + var options = { + compressed: true, + follow: 10, + accept: 'application/vnd.github.full+json' + } + + needle.get('api.github.com/users/tomas', options, function(err, resp, body) { + // body will contain a JSON.parse(d) object + // if parsing fails, you'll simply get the original body + }); + +} + +function Various() { + + needle.get('https://news.ycombinator.com/rss', function(err, resp, body) { + // if xml2js is installed, you'll get a nice object containing the nodes in the RSS + }); + needle.get('http://upload.server.com/tux.png', { output: '/tmp/tux.png' }, function(err, resp, body) { + // you can dump any response to a file, not only binaries. + }); + needle.get('http://search.npmjs.org', { proxy: 'http://localhost:1234' }, function(err, resp, body) { + // request passed through proxy + }); + const stream1 = needle.get('http://www.as35662.net/100.log'); + stream1.on('readable', function() { + let chunk: any; + while (chunk = stream1.read()) { + console.log('got data: ', chunk); + } + }); + const stream2 = needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }); + stream2.on('readable', function() { + let node: any; + + // our stream2 will only emit a single JSON root node. + while (node = stream2.read()) { + console.log('got data: ', node); + } + }); + + /* + // Sample omitted, no JSONStream + needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }) + .pipe(new JSONStream.parse('posts.*.title')) + .on('data', function (obj) { + console.log('got post title: %s', obj); + }); + */ +} + +function FileUpload() { + var data = { + foo: 'bar', + image: { file: '/home/tomas/linux.png', content_type: 'image/png' } + }; + + needle.post('http://my.other.app.com', data, { multipart: true }, function(err, resp, body) { + // needle will read the file and include it in the form-data as binary + }); + needle.put('https://api.app.com/v2', fs.createReadStream('myfile.txt'), function(err, resp, body) { + // stream content is uploaded verbatim + }); +} + +function Multipart() { + var buffer = fs.readFileSync('/path/to/package.zip'); + + var data = { + zip_file: { + buffer: buffer, + filename: 'mypackage.zip', + content_type: 'application/octet-stream' + } + } + + needle.post('http://somewhere.com/over/the/rainbow', data, { multipart: true }, function(err, resp, body) { + // if you see, when using buffers we need to pass the filename for the multipart body. + // you can also pass a filename when using the file path method, in case you want to override + // the default filename to be received on the other end. + }); +} + +function MultipartContentType() { + var data = { + token: 'verysecret', + payload: { + value: JSON.stringify({ title: 'test', version: 1 }), + content_type: 'application/json' + } + } + + needle.post('http://test.com/', data, { timeout: 5000, multipart: true }, function(err, resp, body) { + // in this case, if the request takes more than 5 seconds + // the callback will return a [Socket closed] error + }); } diff --git a/needle/tsconfig.json b/needle/tsconfig.json index 5af602dd4f..59f9b2b49e 100644 --- a/needle/tsconfig.json +++ b/needle/tsconfig.json @@ -5,8 +5,8 @@ "es6" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "needle-tests.ts" ] -} \ No newline at end of file +} diff --git a/needle/v0/index.d.ts b/needle/v0/index.d.ts index fbeb349c33..28b5b8119f 100644 --- a/needle/v0/index.d.ts +++ b/needle/v0/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for needle 0.7.8 +// Type definitions for needle 0.7 // Project: https://github.com/tomas/needle // Definitions by: San Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,19 +8,16 @@ declare module "needle" { import * as http from 'http'; import * as Buffer from 'buffer'; - module Needle { + namespace Needle { interface NeedleResponse extends http.IncomingMessage { body: any; raw: Buffer; bytes: number; } - interface ReadableStream extends NodeJS.ReadableStream { - } + type ReadableStream = NodeJS.ReadableStream; - interface Callback { - (error: Error, response: NeedleResponse, body: any): void; - } + type NeedleCallback = (error: Error, response: NeedleResponse, body: any) => void; interface RequestOptions { timeout?: number; @@ -29,7 +26,7 @@ declare module "needle" { multipart?: boolean; proxy?: string; agent?: string; - headers?: Object; + headers?: {}; auth?: string; // auto | digest | basic (default) json?: boolean; @@ -61,29 +58,23 @@ declare module "needle" { interface NeedleStatic { defaults(options?: any): void; - head(url: string): ReadableStream; - head(url: string, callback?: Callback): ReadableStream; - head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + head(url: string, callback?: NeedleCallback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; - get(url: string): ReadableStream; - get(url: string, callback?: Callback): ReadableStream; - get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + get(url: string, callback?: NeedleCallback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; - post(url: string, data: any): ReadableStream; - post(url: string, data: any, callback?: Callback): ReadableStream; - post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + post(url: string, data: any, callback?: NeedleCallback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; - put(url: string, data: any): ReadableStream; - put(url: string, data: any, callback?: Callback): ReadableStream; - put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + put(url: string, data: any, callback?: NeedleCallback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; - delete(url: string, data: any): ReadableStream; - delete(url: string, data: any, callback?: Callback): ReadableStream; - delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + delete(url: string, data: any, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; - request(method: string, url: string, data: any): ReadableStream; - request(method: string, url: string, data: any, callback?: Callback): ReadableStream; - request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + request(method: string, url: string, data: any, callback?: NeedleCallback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: NeedleCallback): ReadableStream; } } From e1cd2ae0026c09c633cecf2e432ee0f927f54259 Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Sun, 29 Jan 2017 13:39:36 -0500 Subject: [PATCH 71/85] Update d3-hierarchy 1.1/d3 4.5 * [d3-hierarchy] Add `count()` method to hierarchy node interfaces * [d3-hierarchy] Update header to reflect v1.1 minor version * [d3] Bump minor version to 4.5 --- d3-hierarchy/d3-hierarchy-tests.ts | 23 +++++++++++++++++++++ d3-hierarchy/index.d.ts | 32 ++++++++++++++++++------------ d3/index.d.ts | 2 +- 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/d3-hierarchy/d3-hierarchy-tests.ts b/d3-hierarchy/d3-hierarchy-tests.ts index ce7354afe3..7079fae827 100644 --- a/d3-hierarchy/d3-hierarchy-tests.ts +++ b/d3-hierarchy/d3-hierarchy-tests.ts @@ -125,6 +125,13 @@ hierarchyRootNode = hierarchyRootNode.sum(function (d) { return d.val; }); num = hierarchyRootNode.value; +// count() and value ---------------------------------------------------------- + +hierarchyRootNode = hierarchyRootNode.count(); + +num = hierarchyRootNode.value; + + // sort --------------------------------------------------------------------- hierarchyRootNode = hierarchyRootNode.sort(function (a, b) { @@ -307,6 +314,12 @@ clusterRootNode = clusterRootNode.sum(function (d) { return d.val; }); num = clusterRootNode.value; +// count() and value ---------------------------------------------------------- + +clusterRootNode = clusterRootNode.count(); + +num = clusterRootNode.value; + // sort --------------------------------------------------------------------- clusterRootNode = clusterRootNode.sort(function (a, b) { @@ -584,6 +597,11 @@ treemapRootNode = treemapRootNode.sum(function (d) { return d.val; }); num = treemapRootNode.value; +// count() and value ---------------------------------------------------------- + +treemapRootNode = treemapRootNode.count(); + +num = treemapRootNode.value; // sort --------------------------------------------------------------------- treemapRootNode = treemapRootNode.sort(function (a, b) { @@ -766,6 +784,11 @@ packRootNode = packRootNode.sum(function (d) { return d.val; }); num = packRootNode.value; +// count() and value ---------------------------------------------------------- + +packRootNode = packRootNode.count(); + +num = packRootNode.value; // sort --------------------------------------------------------------------- packRootNode = packRootNode.sort(function (a, b) { diff --git a/d3-hierarchy/index.d.ts b/d3-hierarchy/index.d.ts index 7eef444875..bfe750b31e 100644 --- a/d3-hierarchy/index.d.ts +++ b/d3-hierarchy/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for D3JS d3-hierarchy module v1.0.2 +// Type definitions for D3JS d3-hierarchy module 1.1 // Project: https://github.com/d3/d3-hierarchy/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last module patch version validated against: 1.1.1 + // ----------------------------------------------------------------------- // Hierarchy // ----------------------------------------------------------------------- @@ -20,7 +22,7 @@ export interface HierarchyNode { parent: HierarchyNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -35,6 +37,7 @@ export interface HierarchyNode { path(target: HierarchyNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this; each(func: (node: HierarchyNode) => void): this; eachAfter(func: (node: HierarchyNode) => void): this; @@ -43,7 +46,7 @@ export interface HierarchyNode { } -export function hierarchy(data: Datum, children?: (d: Datum) => (Array | null)): HierarchyNode; +export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode; // ----------------------------------------------------------------------- // Stratify @@ -53,11 +56,11 @@ export function hierarchy(data: Datum, children?: (d: Datum) => (Array { - (data: Array): HierarchyNode; - id(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - id(id: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; - parentId(): (d: Datum, i: number, data: Array) => (string | null | '' | undefined); - parentId(parentId: (d: Datum, i?: number, data?: Array) => (string | null | '' | undefined)): this; + (data: Datum[]): HierarchyNode; + id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; + parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined); + parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this; } export function stratify(): StratifyOperator; @@ -80,7 +83,7 @@ export interface HierarchyPointNode { parent: HierarchyPointNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -95,6 +98,7 @@ export interface HierarchyPointNode { path(target: HierarchyPointNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this; each(func: (node: HierarchyPointNode) => void): this; eachAfter(func: (node: HierarchyPointNode) => void): this; @@ -150,7 +154,7 @@ export interface HierarchyRectangularNode { parent: HierarchyRectangularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -165,6 +169,7 @@ export interface HierarchyRectangularNode { path(target: HierarchyRectangularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this; each(func: (node: HierarchyRectangularNode) => void): this; eachAfter(func: (node: HierarchyRectangularNode) => void): this; @@ -258,7 +263,7 @@ export interface HierarchyCircularNode { parent: HierarchyCircularNode | null; children?: Array>; /** - * Aggregated numeric value as calculated by sum(value), + * Aggregated numeric value as calculated by sum(value) or count(), * if previously invoked. */ readonly value?: number; @@ -273,6 +278,7 @@ export interface HierarchyCircularNode { path(target: HierarchyCircularNode): Array>; links(): Array>; sum(value: (d: Datum) => number): this; + count(): this; sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this; each(func: (node: HierarchyCircularNode) => void): this; eachAfter(func: (node: HierarchyCircularNode) => void): this; @@ -310,6 +316,6 @@ export interface PackCircle { // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment // on the mandatory nature, then to create separate interfaces and having to deal with recasting. -export function packSiblings(circles: Array): Array; +export function packSiblings(circles: Datum[]): Datum[]; -export function packEnclose(circles: Array): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; diff --git a/d3/index.d.ts b/d3/index.d.ts index 61953fe148..bf7fa8e6b6 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.4 +// Type definitions for D3JS d3 standard bundle 4.5 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From bee5105c4dfeba76339422fcc45cec70f5fdc2b5 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Mon, 30 Jan 2017 12:22:25 +0900 Subject: [PATCH 72/85] Remove react-router from tests and create browserHistory manually --- react-router-redux/react-router-redux-tests.ts | 3 ++- react-router-redux/v3/react-router-redux-tests.ts | 3 ++- react-router-redux/v3/tsconfig.json | 1 - 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/react-router-redux/react-router-redux-tests.ts b/react-router-redux/react-router-redux-tests.ts index 87b99b2a69..bcf4eaaed1 100644 --- a/react-router-redux/react-router-redux-tests.ts +++ b/react-router-redux/react-router-redux-tests.ts @@ -1,5 +1,5 @@ import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { browserHistory } from 'react-router'; +import { createBrowserHistory } from 'history'; import { syncHistoryWithStore, routerReducer, @@ -15,6 +15,7 @@ import { const reducer = combineReducers({ routing: routerReducer }); // Apply the middleware to the store +const browserHistory = createBrowserHistory() const middleware = routerMiddleware(browserHistory); const store = createStore( reducer, diff --git a/react-router-redux/v3/react-router-redux-tests.ts b/react-router-redux/v3/react-router-redux-tests.ts index c719fb8459..90d68841ff 100644 --- a/react-router-redux/v3/react-router-redux-tests.ts +++ b/react-router-redux/v3/react-router-redux-tests.ts @@ -1,10 +1,11 @@ import { createStore, combineReducers, applyMiddleware } from 'redux'; -import { browserHistory } from 'react-router'; +import { createBrowserHistory } from 'history'; import { syncHistory, routeReducer } from 'react-router-redux'; const reducer = combineReducers({ routing: routeReducer }); // Sync dispatched route actions to the history +const browserHistory = createBrowserHistory() const reduxRouterMiddleware = syncHistory(browserHistory); const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware)(createStore); diff --git a/react-router-redux/v3/tsconfig.json b/react-router-redux/v3/tsconfig.json index 240e09923e..ee406e1759 100644 --- a/react-router-redux/v3/tsconfig.json +++ b/react-router-redux/v3/tsconfig.json @@ -14,7 +14,6 @@ ], "paths": { "history": ["history/v2"], - "react-router": ["react-router/v2"], "react-router-redux": ["react-router-redux/v3"] }, "types": [], From 9e4ef164d66f9812afad77931136fc1abe18d742 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Mon, 30 Jan 2017 13:03:12 +0900 Subject: [PATCH 73/85] Fix react-router-redux v3 typings, add path mapping to redux-router --- react-router-redux/v3/index.d.ts | 58 ++++++++++++++++---------------- redux-router/tsconfig.json | 3 +- 2 files changed, 31 insertions(+), 30 deletions(-) diff --git a/react-router-redux/v3/index.d.ts b/react-router-redux/v3/index.d.ts index 90e884a221..105d081f30 100644 --- a/react-router-redux/v3/index.d.ts +++ b/react-router-redux/v3/index.d.ts @@ -7,38 +7,38 @@ import * as Redux from "redux"; import * as History from "history"; -declare namespace ReactRouterRedux { - const TRANSITION: string; - const UPDATE_LOCATION: string; - const push: PushAction; - const replace: ReplaceAction; - const go: GoAction; - const goBack: GoForwardAction; - const goForward: GoBackAction; - const routeActions: RouteActions; +export const TRANSITION: string; +export const UPDATE_LOCATION: string; - type LocationDescriptor = History.LocationDescriptor; - type PushAction = (nextLocation: LocationDescriptor) => void; - type ReplaceAction = (nextLocation: LocationDescriptor) => void; - type GoAction = (n: number) => void; - type GoForwardAction = () => void; - type GoBackAction = () => void; +export const push: PushAction; +export const replace: ReplaceAction; +export const go: GoAction; +export const goBack: GoForwardAction; +export const goForward: GoBackAction; +export const routeActions: RouteActions; - interface RouteActions { - push: PushAction; - replace: ReplaceAction; - go: GoAction; - goForward: GoForwardAction; - goBack: GoBackAction; - } - interface HistoryMiddleware extends Redux.Middleware { - listenForReplays(store: Redux.Store, selectLocationState?: Function): void; - unsubscribe(): void; - } +export type LocationDescriptor = History.LocationDescriptor; +export type PushAction = (nextLocation: LocationDescriptor) => void; +export type ReplaceAction = (nextLocation: LocationDescriptor) => void; +export type GoAction = (n: number) => void; +export type GoForwardAction = () => void; +export type GoBackAction = () => void; - function routeReducer(state?: any, options?: any): Redux.Reducer; - function syncHistory(history: History.History): HistoryMiddleware; +export interface RouteActions { + push: PushAction; + replace: ReplaceAction; + go: GoAction; + goForward: GoForwardAction; + goBack: GoBackAction; } -export = ReactRouterRedux; +export interface HistoryMiddleware extends Redux.Middleware { + listenForReplays(store: Redux.Store, selectLocationState?: Function): void; + unsubscribe(): void; +} + +export function routeReducer(state?: any, options?: any): Redux.Reducer; +export function syncHistory(history: History.History): HistoryMiddleware; + + diff --git a/redux-router/tsconfig.json b/redux-router/tsconfig.json index 786008c59c..10120c4840 100644 --- a/redux-router/tsconfig.json +++ b/redux-router/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" From 0105edf9c941d293923151ceb802ed824c210c18 Mon Sep 17 00:00:00 2001 From: Rodrigo Pimentel Date: Mon, 30 Jan 2017 12:18:20 -0500 Subject: [PATCH 74/85] Add generic types for results and collections now we can simply do something like: ``` const model = DB.objects("UserContext").sorted("token", true); ``` And expect the model to be of the union of types`IUserContext & Realm.Object` --- realm/index.d.ts | 74 ++++++++++++++++++++++++------------------------ 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/realm/index.d.ts b/realm/index.d.ts index ad77dc5598..d5a2b770e0 100644 --- a/realm/index.d.ts +++ b/realm/index.d.ts @@ -94,7 +94,7 @@ declare namespace Realm { * Collection * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Collection.html } */ - export interface Collection { + export interface Collection { readonly length: number; /** @@ -107,24 +107,24 @@ declare namespace Realm { * @param {any[]} ...arg * @returns Results */ - filtered(query: string, ...arg: any[]): Results; + filtered(query: string, ...arg: any[]): Results; /** * @param {string|SortDescriptor} descriptor * @param {boolean} reverse? * @returns Results */ - sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; + sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; /** - * @returns Iterator + * @returns Iterator */ - [Symbol.iterator](): Iterator; + [Symbol.iterator](): Iterator; /** * @returns Results */ - snapshot(): Results; + snapshot(): Results; /** * @returns Iterator @@ -150,65 +150,65 @@ declare namespace Realm { /** * @param {number} start? * @param {number} end? - * @returns Object + * @returns T[] | Object[] */ - slice(start?: number, end?: number): Object[]; + slice(start?: number, end?: number): (T & Object)[]; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? * @returns Object|void */ - find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): Object | void; + find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): (T & Object) | void; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? * @returns number */ - findIndex(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): number; + findIndex(callback: (object: any, index?: number, collection?: any) => void, thisArg?: any): number; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T|any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns void */ - forEach(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): void; + forEach(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): void; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:T|any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - every(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + every(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns boolean */ - some(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): boolean; + some(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): boolean; /** - * @param {(object:any,index?:any,collection?:any)=>void} callback + * @param {(object:any,index?:number,collection?:any)=>void} callback * @param {any} thisArg? * @returns any */ - map(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): any[]; + map(callback: (object: T, index?: number, collection?: any) => void, thisArg?: any): any[]; + + /** + * @param {(previousValue:T|any,object?:any,index?:number,collection?:any)=>void} callback + * @param {any} initialValue? + * @returns any + */ + reduce(callback: (previousValue: T, object?: T, index?: number, collection?: any) => void, initialValue?: any): any; /** * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback * @param {any} initialValue? * @returns any */ - reduce(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; - - /** - * @param {(previousValue:any,object?:any,index?:any,collection?:any)=>void} callback - * @param {any} initialValue? - * @returns any - */ - reduceRight(callback: (previousValue: any, object?: any, index?: any, collection?: any) => void, initialValue?: any): any; + reduceRight(callback: (previousValue: T, object?: T, index?: any, collection?: any) => void, initialValue?: any): any; } /** @@ -226,22 +226,22 @@ declare namespace Realm { * List * @see { @link https://realm.io/docs/react-native/latest/api/Realm.List.html } */ - export interface List extends Collection { + export interface List extends Collection { /** * @returns Object|void */ - pop(): Object | void; + pop(): (T & Object) | void; /** * @param {any} object * @returns number */ - push(object: any): number; + push(object: T): number; /** * @returns Object|void */ - shift(): Object | void; + shift(): (T & Object) | void; /** * @param {number} index @@ -249,20 +249,20 @@ declare namespace Realm { * @param {any} object? * @returns Object */ - splice(index: number, count?: number, object?: any): Object[]; + splice(index: number, count?: number, object?: any): (T & Object)[]; /** * @param {any} object * @returns number */ - unshift(object: any): number; + unshift(object: T): number; } /** * Results * @see { @link https://realm.io/docs/react-native/latest/api/Realm.Results.html } */ - export interface Results extends Collection {} + export type Results = Collection; } declare class Realm { @@ -297,13 +297,13 @@ declare class Realm { * @param {boolean} update? * @returns Realm.Object|T|any */ - create(type: string | Realm.ObjectType, properties: Realm.ObjectPropsType, update?: boolean): Realm.Object | T | any; + create(type: string | Realm.ObjectType, properties: Realm.ObjectPropsType, update?: boolean): T & Object; /** * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results|any} object * @returns void */ - delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; + delete(object: Realm.Object | Realm.Object[] | Realm.List | Realm.Results | any): void; /** * @returns void @@ -315,13 +315,13 @@ declare class Realm { * @param {number|string} key * @returns Realm.Object|void */ - objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): Realm.Object | void; + objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): (T & Object) | void; /** * @param {string|Realm.ObjectType} type * @returns Realm.Results */ - objects(type: string | Realm.ObjectType): Realm.Results; + objects(type: string | Realm.ObjectType): Realm.ObjectType & Realm.Results; /** * @param {string} name From 16e6ab0e7d33a2e8056c9af8d266952d89c3249f Mon Sep 17 00:00:00 2001 From: Niklas Mollenhauer Date: Mon, 30 Jan 2017 20:00:48 +0100 Subject: [PATCH 75/85] Remove spaces --- needle/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/needle/index.d.ts b/needle/index.d.ts index f7e3bc275c..8cc61f2a2f 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -106,8 +106,8 @@ declare module "needle" { patch(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; patch(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; - delete(url: string, data: BodyData, callback ?: NeedleCallback): ReadableStream; - delete(url: string, data: BodyData, options ?: NeedleOptions, callback ?: NeedleCallback): ReadableStream; + delete(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; + delete(url: string, data: BodyData, options?: NeedleOptions, callback ?: NeedleCallback): ReadableStream; request(method: string, url: string, data: BodyData, callback?: NeedleCallback): ReadableStream; request(method: string, url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream; From 6c13ebd4c567f2d0cce8fdb22ba6ef73254b03e6 Mon Sep 17 00:00:00 2001 From: Rodrigo Pimentel Date: Mon, 30 Jan 2017 16:27:11 -0500 Subject: [PATCH 76/85] explicit Realm.Object for intersection plus version bump and lint --- realm/index.d.ts | 26 +++++++++++++------------- realm/tslint.json | 2 ++ 2 files changed, 15 insertions(+), 13 deletions(-) create mode 100644 realm/tslint.json diff --git a/realm/index.d.ts b/realm/index.d.ts index d5a2b770e0..034d9e390f 100644 --- a/realm/index.d.ts +++ b/realm/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for realm-js 0.14.3 +// Type definitions for realm-js 0.14 // Project: https://github.com/realm/realm-js // Definitions by: Akim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -107,24 +107,24 @@ declare namespace Realm { * @param {any[]} ...arg * @returns Results */ - filtered(query: string, ...arg: any[]): Results; + filtered(query: string, ...arg: any[]): Results; /** * @param {string|SortDescriptor} descriptor * @param {boolean} reverse? * @returns Results */ - sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; - + sorted(descriptor: string | SortDescriptor, reverse?: boolean): Results; + /** * @returns Iterator */ - [Symbol.iterator](): Iterator; + [Symbol.iterator](): Iterator; /** * @returns Results */ - snapshot(): Results; + snapshot(): Results; /** * @returns Iterator @@ -152,14 +152,14 @@ declare namespace Realm { * @param {number} end? * @returns T[] | Object[] */ - slice(start?: number, end?: number): (T & Object)[]; + slice(start?: number, end?: number): T[]; /** * @param {(object:any,index?:any,collection?:any)=>void} callback * @param {any} thisArg? * @returns Object|void */ - find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): (T & Object) | void; + find(callback: (object: any, index?: any, collection?: any) => void, thisArg?: any): T | null | undefined; /** * @param {(object:any,index?:any,collection?:any)=>void} callback @@ -230,7 +230,7 @@ declare namespace Realm { /** * @returns Object|void */ - pop(): (T & Object) | void; + pop(): T | null | undefined; /** * @param {any} object @@ -241,7 +241,7 @@ declare namespace Realm { /** * @returns Object|void */ - shift(): (T & Object) | void; + shift(): T | null | undefined; /** * @param {number} index @@ -249,7 +249,7 @@ declare namespace Realm { * @param {any} object? * @returns Object */ - splice(index: number, count?: number, object?: any): (T & Object)[]; + splice(index: number, count?: number, object?: any): T[]; /** * @param {any} object @@ -297,7 +297,7 @@ declare class Realm { * @param {boolean} update? * @returns Realm.Object|T|any */ - create(type: string | Realm.ObjectType, properties: Realm.ObjectPropsType, update?: boolean): T & Object; + create(type: string | Realm.ObjectType, properties: T & Realm.ObjectPropsType, update?: boolean): T; /** * @param {Realm.Object|Realm.Object[]|Realm.List|Realm.Results|any} object @@ -315,7 +315,7 @@ declare class Realm { * @param {number|string} key * @returns Realm.Object|void */ - objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): (T & Object) | void; + objectForPrimaryKey(type: string | Realm.ObjectType, key: number | string): T | void; /** * @param {string|Realm.ObjectType} type diff --git a/realm/tslint.json b/realm/tslint.json new file mode 100644 index 0000000000..ccdb64abf2 --- /dev/null +++ b/realm/tslint.json @@ -0,0 +1,2 @@ +{ "extends": "../tslint.json" } + From 4750cce5220c94b7ca3ed2c85636f5386cff3690 Mon Sep 17 00:00:00 2001 From: denis Date: Tue, 31 Jan 2017 12:31:18 +0100 Subject: [PATCH 77/85] Changes according to repo owner Truncate version number Add author name --- metismenu/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index 1816090f87..7b8a8eca19 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for metisMenu 2.6.1 +// Type definitions for metisMenu 2.6 // Project: http://github.com/onokumus/metisMenu -// Definitions by: onokums +// Definitions by: onokums , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From e56981db5b421bf383e28554ade722901d5a72cf Mon Sep 17 00:00:00 2001 From: Andrew Zheng Date: Wed, 1 Feb 2017 15:56:56 -0800 Subject: [PATCH 78/85] Update comment, fix typo --- angular-mocks/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index 767eb65f04..8b94fab445 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -132,7 +132,7 @@ declare module 'angular' { /** * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. - * @param digest Do digest before checking expectation. Pass anything expect false to trigger digest. + * @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code. */ verifyNoOutstandingExpectation(digest?: boolean): void; From 350f4ef001a722315ed4d6cc354bb9a8d7f05605 Mon Sep 17 00:00:00 2001 From: denis Date: Thu, 2 Feb 2017 17:04:55 +0100 Subject: [PATCH 79/85] Remove double tap property The property `doubleTapToGo` was deprecated and is gone in 2.6.2. As 2.6.2 is not backward compatible with previous versions, I set back exact version number in header. --- metismenu/index.d.ts | 3 +-- metismenu/metismenu-tests.ts | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index 7b8a8eca19..bdd500041f 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for metisMenu 2.6 +// Type definitions for metisMenu 2.6.2 // Project: http://github.com/onokumus/metisMenu // Definitions by: onokums , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,6 @@ interface MetisMenuOptions { toggle?: boolean; - doubleTapToGo?: boolean; activeClass?: string; collapseClass?: string; collapseInClass?: string; diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index 625a4877ab..eb17270021 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -6,7 +6,6 @@ $('.metismenu').metisMenu({toggle: false}); $('.test').metisMenu({ toggle: false, - doubleTapToGo: true, activeClass: 'active', collapseClass: 'collapse', collapseInClass: 'in', From fb82c5984fb42b460918be03c3aa2e0d765803be Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 3 Feb 2017 09:05:37 +0900 Subject: [PATCH 80/85] Add another signature to match() --- react-router/lib/match.d.ts | 14 +++++++++++--- react-router/react-router-tests.tsx | 6 +++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index bc5af4fda8..407bcc80c2 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -3,14 +3,22 @@ import { Basename, LocationDescriptor, ParseQueryString, RouteConfig, StringifyQ interface MatchArgs { routes: RouteConfig; - location: LocationDescriptor; - history?: History; basename?: Basename; parseQueryString?: ParseQueryString; stringifyQuery?: StringifyQuery; } +interface MatchLocationArgs extends MatchArgs { + location: LocationDescriptor; + history?: History; +} + +interface MatchHistoryArgs extends MatchArgs { + location?: LocationDescriptor; + history: History; +} + export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; -export default function match(args: MatchArgs, cb: MatchCallback): void; +export default function match(args: MatchLocationArgs | MatchHistoryArgs, cb: MatchCallback): void; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index dda05ef9d8..894dfec8c7 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -123,7 +123,11 @@ const routes = (
); -match({history, routes, location: "baseurl"}, (error, redirectLocation, renderProps) => { +match({ routes, location: "baseurl" }, (error, redirectLocation, renderProps) => { + renderToString(); +}); + +match({ history, routes }, (error, redirectLocation, renderProps) => { renderToString(); }); From 352ee03af80d903738241bb89422e7ece88212e0 Mon Sep 17 00:00:00 2001 From: Yaroslav Serhieiev Date: Fri, 3 Feb 2017 19:27:14 +0200 Subject: [PATCH 81/85] angular: made type inference more accurate for ng.IPromise and ng.IQService --- angular/angular-tests.ts | 178 +++++++++++++++++++++++++++++---------- angular/index.d.ts | 19 +++-- 2 files changed, 149 insertions(+), 48 deletions(-) diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 1a4841ab8c..cca4dfc420 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -271,18 +271,28 @@ angular.module('qprovider-test', []) let foo: ng.IPromise; foo.then((x) => { // x is inferred to be a number + x.toFixed(); return 'asdf'; }).then((x) => { // x is inferred to be string const len = x.length; return 123; +}, (e) => { + return anyOf2([123], toPromise([123])); // IPromise | T, both are good for the 2nd arg of .then() }).then((x) => { - // x is infered to be a number - const fixed = x.toFixed(); + // x is infered to be a number or number[] + if (Array.isArray(x)) { + x[0].toFixed(); + } else { + x.toFixed(); + } return; -}).then((x) => { - // x is infered to be void - // Typescript will prevent you to actually use x as a local variable +}).catch(e => { + return foo || 123; // IPromise | T, both are good for .catch() +}).then(x => { + // x is infered to be void | number + x && x.toFixed(); + // Typescript will prevent you to actually use x as a local variable before you check it is not void // Try object: return { a: 123 }; }).then((x) => { @@ -290,7 +300,8 @@ foo.then((x) => { x.a = 123; //Try a promise var y: ng.IPromise; - return y; + var condition: boolean; + return condition ? y : x.a; // IPromise | T, both are good for the 1st arg of .then() }).then((x) => { // x is infered to be a number, which is the resolved value of a promise x.toFixed(); @@ -307,14 +318,22 @@ namespace TestQ { e: number; f: boolean; } + interface TOther { + g: string; + h: number; + } var tResult: TResult; var promiseTResult: angular.IPromise; var tValue: TValue; var promiseTValue: angular.IPromise; + var tOther: TOther; + var promiseTOther: angular.IPromise; var $q: angular.IQService; var promiseAny: angular.IPromise; + const assertPromiseType = (arg: angular.IPromise) => arg; + // $q constructor { let result: angular.IPromise; @@ -349,13 +368,20 @@ namespace TestQ { { let result: angular.IDeferred; result = $q.defer(); + result.resolve(tResult); + var anyValue: any; + result.reject(anyValue); + result.promise.then(result => { + return $q.resolve(result); + }); } // $q.reject { - let result: angular.IPromise; + let result: angular.IPromise; result = $q.reject(); result = $q.reject(''); + result.catch(() => 5).then(x => x.toFixed()); } // $q.resolve @@ -367,6 +393,8 @@ namespace TestQ { let result: angular.IPromise; result = $q.resolve(tResult); result = $q.resolve(promiseTResult); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + result = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); } // $q.when @@ -376,6 +404,8 @@ namespace TestQ { } { let result: angular.IPromise; + let resultOther: angular.IPromise; + result = $q.when(tResult); result = $q.when(promiseTResult); @@ -384,16 +414,20 @@ namespace TestQ { result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => tResult); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); result = $q.when(promiseTValue, (result: TValue) => promiseTResult); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); + result = resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); } } @@ -466,20 +500,26 @@ namespace TestInjector { // Promise signature tests namespace TestPromise { - let result: any; var any: any; interface TResult { + kind: 'result'; a: number; b: string; c: boolean; } + interface TOther { + kind: 'other'; d: number; e: string; f: boolean; } + function isTResult(x: TResult | TOther): x is TResult { + return x.kind === 'result'; + } + var tresult: TResult; var tresultPromise: ng.IPromise; var tresultHttpPromise: ng.IHttpPromise; @@ -489,45 +529,83 @@ namespace TestPromise { var totherHttpPromise: ng.IHttpPromise; var promise: angular.IPromise; + var $q: angular.IQService; + + const assertPromiseType = (arg: angular.IPromise) => arg; + const reject = $q.reject(); // promise.then - result = promise.then((result) => any) as angular.IPromise; - result = promise.then((result) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => any, (any) => any, (any) => any) as angular.IPromise; + assertPromiseType(promise.then((result) => any)); + assertPromiseType(promise.then((result) => any, (any) => any)); + assertPromiseType(promise.then((result) => any, (any) => any, (any) => any)); - result = promise.then((result) => result) as angular.IPromise; - result = promise.then((result) => result, (any) => any) as angular.IPromise; - result = promise.then((result) => result, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultPromise) as angular.IPromise; - result = promise.then((result) => tresultPromise, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultPromise, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => tresultHttpPromise) as angular.IPromise>; - result = promise.then((result) => tresultHttpPromise, (any) => any) as angular.IPromise>; - result = promise.then((result) => tresultHttpPromise, (any) => any, (any) => any) as angular.IPromise>; + assertPromiseType(promise.then((result) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject)); + assertPromiseType(promise.then((result) => reject, (any) => reject, (any) => any)); - result = promise.then((result) => tother) as angular.IPromise; - result = promise.then((result) => tother, (any) => any) as angular.IPromise; - result = promise.then((result) => tother, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => totherPromise) as angular.IPromise; - result = promise.then((result) => totherPromise, (any) => any) as angular.IPromise; - result = promise.then((result) => totherPromise, (any) => any, (any) => any) as angular.IPromise; - result = promise.then((result) => totherHttpPromise) as angular.IPromise>; - result = promise.then((result) => totherHttpPromise, (any) => any) as angular.IPromise>; - result = promise.then((result) => totherHttpPromise, (any) => any, (any) => any) as angular.IPromise>; + assertPromiseType(promise.then((result) => result)); + assertPromiseType(promise.then((result) => tresult)); + assertPromiseType(promise.then((result) => tresultPromise)); + assertPromiseType(promise.then((result) => result, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => result, (any) => reject, (any) => any)); + + assertPromiseType(promise.then((result) => anyOf2(reject, result))); + assertPromiseType(promise.then((result) => anyOf3(result, tresultPromise, reject))); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, tresultPromise), + (reason) => anyOf3(reject, tresult, tresultPromise) + )); + + + assertPromiseType>(promise.then((result) => tresultHttpPromise)); + + assertPromiseType(promise.then((result) => result, (any) => tother)); + assertPromiseType(promise.then( + (result) => anyOf3(reject, result, totherPromise), + (reason) => anyOf3(reject, tother, tresultPromise) + )); + + assertPromiseType(promise.then( + (result) => anyOf3(tresultPromise, result, totherPromise) + )); + + assertPromiseType(promise.then((result) => result, (any) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise)); + assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); + + assertPromiseType(promise.then((result) => tother)); + assertPromiseType(promise.then((result) => tother, (any) => any)); + assertPromiseType(promise.then((result) => tother, (any) => any, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any)); + assertPromiseType(promise.then((result) => totherPromise, (any) => any, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); + + assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.catch - result = promise.catch((err) => any) as angular.IPromise; - result = promise.catch((err) => tresult) as angular.IPromise; - result = promise.catch((err) => tresultPromise) as angular.IPromise; - result = promise.catch((err) => tresultHttpPromise) as angular.IPromise>; - result = promise.catch((err) => tother) as angular.IPromise; - result = promise.catch((err) => totherPromise) as angular.IPromise; - result = promise.catch((err) => totherHttpPromise) as angular.IPromise>; + assertPromiseType(promise.catch((err) => err)); + assertPromiseType(promise.catch((err) => any)); + assertPromiseType(promise.catch((err) => tresult)); + assertPromiseType(promise.catch((err) => anyOf2(tresult, reject))); + assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); + assertPromiseType(promise.catch((err) => tresultPromise)); + assertPromiseType>(promise.catch((err) => tresultHttpPromise)); + assertPromiseType(promise.catch((err) => tother)); + assertPromiseType(promise.catch((err) => totherPromise)); + assertPromiseType>(promise.catch((err) => totherHttpPromise)); + + assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); // promise.finally - result = promise.finally(() => any) as angular.IPromise; - result = promise.finally(() => tresult) as angular.IPromise; - result = promise.finally(() => tother) as angular.IPromise; + assertPromiseType(promise.finally(() => any)); + assertPromiseType(promise.finally(() => tresult)); + assertPromiseType(promise.finally(() => tother)); } function test_angular_forEach() { @@ -1212,3 +1290,17 @@ function testIHttpParamSerializerJQLikeProvider() { a: 'b' }); } + +function anyOf2(v1: T1, v2: T2) { + return Math.random() < 1/2 ? v1 : v2; +} + +function anyOf3(v1: T1, v2: T2, v3: T3) { + const rnd = Math.random(); + return rnd < 1/3 ? v1 : rnd < 2/3 ? v2 : v3; +} + +function toPromise(val: T): ng.IPromise { + var p: ng.IPromise; + return p; +} diff --git a/angular/index.d.ts b/angular/index.d.ts index 3f094f3185..73535e9922 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1044,13 +1044,14 @@ declare namespace angular { * * @param reason Constant, message, exception or an object representing the rejection reason. */ - reject(reason?: any): IPromise; + reject(reason?: any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. * * @param value Value or a promise */ resolve(value: IPromise|T): IPromise; + resolve(value: IPromise|T2): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. */ @@ -1061,7 +1062,10 @@ declare namespace angular { * @param value Value or a promise */ when(value: IPromise|T): IPromise; - when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise|T2): IPromise; + when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult): IPromise; + when(value: T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: null | undefined | ((reason: any) => any), notifyCallback?: (state: any) => any): IPromise; + when(value: IPromise, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => TResult2 | IPromise, notifyCallback?: (state: any) => any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. */ @@ -1090,15 +1094,20 @@ declare namespace angular { interface IPromise { /** * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * The successCallBack may return IPromise for when a $q.reject() needs to be returned * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. */ - then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback?: null | undefined, notifyCallback?: (state: any) => any): IPromise; + + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => IPromise|TCatch, notifyCallback?: (state: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback: (reason: any) => IPromise|TCatch2, notifyCallback?: (state: any) => any): IPromise; /** * Shorthand for promise.then(null, errorCallback) */ - catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch): IPromise; + catch(onRejected: (reason: any) => IPromise|TCatch2): IPromise; /** * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. From 4908d6bad56ffcd03f93df1a2bced3f06052b272 Mon Sep 17 00:00:00 2001 From: Matt Bailey Date: Fri, 3 Feb 2017 15:00:02 -0800 Subject: [PATCH 82/85] Updated definitions with checkForm() function on Validator prototype --- jquery.validation/index.d.ts | 1 + jquery.validation/jquery.validation-tests.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/jquery.validation/index.d.ts b/jquery.validation/index.d.ts index 953755a065..2bb690c07e 100644 --- a/jquery.validation/index.d.ts +++ b/jquery.validation/index.d.ts @@ -217,6 +217,7 @@ declare namespace JQueryValidation interface Validator { element(element: string|JQuery): boolean; + checkForm(): boolean; /** * Validates the form, returns true if it is valid, false otherwise. */ diff --git a/jquery.validation/jquery.validation-tests.ts b/jquery.validation/jquery.validation-tests.ts index 15bb9f790c..0b2de520f2 100644 --- a/jquery.validation/jquery.validation-tests.ts +++ b/jquery.validation/jquery.validation-tests.ts @@ -208,6 +208,7 @@ function test_methods() { $("#myform").submit(); $("#myinput").attr(rules); }); + $("#myform").validate().checkForm(); $("#myform").validate().form(); $("#myform").validate().element("#myselect"); $("#myform").validate().element($("#myselect")); From cc903d2865dec7a3b9a148ceeb9a9090f828db72 Mon Sep 17 00:00:00 2001 From: Bowden Kelly Date: Fri, 3 Feb 2017 17:47:14 -0800 Subject: [PATCH 83/85] Update index.d.ts --- roslib/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roslib/index.d.ts b/roslib/index.d.ts index 14fe2c1e3e..991585d803 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for roslib.js +// Type definitions for roslib.js 1.9 // Project: http://wiki.ros.org/roslibjs // Definitions by: Stefan Profanter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 04dcec1c303f31c7ca825b898a9e7d5c7149b640 Mon Sep 17 00:00:00 2001 From: Bowden Kelly Date: Fri, 3 Feb 2017 18:18:22 -0800 Subject: [PATCH 84/85] Update index.d.ts --- cron/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cron/index.d.ts b/cron/index.d.ts index 79a5b96a01..d4fa027c93 100644 --- a/cron/index.d.ts +++ b/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.2.1 +// Type definitions for cron 1.2 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 7eec158cd5956142788d1f89b65d48eb245e92b4 Mon Sep 17 00:00:00 2001 From: Bowden Kelly Date: Fri, 3 Feb 2017 18:39:05 -0800 Subject: [PATCH 85/85] Update index.d.ts --- metismenu/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index bdd500041f..8117328bf8 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for metisMenu 2.6.2 +// Type definitions for metisMenu 2.6 // Project: http://github.com/onokumus/metisMenu // Definitions by: onokums , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped