From a48a91ccfe9e2608620f78ff79fa32d581849311 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Tue, 3 May 2016 18:47:44 +0000 Subject: [PATCH 01/13] modified compiler options --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f61bd31..48a96f5 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ }, "scripts": { "clean": "rimraf lib dist build", - "ts": "tsc --module commonjs -t ES5 --out typings/rest-io/rest-io.ts --p . --declaration", + "ts": "tsc --module commonjs -t ES5 --outDir lib", "ts-watch": "tsc --module commonjs -t ES5 --outDir lib -p . -w", "test": "mocha lib/test/**/*.spec.js -R mocha-better-spec-reporter", "test-watch": "watch \"npm run test\" lib/", From 59f780d58a9e3d09e01e7937acef8dc775548066 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Tue, 3 May 2016 18:51:34 +0000 Subject: [PATCH 02/13] changed from tsd to typings --- tsconfig.json | 2 +- tsd.json | 39 - typings.json | 18 + typings/browser.d.ts | 12 + .../ambient/body-parser/index.d.ts} | 3 +- .../ambient/chai/index.d.ts} | 4 +- .../ambient/express/index.d.ts} | 5 +- .../ambient/mocha/index.d.ts} | 4 +- .../ambient/mongoose/index.d.ts} | 6 +- .../ambient/node/index.d.ts} | 1401 ++++++++-- .../ambient/pluralize/index.d.ts} | 2 + .../ambient/sinon-chai/index.d.ts} | 6 +- .../ambient/sinon/index.d.ts} | 4 +- .../ambient/superagent/index.d.ts} | 16 +- .../ambient/supertest/index.d.ts} | 5 +- typings/main.d.ts | 12 + typings/main/ambient/body-parser/index.d.ts | 139 + typings/main/ambient/chai/index.d.ts | 310 +++ typings/main/ambient/express/index.d.ts | 1099 ++++++++ typings/main/ambient/mocha/index.d.ts | 168 ++ typings/main/ambient/mongoose/index.d.ts | 461 ++++ typings/main/ambient/node/index.d.ts | 2377 +++++++++++++++++ typings/main/ambient/pluralize/index.d.ts | 67 + typings/main/ambient/sinon-chai/index.d.ts | 84 + typings/main/ambient/sinon/index.d.ts | 422 +++ typings/main/ambient/superagent/index.d.ts | 116 + typings/main/ambient/supertest/index.d.ts | 40 + typings/tsd.d.ts | 12 - typings/{yadda => }/yadda.d.ts | 0 29 files changed, 6491 insertions(+), 343 deletions(-) delete mode 100644 tsd.json create mode 100644 typings.json create mode 100644 typings/browser.d.ts rename typings/{body-parser/body-parser.d.ts => browser/ambient/body-parser/index.d.ts} (96%) rename typings/{chai/chai.d.ts => browser/ambient/chai/index.d.ts} (98%) rename typings/{express/express.d.ts => browser/ambient/express/index.d.ts} (99%) rename typings/{mocha/mocha.d.ts => browser/ambient/mocha/index.d.ts} (96%) rename typings/{mongoose/mongoose.d.ts => browser/ambient/mongoose/index.d.ts} (99%) rename typings/{node/node.d.ts => browser/ambient/node/index.d.ts} (53%) rename typings/{pluralize/pluralize.d.ts => browser/ambient/pluralize/index.d.ts} (89%) rename typings/{sinon-chai/sinon-chai.d.ts => browser/ambient/sinon-chai/index.d.ts} (94%) rename typings/{sinon/sinon.d.ts => browser/ambient/sinon/index.d.ts} (98%) rename typings/{superagent/superagent.d.ts => browser/ambient/superagent/index.d.ts} (90%) rename typings/{supertest/supertest.d.ts => browser/ambient/supertest/index.d.ts} (88%) create mode 100644 typings/main.d.ts create mode 100644 typings/main/ambient/body-parser/index.d.ts create mode 100644 typings/main/ambient/chai/index.d.ts create mode 100644 typings/main/ambient/express/index.d.ts create mode 100644 typings/main/ambient/mocha/index.d.ts create mode 100644 typings/main/ambient/mongoose/index.d.ts create mode 100644 typings/main/ambient/node/index.d.ts create mode 100644 typings/main/ambient/pluralize/index.d.ts create mode 100644 typings/main/ambient/sinon-chai/index.d.ts create mode 100644 typings/main/ambient/sinon/index.d.ts create mode 100644 typings/main/ambient/superagent/index.d.ts create mode 100644 typings/main/ambient/supertest/index.d.ts delete mode 100644 typings/tsd.d.ts rename typings/{yadda => }/yadda.d.ts (100%) diff --git a/tsconfig.json b/tsconfig.json index b69d1c5..a185bc7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,7 +18,7 @@ ], "files": [ "definitions/rest-io.d.ts", - "typings/tsd.d.ts", + "typings/main.d.ts", "examples/authentication/app.ts", "examples/authentication/resources/parent.ts", "examples/authentication/resources/sub.ts", diff --git a/tsd.json b/tsd.json deleted file mode 100644 index 518445c..0000000 --- a/tsd.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "version": "v4", - "repo": "borisyankov/DefinitelyTyped", - "ref": "master", - "path": "typings", - "bundle": "typings/tsd.d.ts", - "installed": { - "mongoose/mongoose.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "node/node.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "express/express.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "body-parser/body-parser.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "chai/chai.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "mocha/mocha.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "sinon-chai/sinon-chai.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "sinon/sinon.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "supertest/supertest.d.ts": { - "commit": "8c7444882a2bc2ab87387f8f736a7d97e89b9c90" - }, - "pluralize/pluralize.d.ts": { - "commit": "101a5daef4fc42eca0d447ba5d080248f80daf90" - } - } -} diff --git a/typings.json b/typings.json new file mode 100644 index 0000000..c758bc1 --- /dev/null +++ b/typings.json @@ -0,0 +1,18 @@ +{ + "name": "rest-io", + "version": false, + "ambientDependencies": { + "body-parser": "github:DefinitelyTyped/DefinitelyTyped/body-parser/body-parser.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "chai": "github:DefinitelyTyped/DefinitelyTyped/chai/chai.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "crypto-js": "registry:dt/crypto-js#3.1.3+20160317120654", + "express": "github:DefinitelyTyped/DefinitelyTyped/express/express.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "mocha": "github:DefinitelyTyped/DefinitelyTyped/mocha/mocha.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "mongoose": "github:DefinitelyTyped/DefinitelyTyped/mongoose/mongoose.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "node": "registry:dt/node#4.0.0+20160501135006", + "pluralize": "github:DefinitelyTyped/DefinitelyTyped/pluralize/pluralize.d.ts#101a5daef4fc42eca0d447ba5d080248f80daf90", + "sinon": "github:DefinitelyTyped/DefinitelyTyped/sinon/sinon.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "sinon-chai": "github:DefinitelyTyped/DefinitelyTyped/sinon-chai/sinon-chai.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90", + "superagent": "registry:dt/superagent#1.4.0+20160317120654", + "supertest": "github:DefinitelyTyped/DefinitelyTyped/supertest/supertest.d.ts#8c7444882a2bc2ab87387f8f736a7d97e89b9c90" + } +} diff --git a/typings/browser.d.ts b/typings/browser.d.ts new file mode 100644 index 0000000..75524d2 --- /dev/null +++ b/typings/browser.d.ts @@ -0,0 +1,12 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/typings/body-parser/body-parser.d.ts b/typings/browser/ambient/body-parser/index.d.ts similarity index 96% rename from typings/body-parser/body-parser.d.ts rename to typings/browser/ambient/body-parser/index.d.ts index 994aa4e..56d3cc2 100644 --- a/typings/body-parser/body-parser.d.ts +++ b/typings/browser/ambient/body-parser/index.d.ts @@ -1,9 +1,10 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/body-parser/body-parser.d.ts // Type definitions for body-parser // Project: http://expressjs.com // Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// declare module "body-parser" { import express = require('express'); diff --git a/typings/chai/chai.d.ts b/typings/browser/ambient/chai/index.d.ts similarity index 98% rename from typings/chai/chai.d.ts rename to typings/browser/ambient/chai/index.d.ts index cb685f3..4ab4d27 100644 --- a/typings/chai/chai.d.ts +++ b/typings/browser/ambient/chai/index.d.ts @@ -1,3 +1,5 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/chai/chai.d.ts // Type definitions for chai 2.0.0 // Project: http://chaijs.com/ // Definitions by: Jed Mao , @@ -305,4 +307,4 @@ declare module "chai" { interface Object { should: Chai.Assertion; -} +} \ No newline at end of file diff --git a/typings/express/express.d.ts b/typings/browser/ambient/express/index.d.ts similarity index 99% rename from typings/express/express.d.ts rename to typings/browser/ambient/express/index.d.ts index 4dd4d3c..a5a0c5b 100644 --- a/typings/express/express.d.ts +++ b/typings/browser/ambient/express/index.d.ts @@ -1,3 +1,5 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/express/express.d.ts // Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov @@ -10,7 +12,6 @@ =============================================== */ -/// declare module Express { @@ -1095,4 +1096,4 @@ declare module "express" { } export = e; -} +} \ No newline at end of file diff --git a/typings/mocha/mocha.d.ts b/typings/browser/ambient/mocha/index.d.ts similarity index 96% rename from typings/mocha/mocha.d.ts rename to typings/browser/ambient/mocha/index.d.ts index 63ad660..c4fdd8d 100644 --- a/typings/mocha/mocha.d.ts +++ b/typings/browser/ambient/mocha/index.d.ts @@ -1,3 +1,5 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mocha/mocha.d.ts // Type definitions for mocha 2.0.1 // Project: http://mochajs.org/ // Definitions by: Kazi Manzur Rashid , otiai10 , jt000 @@ -163,4 +165,4 @@ declare module "mocha" { } export = Mocha; -} +} \ No newline at end of file diff --git a/typings/mongoose/mongoose.d.ts b/typings/browser/ambient/mongoose/index.d.ts similarity index 99% rename from typings/mongoose/mongoose.d.ts rename to typings/browser/ambient/mongoose/index.d.ts index 29e167d..eda050c 100644 --- a/typings/mongoose/mongoose.d.ts +++ b/typings/browser/ambient/mongoose/index.d.ts @@ -1,9 +1,10 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mongoose/mongoose.d.ts // Type definitions for Mongoose 3.8.5 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// declare module "mongoose" { function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; @@ -457,5 +458,4 @@ declare module "mongoose" { error(err: any): Promise; } -} - +} \ No newline at end of file diff --git a/typings/node/node.d.ts b/typings/browser/ambient/node/index.d.ts similarity index 53% rename from typings/node/node.d.ts rename to typings/browser/ambient/node/index.d.ts index 6442160..e9b4c3d 100644 --- a/typings/node/node.d.ts +++ b/typings/browser/ambient/node/index.d.ts @@ -1,14 +1,29 @@ -// Type definitions for Node.js v0.12.0 +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4f479b281cb116de213cc5301f273018c13c7267/node/node.d.ts +// Type definitions for Node.js v4.x // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ * * -* Node.js v0.12.0 API * +* Node.js v4.x API * * * ************************************************/ +interface Error { + stack?: string; +} + + +// 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 {} + /************************************************ * * * GLOBAL * @@ -27,23 +42,30 @@ declare function clearInterval(intervalId: NodeJS.Timer): void; declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; -declare var require: { +interface NodeRequireFunction { (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { resolve(id:string): string; cache: any; extensions: any; main: any; -}; +} -declare var module: { +declare var require: NodeRequire; + +interface NodeModule { exports: any; - require(id: string): any; + require: NodeRequireFunction; id: string; filename: string; loaded: boolean; parent: any; children: any[]; -}; +} + +declare var module: NodeModule; // Same as module.exports declare var exports: any; @@ -60,16 +82,123 @@ declare var SlowBuffer: { // Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; interface Buffer extends NodeBuffer {} + +/** + * 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; - new (size: Uint8Array): 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; - isBuffer(obj: any): boolean; + /** + * 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; }; /************************************************ @@ -77,23 +206,26 @@ declare var Buffer: { * GLOBAL INTERFACES * * * ************************************************/ -declare module NodeJS { +declare namespace NodeJS { export interface ErrnoException extends Error { errno?: number; code?: string; path?: string; syscall?: string; + stack?: string; } export interface EventEmitter { - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): 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; + setMaxListeners(n: number): this; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; } export interface ReadableStream extends EventEmitter { @@ -111,8 +243,7 @@ declare module NodeJS { export interface WritableStream extends EventEmitter { writable: boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; + write(buffer: Buffer|string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; end(buffer: Buffer, cb?: Function): void; @@ -122,11 +253,35 @@ declare module NodeJS { export interface ReadWriteStream extends ReadableStream, WritableStream {} + 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; + + 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 Process extends EventEmitter { stdout: WritableStream; stderr: WritableStream; stdin: ReadableStream; argv: string[]; + execArgv: string[]; execPath: string; abort(): void; chdir(directory: string): void; @@ -175,19 +330,22 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; platform: string; - memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + memoryUsage(): MemoryUsage; nextTick(callback: Function): void; umask(mask?: number): number; uptime(): number; hrtime(time?:number[]): number[]; + domain: Domain; // Worker send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; } export interface Global { @@ -195,6 +353,7 @@ declare module NodeJS { ArrayBuffer: typeof ArrayBuffer; Boolean: typeof Boolean; Buffer: typeof Buffer; + DataView: typeof DataView; Date: typeof Date; Error: typeof Error; EvalError: typeof EvalError; @@ -208,6 +367,7 @@ declare module NodeJS { Int8Array: typeof Int8Array; Intl: typeof Intl; JSON: typeof JSON; + Map: MapConstructor; Math: typeof Math; NaN: typeof NaN; Number: typeof Number; @@ -216,6 +376,7 @@ declare module NodeJS { RangeError: typeof RangeError; ReferenceError: typeof ReferenceError; RegExp: typeof RegExp; + Set: SetConstructor; String: typeof String; Symbol: Function; SyntaxError: typeof SyntaxError; @@ -225,7 +386,8 @@ declare module NodeJS { Uint32Array: typeof Uint32Array; Uint8Array: typeof Uint8Array; Uint8ClampedArray: Function; - WeakSet: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; clearImmediate: (immediateId: any) => void; clearInterval: (intervalId: NodeJS.Timer) => void; clearTimeout: (timeoutId: NodeJS.Timer) => void; @@ -247,8 +409,9 @@ declare module NodeJS { 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; + unescape: (str: string) => string; gc: () => void; + v8debug?: any; } export interface Timer { @@ -260,15 +423,23 @@ declare module NodeJS { /** * @deprecated */ -interface NodeBuffer { - [index: number]: number; +interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; toJSON(): any; - length: number; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; - readUInt8(offset: number, noAsset?: boolean): number; + 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; @@ -282,21 +453,27 @@ interface NodeBuffer { 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): void; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeInt8(value: number, offset: number, noAssert?: boolean): void; - writeInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeFloatLE(value: number, offset: number, noAssert?: boolean): void; - writeFloatBE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; - fill(value: any, offset?: number, end?: number): void; + 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): Buffer; + // TODO: encoding param + indexOf(value: string | number | Buffer, byteOffset?: number): number; + // TODO: entries + // TODO: includes + // TODO: keys + // TODO: values } /************************************************ @@ -306,43 +483,71 @@ interface NodeBuffer { ************************************************/ declare module "buffer" { 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 function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export interface StringifyOptions { + encodeURIComponent?: 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; } declare module "events" { export class EventEmitter implements NodeJS.EventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; - - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: 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; + setMaxListeners(n: number): this; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; - } + listenerCount(type: string): number; + } } declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); - - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; - listen(port: number, hostname?: string, callback?: Function): Server; - listen(path: string, callback?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(cb?: any): Server; - address(): { port: number; family: string; address: string; }; + 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 Server extends events.EventEmitter, net.Server { + setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; + timeout: number; } /** * @deprecated Use IncomingMessage @@ -362,7 +567,9 @@ declare module "http" { writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; writeHead(statusCode: number, headers?: any): void; statusCode: number; - setHeader(name: string, value: string): void; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; sendDate: boolean; getHeader(name: string): string; removeHeader(name: string): void; @@ -390,6 +597,11 @@ declare module "http" { 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; @@ -427,41 +639,43 @@ declare module "http" { */ export interface ClientResponse extends IncomingMessage { } - 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; + 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 STATUS_CODES: { [errorCode: number]: string; @@ -469,14 +683,14 @@ declare module "http" { }; export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + 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 child = require("child_process"); - import events = require("events"); + import * as child from "child_process"; + import * as events from "events"; export interface ClusterSettings { exec?: string; @@ -484,6 +698,12 @@ declare module "cluster" { silent?: boolean; } + export interface Address { + address: string; + port: number; + addressType: string; + } + export class Worker extends events.EventEmitter { id: string; process: child.ChildProcess; @@ -492,6 +712,8 @@ declare module "cluster" { kill(signal?: string): void; destroy(signal?: string): void; disconnect(): void; + isConnected(): boolean; + isDead(): boolean; } export var settings: ClusterSettings; @@ -501,10 +723,19 @@ declare module "cluster" { export function fork(env?: any): Worker; export function disconnect(callback?: Function): void; export var worker: Worker; - export var workers: Worker[]; + export var workers: { + [index: string]: Worker + }; // 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; @@ -515,7 +746,7 @@ declare module "cluster" { } declare module "zlib" { - import stream = require("stream"); + import * as stream from "stream"; export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends stream.Transform { } @@ -535,12 +766,19 @@ declare module "zlib" { export function createUnzip(options?: ZlibOptions): Unzip; export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; // Constants export var Z_NO_FLUSH: number; @@ -577,7 +815,29 @@ declare module "zlib" { } 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 tmpdir(): string; + export function homedir(): string; + export function endianness(): string; export function hostname(): string; export function type(): string; export function platform(): string; @@ -587,15 +847,15 @@ declare module "os" { export function loadavg(): number[]; export function totalmem(): number; export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; export var EOL: string; } declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; export interface ServerOptions { pfx?: any; @@ -612,15 +872,7 @@ declare module "https" { SNICallback?: (servername: string) => any; } - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; + export interface RequestOptions extends http.RequestOptions{ pfx?: any; key?: any; passphrase?: string; @@ -628,6 +880,7 @@ declare module "https" { ca?: any; ciphers?: string; rejectUnauthorized?: boolean; + secureProtocol?: string; } export interface Agent { @@ -652,15 +905,15 @@ declare module "punycode" { export function toASCII(domain: string): string; export var ucs2: ucs2; interface ucs2 { - decode(string: string): string; + decode(string: string): number[]; encode(codePoints: number[]): string; } export var version: any; } declare module "repl" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as events from "events"; export interface ReplOptions { prompt?: string; @@ -677,134 +930,262 @@ declare module "repl" { } declare module "readline" { - import events = require("events"); - import stream = require("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 ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; close(): void; - write(data: any, key?: any): void; + write(data: string|Buffer, key?: Key): void; + } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; } + + export interface CompleterResult { + completions: string[]; + line: string; + } + export interface ReadLineOptions { input: NodeJS.ReadableStream; - output: NodeJS.WritableStream; - completer?: Function; + 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 Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; + 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 events = require("events"); - import stream = require("stream"); + import * as events from "events"; + import * as stream from "stream"; 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): void; disconnect(): void; + unref(): void; } - export function spawn(command: string, args?: string[], options?: { + export interface SpawnOptions { cwd?: string; - stdio?: any; - custom?: any; env?: any; + stdio?: any; detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { cwd?: string; - stdio?: any; - customFds?: any; env?: any; - encoding?: string; + shell?: string; timeout?: number; maxBuffer?: number; killSignal?: string; - }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: { + 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 ExecFileOptions { cwd?: string; - stdio?: any; - customFds?: any; env?: any; - encoding?: string; timeout?: number; - maxBuffer?: string; + maxBuffer?: number; killSignal?: string; - }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { + 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 ForkOptions { cwd?: string; env?: any; - encoding?: string; - }): ChildProcess; - export function execSync(command: string, options?: { + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { cwd?: string; - input?: string|Buffer; + input?: string | Buffer; stdio?: any; env?: any; uid?: number; gid?: number; timeout?: number; - maxBuffer?: number; killSignal?: string; + maxBuffer?: number; encoding?: string; - }): ChildProcess; - export function execFileSync(command: string, args?: string[], options?: { + 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 ExecSyncOptions { cwd?: string; - input?: string|Buffer; + 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?: string; - }): ChildProcess; + } + 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: any; // string | Object - slashes: boolean; - hash?: string; - path?: string; - } - - export interface UrlOptions { + href?: string; protocol?: string; auth?: string; hostname?: string; @@ -812,13 +1193,14 @@ declare module "url" { host?: string; pathname?: string; search?: string; - query?: any; + query?: any; // string | Object + slashes?: boolean; hash?: string; path?: string; } export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: UrlOptions): string; + export function format(url: Url): string; export function resolve(from: string, to: string): string; } @@ -838,7 +1220,7 @@ declare module "dns" { } declare module "net" { - import stream = require("stream"); + import * as stream from "stream"; export interface Socket extends stream.Duplex { // Extended base methods @@ -883,21 +1265,38 @@ declare module "net" { 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 Socket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + 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(handle: any, backlog?: number, listeningListener?: Function): Server; listen(handle: any, listeningListener?: Function): Server; + listen(options: ListenOptions, 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; } export function createServer(connectionListener?: (socket: Socket) =>void ): Server; export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + 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: { allowHalfOpen?: boolean; }, 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; @@ -906,7 +1305,7 @@ declare module "net" { } declare module "dgram" { - import events = require("events"); + import * as events from "events"; interface RemoteInfo { address: string; @@ -936,8 +1335,8 @@ declare module "dgram" { } declare module "fs" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as events from "events"; interface Stats { isFile(): boolean; @@ -960,6 +1359,7 @@ declare module "fs" { atime: Date; mtime: Date; ctime: Date; + birthtime: Date; } interface FSWatcher extends events.EventEmitter { @@ -971,9 +1371,21 @@ declare module "fs" { } export interface WriteStream extends stream.Writable { close(): void; + bytesWritten: number; } + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ export function renameSync(oldPath: string, newPath: string): void; export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; @@ -1013,15 +1425,71 @@ declare module "fs" { export function readlinkSync(path: string): string; export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: {[path: string]: string}): string; + export function realpathSync(path: string, 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. + */ export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ export function unlinkSync(path: string): 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. + */ export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ export function rmdirSync(path: string): 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. + */ export function mkdir(path: string, 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. + */ export function mkdir(path: string, 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. + */ export function mkdir(path: string, 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, 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, mode?: string): void; export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; export function readdirSync(path: string): string[]; @@ -1043,15 +1511,65 @@ declare module "fs" { 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 writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + 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; - export function readFile(filename: 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; @@ -1070,49 +1588,148 @@ declare module "fs" { export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; export function exists(path: string, callback?: (exists: boolean) => void): void; export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, 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, mode ?: number): void; export function createReadStream(path: string, options?: { flags?: string; encoding?: string; - fd?: string; + fd?: number; mode?: number; - bufferSize?: number; - }): ReadStream; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: string; - bufferSize?: number; + autoClose?: boolean; }): ReadStream; export function createWriteStream(path: string, options?: { flags?: string; encoding?: string; - string?: string; + fd?: number; + mode?: number; }): WriteStream; } 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:\' + */ 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: any[]): 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: any[]): string; - export function isAbsolute(p: string): boolean; + /** + * 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 posix { export function normalize(p: string): string; @@ -1156,14 +1773,16 @@ declare module "string_decoder" { } declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("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 interface TlsOptions { + host?: string; + port?: number; pfx?: any; //string or buffer key?: any; //string or buffer passphrase?: string; @@ -1193,12 +1812,6 @@ declare module "tls" { } export interface Server extends net.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - - listen(port: number, host?: string, callback?: Function): Server; close(): Server; address(): { port: number; family: string; address: string; }; addContext(hostName: string, credentials: { @@ -1232,11 +1845,27 @@ declare module "tls" { cleartext: any; } + export interface SecureContextOptions { + pfx?: any; //string | buffer + key?: any; //string | buffer + passphrase?: string; + cert?: any; // string | buffer + ca?: any; // string | buffer + crl?: any; // 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: TlsOptions, 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" { @@ -1254,13 +1883,13 @@ declare module "crypto" { export function createHash(algorithm: string): Hash; export function createHmac(algorithm: string, key: string): Hmac; export function createHmac(algorithm: string, key: Buffer): Hmac; - interface Hash { + export interface Hash { update(data: any, input_encoding?: string): Hash; digest(encoding: 'buffer'): Buffer; digest(encoding: string): any; digest(): Buffer; } - interface Hmac { + export interface Hmac extends NodeJS.ReadWriteStream { update(data: any, input_encoding?: string): Hmac; digest(encoding: 'buffer'): Buffer; digest(encoding: string): any; @@ -1268,35 +1897,41 @@ declare module "crypto" { } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - interface Cipher { + export interface Cipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; + update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; + update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; } export function createDecipher(algorithm: string, password: any): Decipher; export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - interface Decipher { + export interface Decipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; + update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; + update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; } export function createSign(algorithm: string): Signer; - interface Signer { + export interface Signer extends NodeJS.WritableStream { update(data: any): void; sign(private_key: string, output_format: string): string; } export function createVerify(algorith: string): Verify; - interface Verify { + export interface Verify extends NodeJS.WritableStream { update(data: any): void; verify(object: string, signature: string, signature_format?: string): boolean; } export function createDiffieHellman(prime_length: number): DiffieHellman; export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - interface DiffieHellman { + export interface DiffieHellman { generateKeys(encoding?: string): string; computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; getPrime(encoding?: string): string; @@ -1307,18 +1942,31 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + 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) : 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 RsaPublicKey { + key: string; + padding?: any; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: any; + } + export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer } declare module "stream" { - import events = require("events"); + import * as events from "events"; - export interface Stream extends events.EventEmitter { + export class Stream extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } @@ -1332,14 +1980,13 @@ declare module "stream" { readable: boolean; constructor(opts?: ReadableOptions); _read(size: number): void; - read(size?: number): string|Buffer; + read(size?: number): any; setEncoding(encoding: string): void; pause(): void; resume(): void; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; + unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; } @@ -1347,20 +1994,18 @@ declare module "stream" { export interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; + objectMode?: boolean; } export class Writable extends events.EventEmitter implements NodeJS.WritableStream { writable: boolean; constructor(opts?: WritableOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; + _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(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; } export interface DuplexOptions extends ReadableOptions, WritableOptions { @@ -1371,15 +2016,12 @@ declare module "stream" { export class Duplex extends Readable implements NodeJS.ReadWriteStream { writable: boolean; constructor(opts?: DuplexOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; + _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(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; } export interface TransformOptions extends ReadableOptions, WritableOptions {} @@ -1389,8 +2031,7 @@ declare module "stream" { readable: boolean; writable: boolean; constructor(opts?: TransformOptions); - _transform(chunk: Buffer, encoding: string, callback: Function): void; - _transform(chunk: string, encoding: string, callback: Function): void; + _transform(chunk: any, encoding: string, callback: Function): void; _flush(callback: Function): void; read(size?: number): any; setEncoding(encoding: string): void; @@ -1398,17 +2039,14 @@ declare module "stream" { resume(): void; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; + unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, 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; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; } export class PassThrough extends Transform {} @@ -1435,11 +2073,12 @@ declare module "util" { 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; } declare module "assert" { function internal (value: any, message?: string): void; - module internal { + namespace internal { export class AssertionError implements Error { name: string; message: string; @@ -1460,6 +2099,8 @@ declare module "assert" { 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; @@ -1481,36 +2122,256 @@ declare module "assert" { } declare module "tty" { - import net = require("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; } } declare module "domain" { - import events = require("events"); + import * as events from "events"; - export class Domain extends events.EventEmitter { + 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; - - addListener(event: string, listener: Function): Domain; - on(event: string, listener: Function): Domain; - once(event: string, listener: Function): Domain; - removeListener(event: string, listener: Function): Domain; - removeAllListeners(event?: string): 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_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: 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; +} \ No newline at end of file diff --git a/typings/pluralize/pluralize.d.ts b/typings/browser/ambient/pluralize/index.d.ts similarity index 89% rename from typings/pluralize/pluralize.d.ts rename to typings/browser/ambient/pluralize/index.d.ts index 501a96b..43daef9 100644 --- a/typings/pluralize/pluralize.d.ts +++ b/typings/browser/ambient/pluralize/index.d.ts @@ -1,3 +1,5 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/101a5daef4fc42eca0d447ba5d080248f80daf90/pluralize/pluralize.d.ts // Type definitions for pluralize // Project: https://www.npmjs.com/package/pluralize // Definitions by: Syu Kato diff --git a/typings/sinon-chai/sinon-chai.d.ts b/typings/browser/ambient/sinon-chai/index.d.ts similarity index 94% rename from typings/sinon-chai/sinon-chai.d.ts rename to typings/browser/ambient/sinon-chai/index.d.ts index 03bd0e8..0b923d7 100644 --- a/typings/sinon-chai/sinon-chai.d.ts +++ b/typings/browser/ambient/sinon-chai/index.d.ts @@ -1,10 +1,10 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon-chai/sinon-chai.d.ts // Type definitions for sinon-chai 2.7.0 // Project: https://github.com/domenic/sinon-chai // Definitions by: Kazi Manzur Rashid , Jed Mao // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// -/// declare module Chai { @@ -81,4 +81,4 @@ declare module Chai { declare module "sinon-chai" { function sinonChai(chai: any, utils: any): void; export = sinonChai; -} +} \ No newline at end of file diff --git a/typings/sinon/sinon.d.ts b/typings/browser/ambient/sinon/index.d.ts similarity index 98% rename from typings/sinon/sinon.d.ts rename to typings/browser/ambient/sinon/index.d.ts index 6440dda..4b743f9 100644 --- a/typings/sinon/sinon.d.ts +++ b/typings/browser/ambient/sinon/index.d.ts @@ -1,3 +1,5 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon/sinon.d.ts // Type definitions for Sinon 1.8.1 // Project: http://sinonjs.org/ // Definitions by: William Sears @@ -417,4 +419,4 @@ declare var sinon: Sinon.SinonStatic; declare module "sinon" { export = sinon; -} +} \ No newline at end of file diff --git a/typings/superagent/superagent.d.ts b/typings/browser/ambient/superagent/index.d.ts similarity index 90% rename from typings/superagent/superagent.d.ts rename to typings/browser/ambient/superagent/index.d.ts index 6944fcc..485a146 100644 --- a/typings/superagent/superagent.d.ts +++ b/typings/browser/ambient/superagent/index.d.ts @@ -1,18 +1,19 @@ -// Type definitions for SuperAgent 0.15.4 +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/superagent/superagent.d.ts +// Type definitions for SuperAgent v1.4.0 // Project: https://github.com/visionmedia/superagent // Definitions by: Alex Varju -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "superagent" { import stream = require('stream'); - type CallbackHandler = { (err: any, res: request.Response): void; }|{ (res: request.Response): void; }; + type CallbackHandler = (err: any, res: request.Response) => void; var request: request.SuperAgentStatic; - module request { + namespace request { interface SuperAgentStatic extends SuperAgent { (url: string): SuperAgentRequest; (method: string, url: string): SuperAgentRequest; @@ -97,10 +98,12 @@ declare module "superagent" { redirects(n: number): Req; send(data: string): Req; send(data: Object): Req; + send(): Req; set(field: string, val: string): Req; set(field: Object): Req; timeout(ms: number): Req; type(val: string): Req; + use(fn: Function): Req; withCredentials(): Req; write(data: string, encoding?: string): Req; write(data: Buffer, encoding?: string): Req; @@ -110,5 +113,4 @@ declare module "superagent" { } export = request; -} - +} \ No newline at end of file diff --git a/typings/supertest/supertest.d.ts b/typings/browser/ambient/supertest/index.d.ts similarity index 88% rename from typings/supertest/supertest.d.ts rename to typings/browser/ambient/supertest/index.d.ts index dccbd47..682de62 100644 --- a/typings/supertest/supertest.d.ts +++ b/typings/browser/ambient/supertest/index.d.ts @@ -1,9 +1,10 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/supertest/supertest.d.ts // Type definitions for SuperTest 0.14.0 // Project: https://github.com/visionmedia/supertest // Definitions by: Alex Varju // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// declare module "supertest" { import superagent = require('superagent'); @@ -36,4 +37,4 @@ declare module "supertest" { } export = supertest; -} +} \ No newline at end of file diff --git a/typings/main.d.ts b/typings/main.d.ts new file mode 100644 index 0000000..3b7c164 --- /dev/null +++ b/typings/main.d.ts @@ -0,0 +1,12 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/typings/main/ambient/body-parser/index.d.ts b/typings/main/ambient/body-parser/index.d.ts new file mode 100644 index 0000000..56d3cc2 --- /dev/null +++ b/typings/main/ambient/body-parser/index.d.ts @@ -0,0 +1,139 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/body-parser/body-parser.d.ts +// Type definitions for body-parser +// Project: http://expressjs.com +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "body-parser" { + import express = require('express'); + + /** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ + + function bodyParser(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + + module bodyParser { + export function json(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'json') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + }): express.RequestHandler; + + export function raw(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + }): express.RequestHandler; + + export function text(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + }): express.RequestHandler; + + export function urlencoded(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; + }): express.RequestHandler; + } + + export = bodyParser; +} \ No newline at end of file diff --git a/typings/main/ambient/chai/index.d.ts b/typings/main/ambient/chai/index.d.ts new file mode 100644 index 0000000..4ab4d27 --- /dev/null +++ b/typings/main/ambient/chai/index.d.ts @@ -0,0 +1,310 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/chai/chai.d.ts +// Type definitions for chai 2.0.0 +// Project: http://chaijs.com/ +// Definitions by: Jed Mao , +// Bart van der Schoor , +// Andrew Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Chai { + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): any; + assert: AssertStatic; + config: Config; + } + + export interface ExpectStatic extends AssertionStatic { + } + + export interface AssertStatic extends Assert { + } + + export interface AssertionStatic { + (target: any, message?: string): Assertion; + } + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(actual: any, expected: any, message?: string, operator?: string): void; + } + + interface ShouldThrow { + (actual: Function): void; + (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + a: TypeComparison; + an: TypeComparison; + include: Include; + contain: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: OwnProperty; + haveOwnProperty: OwnProperty; + length: Length; + lengthOf: Length; + match(regexp: RegExp|string, message?: string): Assertion; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo(method: string, message?: string): Assertion; + itself: Assertion; + satisfy(matcher: Function, message?: string): Assertion; + closeTo(expected: number, delta: number, message?: string): Assertion; + members: Members; + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + } + + interface NumberComparer { + (value: number, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: Object, message?: string): Assertion; + } + + interface Deep { + equal: Equal; + include: Include; + property: Property; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string, value?: any, message?: string): Assertion; + } + + interface OwnProperty { + (name: string, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; + keys: Keys; + members: Members; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: any[]): Assertion; + } + + interface Throw { + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; + + ok(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; + + equal(act: any, exp: any, msg?: string): void; + notEqual(act: any, exp: any, msg?: string): void; + + strictEqual(act: any, exp: any, msg?: string): void; + notStrictEqual(act: any, exp: any, msg?: string): void; + + deepEqual(act: any, exp: any, msg?: string): void; + notDeepEqual(act: any, exp: any, msg?: string): void; + + isTrue(val: any, msg?: string): void; + isFalse(val: any, msg?: string): void; + + isNull(val: any, msg?: string): void; + isNotNull(val: any, msg?: string): void; + + isUndefined(val: any, msg?: string): void; + isDefined(val: any, msg?: string): void; + + isFunction(val: any, msg?: string): void; + isNotFunction(val: any, msg?: string): void; + + isObject(val: any, msg?: string): void; + isNotObject(val: any, msg?: string): void; + + isArray(val: any, msg?: string): void; + isNotArray(val: any, msg?: string): void; + + isString(val: any, msg?: string): void; + isNotString(val: any, msg?: string): void; + + isNumber(val: any, msg?: string): void; + isNotNumber(val: any, msg?: string): void; + + isBoolean(val: any, msg?: string): void; + isNotBoolean(val: any, msg?: string): void; + + typeOf(val: any, type: string, msg?: string): void; + notTypeOf(val: any, type: string, msg?: string): void; + + instanceOf(val: any, type: Function, msg?: string): void; + notInstanceOf(val: any, type: Function, msg?: string): void; + + include(exp: string, inc: any, msg?: string): void; + include(exp: any[], inc: any, msg?: string): void; + + notInclude(exp: string, inc: any, msg?: string): void; + notInclude(exp: any[], inc: any, msg?: string): void; + + match(exp: any, re: RegExp, msg?: string): void; + notMatch(exp: any, re: RegExp, msg?: string): void; + + property(obj: Object, prop: string, msg?: string): void; + notProperty(obj: Object, prop: string, msg?: string): void; + deepProperty(obj: Object, prop: string, msg?: string): void; + notDeepProperty(obj: Object, prop: string, msg?: string): void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + lengthOf(exp: any, len: number, msg?: string): void; + //alias frenzy + throw(fn: Function, msg?: string): void; + throw(fn: Function, regExp: RegExp): void; + throw(fn: Function, errType: Function, msg?: string): void; + throw(fn: Function, errType: Function, regExp: RegExp): void; + + throws(fn: Function, msg?: string): void; + throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, errType: Function, msg?: string): void; + throws(fn: Function, errType: Function, regExp: RegExp): void; + + Throw(fn: Function, msg?: string): void; + Throw(fn: Function, regExp: RegExp): void; + Throw(fn: Function, errType: Function, msg?: string): void; + Throw(fn: Function, errType: Function, regExp: RegExp): void; + + doesNotThrow(fn: Function, msg?: string): void; + doesNotThrow(fn: Function, regExp: RegExp): void; + doesNotThrow(fn: Function, errType: Function, msg?: string): void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; + + operator(val: any, operator: string, val2: any, msg?: string): void; + closeTo(act: number, exp: number, delta: number, msg?: string): void; + + sameMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(set1: any[], set2: any[], msg?: string): void; + + ifError(val: any, msg?: string): void; + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare var chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +interface Object { + should: Chai.Assertion; +} \ No newline at end of file diff --git a/typings/main/ambient/express/index.d.ts b/typings/main/ambient/express/index.d.ts new file mode 100644 index 0000000..a5a0c5b --- /dev/null +++ b/typings/main/ambient/express/index.d.ts @@ -0,0 +1,1099 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/express/express.d.ts +// Type definitions for Express 4.x +// Project: http://expressjs.com +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import express = require('express'); + var app = express(); + + =============================================== */ + + +declare module Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } +} + + +declare module "express" { + import http = require('http'); + + function e(): e.Express; + + module e { + interface IRoute { + path: string; + stack: any; + all(...handler: RequestHandler[]): IRoute; + get(...handler: RequestHandler[]): IRoute; + post(...handler: RequestHandler[]): IRoute; + put(...handler: RequestHandler[]): IRoute; + delete(...handler: RequestHandler[]): IRoute; + patch(...handler: RequestHandler[]): IRoute; + options(...handler: RequestHandler[]): IRoute; + } + + interface IRouterMatcher { + (name: string, ...handlers: RequestHandler[]): T; + (name: RegExp, ...handlers: RequestHandler[]): T; + } + + interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + + route(path: string): IRoute; + + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler): T; + } + + export function Router(options?: any): Router; + + export interface Router extends IRouter {} + + interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + interface Errback { (err: Error): void; } + + interface Request extends http.ServerRequest, Express.Request { + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get (name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(type: string): string; + + accepts(type: string[]): string; + + /** + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): boolean; + + /** + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): boolean; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * Return an array of Accepted languages + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Language: en;q=.5, en-us + * ['en-us', 'en'] + */ + acceptedLanguages: any[]; + + /** + * Return an array of Accepted charsets + * ordered from highest quality to lowest. + * + * Examples: + * + * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 + * ['unicode-1-1', 'iso-8859-5'] + */ + acceptedCharsets: any[]; + + /** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: any; + + user: any; + + authenticatedUser: any; + + files: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + } + + interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

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

hey

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

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): Response; + set(field: string, value?: string): Response; + + header(field: any): Response; + header(field: string, value?: string): Response; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** + * Get value for header `field`. + * + * @param field + */ + get (field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + cookie(name: string, val: any, options: CookieOptions): Response; + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; + render(view: string, callback?: (err: Error, html: string) => void ): void; + + locals: any; + + charset: string; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: Function): any; + } + + interface RequestHandler { + (req: Request, res: Response, next: Function): any; + } + + interface Handler extends RequestHandler {} + + interface RequestParamHandler { + (req: Request, res: Response, next: Function, param: any): any; + } + + interface Application extends IRouter, Express.Application { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set(setting: string, val: any): Application; + get: { + (name: string): any; // Getter + (name: string, ...handlers: RequestHandler[]): Application; + (name: RegExp, ...handlers: RequestHandler[]): Application; + }; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(fn: Function): Application; + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + listen(port: number, hostname: string, callback?: Function): http.Server; + listen(port: number, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + + route(path: string): IRoute; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + } + + interface Express extends Application { + /** + * Framework version. + */ + version: string; + + /** + * Expose mime. + */ + mime: string; + + (): Application; + + /** + * Create an express application. + */ + createApplication(): Application; + + createServer(): Application; + + application: any; + + request: Request; + + response: Response; + } + + /** + * Static: + * + * Static file server with the given `root` path. + * + * Examples: + * + * var oneDay = 86400000; + * + * connect() + * .use(connect.static(__dirname + '/public')) + * + * connect() + * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) + * + * Options: + * + * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 + * - `hidden` Allow transfer of hidden files. defaults to false + * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true + * + * @param root + * @param options + */ + function static(root: string, options?: any): RequestHandler; + } + + export = e; +} \ No newline at end of file diff --git a/typings/main/ambient/mocha/index.d.ts b/typings/main/ambient/mocha/index.d.ts new file mode 100644 index 0000000..c4fdd8d --- /dev/null +++ b/typings/main/ambient/mocha/index.d.ts @@ -0,0 +1,168 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mocha/mocha.d.ts +// Type definitions for mocha 2.0.1 +// Project: http://mochajs.org/ +// Definitions by: Kazi Manzur Rashid , otiai10 , jt000 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Mocha { + // Setup mocha with the given setting options. + setup(options: MochaSetupOptions): Mocha; + + //Run tests and invoke `fn()` when complete. + run(callback?: () => void): void; + + // Set reporter as function + reporter(reporter: () => void): Mocha; + + // Set reporter, defaults to "dot" + reporter(reporter: string): Mocha; + + // Enable growl support. + growl(): Mocha +} + +interface MochaSetupOptions { + //milliseconds to wait before considering a test slow + slow?: number; + + // timeout in milliseconds + timeout?: number; + + // ui name "bdd", "tdd", "exports" etc + ui?: string; + + //array of accepted globals + globals?: any[]; + + // reporter instance (function or string), defaults to `mocha.reporters.Dot` + reporter?: any; + + // bail on the first test failure + bail?: boolean; + + // ignore global leaks + ignoreLeaks?: boolean; + + // grep string or regexp to filter tests with + grep?: any; +} + +interface MochaDone { + (error?: Error): void; +} + +declare var mocha: Mocha; + +declare var describe: { + (description: string, spec: () => void): void; + only(description: string, spec: () => void): void; + skip(description: string, spec: () => void): void; + timeout(ms: number): void; +} + +// alias for `describe` +declare var context: { + (contextTitle: string, spec: () => void): void; + only(contextTitle: string, spec: () => void): void; + skip(contextTitle: string, spec: () => void): void; + timeout(ms: number): void; +}; + +// alias for `describe` +declare var suite: { + (suiteTitle: string, spec: () => void): void; + only(suiteTitle: string, spec: () => void): void; + skip(suiteTitle: string, spec: () => void): void; + timeout(ms: number): void; +}; + +declare var it: { + (expectation: string, assertion?: () => void): void; + (expectation: string, assertion?: (done: MochaDone) => void): void; + only(expectation: string, assertion?: () => void): void; + only(expectation: string, assertion?: (done: MochaDone) => void): void; + skip(expectation: string, assertion?: () => void): void; + skip(expectation: string, assertion?: (done: MochaDone) => void): void; + timeout(ms: number): void; +}; + +// alias for `it` +declare var test: { + (expectation: string, assertion?: () => void): void; + (expectation: string, assertion?: (done: MochaDone) => void): void; + only(expectation: string, assertion?: () => void): void; + only(expectation: string, assertion?: (done: MochaDone) => void): void; + skip(expectation: string, assertion?: () => void): void; + skip(expectation: string, assertion?: (done: MochaDone) => void): void; + timeout(ms: number): void; +}; + +declare function before(action: () => void): void; + +declare function before(action: (done: MochaDone) => void): void; + +declare function setup(action: () => void): void; + +declare function setup(action: (done: MochaDone) => void): void; + +declare function after(action: () => void): void; + +declare function after(action: (done: MochaDone) => void): void; + +declare function teardown(action: () => void): void; + +declare function teardown(action: (done: MochaDone) => void): void; + +declare function beforeEach(action: () => void): void; + +declare function beforeEach(action: (done: MochaDone) => void): void; + +declare function suiteSetup(action: () => void): void; + +declare function suiteSetup(action: (done: MochaDone) => void): void; + +declare function afterEach(action: () => void): void; + +declare function afterEach(action: (done: MochaDone) => void): void; + +declare function suiteTeardown(action: () => void): void; + +declare function suiteTeardown(action: (done: MochaDone) => void): void; + +declare module "mocha" { + + class Mocha { + constructor(options?: { + grep?: RegExp; + ui?: string; + reporter?: string; + timeout?: number; + bail?: boolean; + }); + + bail(value?: boolean): Mocha; + addFile(file: string): Mocha; + reporter(value: string): Mocha; + ui(value: string): Mocha; + grep(value: string): Mocha; + grep(value: RegExp): Mocha; + invert(): Mocha; + ignoreLeaks(value: boolean): Mocha; + checkLeaks(): Mocha; + growl(): Mocha; + globals(value: string): Mocha; + globals(values: string[]): Mocha; + useColors(value: boolean): Mocha; + useInlineDiffs(value: boolean): Mocha; + timeout(value: number): Mocha; + slow(value: number): Mocha; + enableTimeouts(value: boolean): Mocha; + asyncOnly(value: boolean): Mocha; + noHighlighting(value: boolean): Mocha; + + run(onComplete?: (failures: number) => void): void; + } + + export = Mocha; +} \ No newline at end of file diff --git a/typings/main/ambient/mongoose/index.d.ts b/typings/main/ambient/mongoose/index.d.ts new file mode 100644 index 0000000..eda050c --- /dev/null +++ b/typings/main/ambient/mongoose/index.d.ts @@ -0,0 +1,461 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mongoose/mongoose.d.ts +// Type definitions for Mongoose 3.8.5 +// Project: http://mongoosejs.com/ +// Definitions by: horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "mongoose" { + function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + function createConnection(): Connection; + function createConnection(uri: string, options?: ConnectionOption): Connection; + function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + function disconnect(callback?: (err?: any) => void): Mongoose; + + function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + function modelNames(): string[]; + function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + + function get(key: string): any; + function set(key: string, value: any): void; + + var mongo: any; + var mquery: any; + var version: string; + var connection: Connection; + + export class Mongoose { + connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + createConnection(): Connection; + createConnection(uri: string, options?: Object): Connection; + createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + disconnect(callback?: (err?: any) => void): Mongoose; + get(key: string): any; + model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + modelNames(): string[]; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + set(key: string, value: any): void; + + mongo: any; + mquery: any; + version: string; + connection: Connection; + } + + export interface Connection extends NodeJS.EventEmitter { + constructor(base: Mongoose): Connection; + + close(callback?: (err: any) => void): Connection; + collection(name: string, options?: Object): Collection; + model(name: string, schema?: Schema, collection?: string): Model; + modelNames(): string[]; + open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection; + openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection; + + db: any; + collections: {[index: string]: Collection}; + readyState: number; + } + export interface ConnectionOption { + db?: any; + server?: any; + replset?: any; + user?: string; + pass?: string; + auth?: any; + } + export interface ConnectionSetOption extends ConnectionOption { + mongos?: boolean; + } + + export interface Collection { + } + + + export class SchemaType { } + export class VirtualType { + get(fn: Function): VirtualType; + set(fn: Function): VirtualType; + } + export module Types { + export class ObjectId { + constructor(id: string|number); + toHexString(): string; + equals(other: ObjectId): boolean; + getTimestamp(): Date; + isValid(): boolean; + static createFromTime(time: number): ObjectId; + static createFromHexString(hexString: string): ObjectId; + } + } + + export class Schema { + static Types: { + String: String; + ObjectId: Types.ObjectId; + OId: Types.ObjectId; + Mixed: any; + }; + constructor(schema?: Object, options?: Object); + + add(obj: Object, prefix?: string): void; + eachPath(fn: (path: string, type: any) => void): Schema; + get(key: string): any; + index(fields: Object, options?: Object): Schema; + indexes(): void; + method(name: string, fn: Function): Schema; + method(method: Object): Schema; + path(path: string): any; + path(path: string, constructor: any): Schema; + pathType(path: string): string; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + post(method: string, fn: Function): Schema; + pre(method: string, callback: Function): Schema; + requiredPaths(): string[]; + set(key: string, value: any): void; + static(name: string, fn: Function): Schema; + virtual(name: string, options?: Object): VirtualType; + virtualpath(name: string): VirtualType; + } + export interface SchemaOption { + autoIndex?: boolean; + bufferCommands?: boolean; + capped?: boolean; + collection?: string; + id?: boolean; + _id?: boolean; + minimize?: boolean; + read?: string; + safe?: boolean; + shardKey?: boolean; + strict?: boolean; + toJSON?: Object; + toObject?: Object; + versionKey?: boolean; + } + + export interface Model extends NodeJS.EventEmitter { + new(doc: Object): T; + + aggregate(...aggregations: Object[]): Aggregate; + aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + create(doc: Object, fn?: (err: any, res: T) => void): Promise; + create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; + create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; + discriminator(name: string, schema: Schema): Model; + distinct(field: string, callback?: (err: any, res: T[]) => void): Query; + distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; + ensureIndexes(callback: (err: any) => void): Promise; + + find(cond: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; + findById(id: string, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + + geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query; + geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query; + geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; + increment(): T; + mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + model(name: string): Model; + + populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; + populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; + update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + remove(cond: Object, callback?: (err: any) => void): Query<{}>; + save(callback?: (err: any, result: T, numberAffected: number) => void): Query; + where(path: string, val?: Object): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + base: Mongoose; + collection: Collection; + db: any; + discriminators: any; + modelName: string; + schema: Schema; + } + export interface FindAndUpdateOption { + new?: boolean; + upsert?: boolean; + sort?: Object; + select?: Object; + } + export interface GeoSearchOption { + near: number[]; + maxDistance: number; + limit?: number; + lean?: boolean; + } + export interface MapReduceOption { + map: () => void; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceOption2 { + map: string; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceResult { + _id: Key; + value: Val; + } + + export class Query { + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string, callback?: (err: any, res: T) => void): Promise; + exec(operation: Function, callback?: (err: any, res: T) => void): Promise; + + all(val: number): Query; + all(path: string, val: number): Query; + and(array: Object[]): Query; + box(val: Object): Query; + box(a: number[], b: number[]): Query; + batchSize(val: number): Query; + cast(model: Model, obj: Object): U; + //center(): Query; + //centerSphere(path: string, val: Object): Query; + circle(area: Object): Query; + circle(path: string, area: Object): Query; + comment(val: any): Query; + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; + distinct(callback?: (err: any, res: T) => void): Query; + distinct(field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; + elemMatch(criteria: Object): Query; + elemMatch(criteria: (elem: Query) => void): Query; + elemMatch(path: string, criteria: Object): Query; + elemMatch(path: string, criteria: (elem: Query) => void): Query; + equals(val: Object): Query; + exists(val?: boolean): Query; + exists(path: string, val?: boolean): Query; + find(callback?: (err: any, res: T) => void): Query; + find(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOne(callback?: (err: any, res: T) => void): Query; + findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + geometry(object: Object): Query; + gt(val: number): Query; + gt(path: string, val: number): Query; + gte(val: number): Query; + gte(path: string, val: number): Query; + hint(val: Object): Query; + in(val: any[]): Query; + in(path: string, val: any[]): Query; + intersects(arg?: Object): Query; + lean(bool?: boolean): Query; + limit(val: number): Query; + lt(val: number): Query; + lt(path: string, val: number): Query; + lte(val: number): Query; + lte(path: string, val: number): Query; + maxDistance(val: number): Query; + maxDistance(path: string, val: number): Query; + maxScan(val: number): Query; + merge(source: Query): Query; + merge(source: Object): Query; + mod(val: number[]): Query; + mod(path: string, val: number[]): Query; + ne(val: any): Query; + ne(path: string, val: any): Query; + near(val: Object): Query; + near(path: string, val: Object): Query; + nearSphere(val: Object): Query; + nearSphere(path: string, val: Object): Query; + nin(val: any[]): Query; + nin(path: string, val: any[]): Query; + nor(array: Object[]): Query; + or(array: Object[]): Query; + polygon(...coordinatePairs: number[][]): Query; + polygon(path: string, ...coordinatePairs: number[][]): Query; + populate(path: string, select?: string, match?: Object, options?: Object): Query; + populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; + populate(opt: PopulateOption): Query; + read(pref: string, tags?: Object[]): Query; + regex(val: RegExp): Query; + regex(path: string, val: RegExp): Query; + remove(callback?: (err: any, res: T) => void): Query; + remove(criteria: Object, callback?: (err: any, res: T) => void): Query; + select(arg: string): Query; + select(arg: Object): Query; + setOptions(options: Object): Query; + size(val: number): Query; + size(path: string, val: number): Query; + skip(val: number): Query; + slaveOk(v?: boolean): Query; + slice(val: number): Query; + slice(val: number[]): Query; + slice(path: string, val: number): Query; + slice(path: string, val: number[]): Query; + snapshot(v?: boolean): Query; + sort(arg: Object): Query; + sort(arg: string): Query; + stream(options?: { transform?: Function; }): QueryStream; + tailable(v?: boolean): Query; + toConstructor(): Query; + update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + where(path?: string, val?: any): Query; + where(path?: Object, val?: any): Query; + within(val?: Object): Query; + within(coordinate: number[], ...coordinatePairs: number[][]): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + static use$geoWithin: boolean; + } + + export interface PopulateOption { + path: string; + select?: string; + model?: string; + match?: Object; + options?: Object; + } + + export interface QueryStream extends NodeJS.EventEmitter { + destory(err?: any): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + paused: number; + readable: boolean; + } + + export interface Document { + id?: string; + _id: Types.ObjectId; + + equals(doc: Document): boolean; + get(path: string, type?: new(...args: any[]) => any): any; + inspect(options?: Object): string; + invalidate(path: string, errorMsg: string, value: any): void; + invalidate(path: string, error: Error, value: any): void; + isDirectModified(path: string): boolean; + isInit(path: string): boolean; + isModified(path?: string): boolean; + isSelected(path: string): boolean; + markModified(path: string): void; + modifiedPaths(): string[]; + populate(callback?: (err: any, res: T) => void): Document; + populate(path?: string, callback?: (err: any, res: T) => void): Document; + populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; + populated(path: string): any; + remove(callback?: (err: any) => void): Query; + save(callback?: (err: any, res: T) => void): void; + set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; + set(path: string, val: any, options?: Object): void; + set(value: Object): void; + toJSON(options?: Object): Object; + toObject(options?: Object): Object; + toString(): string; + update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; + validate(cb: (err: any) => void): void; + + isNew: boolean; + errors: Object; + schema: Object; + } + + + export class Aggregate { + constructor(...options: Object[]); + + append(...options: Object[]): Aggregate; + group(arg: Object): Aggregate; + limit(num: number): Aggregate; + match(arg: Object): Aggregate; + near(parameters: Object): Aggregate; + project(arg: string): Aggregate; + project(arg: Object): Aggregate; + select(filter: string): Aggregate; + skip(num: number): Aggregate; + sort(arg: string): Aggregate; + sort(arg: Object): Aggregate; + unwind(fiels: string, ...rest: string[]): Aggregate; + + exec(callback?: (err: any, result: T) => void): Promise; + read(pref: string, ...tags: Object[]): Aggregate; + } + + export class Promise { + constructor(fn?: (err: any, result: T) => void); + + then(onFulFill: (result: T) => void, onReject?: (err: any) => void): Promise; + end(): void; + + fulfill(result: T): Promise; + reject(err: any): Promise; + resolve(err: any, result: T): Promise; + + onFulfill(listener: (result: T) => void): Promise; + onReject(listener: (err: any) => void): Promise; + onResolve(listener: (err: any, result: T) => void): Promise; + on(event: string, listener: Function): Promise; + + // Deprecated methods. + addBack(listener: (err: any, result: T) => void): Promise; + addCallback(listener: (result: T) => void): Promise; + addErrback(listener: (err: any) => void): Promise; + complete(result: T): Promise; + error(err: any): Promise; + } + +} \ No newline at end of file diff --git a/typings/main/ambient/node/index.d.ts b/typings/main/ambient/node/index.d.ts new file mode 100644 index 0000000..e9b4c3d --- /dev/null +++ b/typings/main/ambient/node/index.d.ts @@ -0,0 +1,2377 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4f479b281cb116de213cc5301f273018c13c7267/node/node.d.ts +// Type definitions for Node.js v4.x +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/************************************************ +* * +* Node.js v4.x API * +* * +************************************************/ + +interface Error { + stack?: string; +} + + +// 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 {} + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id:string): string; + cache: any; + extensions: any; + main: any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: any; + children: any[]; +} + +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; +}; + + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer {} + +/** + * 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; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare namespace NodeJS { + 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; + 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; + listenerCount(type: string): number; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string|Buffer; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + 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; + 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 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; + + 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 Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + 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[]; + domain: Domain; + + // 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 Timer { + ref() : void; + unref() : void; + } +} + +/** + * @deprecated + */ +interface NodeBuffer extends Uint8Array { + 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): Buffer; + // TODO: encoding param + indexOf(value: string | number | Buffer, byteOffset?: number): number; + // TODO: entries + // TODO: includes + // TODO: keys + // TODO: values +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + 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 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; +} + +declare module "events" { + export class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: 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; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + } +} + +declare module "http" { + 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 Server extends events.EventEmitter, net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends events.EventEmitter, 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; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + 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 ClientRequest extends events.EventEmitter, 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 events.EventEmitter, stream.Readable { + httpVersion: string; + 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; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + 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; + + 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; + } + + 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; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export interface Address { + address: string; + port: number; + addressType: string; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): 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 + }; + + // 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; } + + 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 deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzipSync(buf: Buffer, 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 tmpdir(): string; + export function homedir(): string; + export function endianness(): string; + 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 var EOL: string; +} + +declare module "https" { + 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 RequestOptions extends http.RequestOptions{ + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + export var Agent: { + new (options?: RequestOptions): 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; +} + +declare module "repl" { + import * as stream from "stream"; + import * as events from "events"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; +} + +declare module "readline" { + 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 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; + } + + export interface CompleterResult { + completions: string[]; + line: 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 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"; + + 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): void; + disconnect(): void; + unref(): void; + } + + 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 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 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 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 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 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?: 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?: any; // string | Object + 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; +} + +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[]; +} + +declare module "net" { + 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; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): 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; + + // 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 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 Socket { + 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(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + listen(options: ListenOptions, 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; + } + 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"; + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): 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; + } +} + +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; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } + + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, 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, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, 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, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, 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, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, 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): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, 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. + */ + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string): 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. + */ + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string): 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. + */ + export function mkdir(path: string, 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. + */ + export function mkdir(path: string, 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. + */ + export function mkdir(path: string, 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, 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, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, 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, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, 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, mode ?: number): void; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + }): WriteStream; +} + +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:\' + */ + 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: any[]): 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: 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; + /** + * 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; + 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" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + 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"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + host?: string; + port?: number; + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: any; //string | Buffer + key?: any; //string | Buffer + passphrase?: string; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer + rejectUnauthorized?: boolean; + NPNProtocols?: any; //Array of string | Buffer + servername?: string; + } + + export interface Server extends net.Server { + close(): 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 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?: any; //string | buffer + key?: any; //string | buffer + passphrase?: string; + cert?: any; // string | buffer + ca?: any; // string | buffer + crl?: any; // 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: TlsOptions, 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" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + 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): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + export interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + 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: "utf8"|"ascii"|"binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; + update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; + } + 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: "binary"|"base64"|"hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; + update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + export interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_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 getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + 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) : 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 RsaPublicKey { + key: string; + padding?: any; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: any; + } + export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer +} + +declare module "stream" { + import * as events from "events"; + + export class Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + 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; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _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 DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _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 ReadableOptions, WritableOptions {} + + // 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); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + 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 {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + 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; +} + +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; + + 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 = internal; +} + +declare module "tty" { + 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; + } +} + +declare module "domain" { + 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; + } + + 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_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: 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; +} \ No newline at end of file diff --git a/typings/main/ambient/pluralize/index.d.ts b/typings/main/ambient/pluralize/index.d.ts new file mode 100644 index 0000000..43daef9 --- /dev/null +++ b/typings/main/ambient/pluralize/index.d.ts @@ -0,0 +1,67 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/101a5daef4fc42eca0d447ba5d080248f80daf90/pluralize/pluralize.d.ts +// Type definitions for pluralize +// Project: https://www.npmjs.com/package/pluralize +// Definitions by: Syu Kato +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface PluralizeStatic { + /** + * Pluralize or singularize a word based on the passed in count. + * + * @param word + * @param count + * @param inclusive + */ + (word: string, count?: number, inclusive?: boolean): string; + + /** + * Pluralize a word based. + * + * @param word + */ + plural(word: string): string; + + /** + * Singularize a word based. + * + * @param word + */ + singular(word: string): string; + + /** + * Add a pluralization rule to the collection. + * + * @param rule + * @param replacement + */ + addPluralRule(rule: string|RegExp, replacemant: string): void; + + /** + * Add a singularization rule to the collection. + * + * @param rule + * @param replacement + */ + addSingularRule(rule: string|RegExp, replacemant: string): void; + + /** + * Add an irregular word definition. + * + * @param single + * @param plural + */ + addIrregularRule(single: string, plural: string): void; + + /** + * Add an uncountable word rule. + * + * @param word + */ + addUncountableRule(word: string|RegExp): void; +} + +declare module "pluralize" { + export = pluralize; +} +declare var pluralize: PluralizeStatic; \ No newline at end of file diff --git a/typings/main/ambient/sinon-chai/index.d.ts b/typings/main/ambient/sinon-chai/index.d.ts new file mode 100644 index 0000000..0b923d7 --- /dev/null +++ b/typings/main/ambient/sinon-chai/index.d.ts @@ -0,0 +1,84 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon-chai/sinon-chai.d.ts +// Type definitions for sinon-chai 2.7.0 +// Project: https://github.com/domenic/sinon-chai +// Definitions by: Kazi Manzur Rashid , Jed Mao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module Chai { + + interface LanguageChains { + always: Assertion; + } + + interface Assertion { + /** + * true if the spy was called at least once. + */ + called: Assertion; + /** + * @param count The number of recorded calls. + */ + callCount(count: number): Assertion; + /** + * true if the spy was called exactly once. + */ + calledOnce: Assertion; + /** + * true if the spy was called exactly twice. + */ + calledTwice: Assertion; + /** + * true if the spy was called exactly thrice. + */ + calledThrice: Assertion; + /** + * Returns true if the spy was called before anotherSpy. + */ + calledBefore(anotherSpy: Sinon.SinonSpy): Assertion; + /** + * Returns true if the spy was called after anotherSpy. + */ + calledAfter(anotherSpy: Sinon.SinonSpy): Assertion; + /** + * Returns true if spy/stub was called with the new operator. Beware that + * this is inferred based on the value of the this object and the spy + * function's prototype, so it may give false positives if you actively + * return the right kind of object. + */ + calledWithNew: Assertion; + /** + * Returns true if context was this for this call. + */ + calledOn(context: any): Assertion; + /** + * Returns true if call received provided arguments (and possibly others). + */ + calledWith(...args: any[]): Assertion; + /** + * Returns true if call received provided arguments and no others. + */ + calledWithExactly(...args: any[]): Assertion; + /** + * Returns true if call received matching arguments (and possibly others). + * This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). + */ + calledWithMatch(...args: any[]): Assertion; + /** + * Returns true if spy returned the provided value at least once. Uses + * deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) + * for strict comparison (see matchers). + */ + returned(obj: any): Assertion; + /** + * Returns true if spy threw the provided exception object at least once. + */ + thrown(obj?: Error|typeof Error|string): Assertion; + } +} + +declare module "sinon-chai" { + function sinonChai(chai: any, utils: any): void; + export = sinonChai; +} \ No newline at end of file diff --git a/typings/main/ambient/sinon/index.d.ts b/typings/main/ambient/sinon/index.d.ts new file mode 100644 index 0000000..4b743f9 --- /dev/null +++ b/typings/main/ambient/sinon/index.d.ts @@ -0,0 +1,422 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon/sinon.d.ts +// Type definitions for Sinon 1.8.1 +// Project: http://sinonjs.org/ +// Definitions by: William Sears +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Sinon { + interface SinonSpyCallApi { + // Properties + thisValue: any; + args: any[]; + exception: any; + returnValue: any; + + // Methods + calledOn(obj: any): boolean; + calledWith(...args: any[]): boolean; + calledWithExactly(...args: any[]): boolean; + calledWithMatch(...args: any[]): boolean; + notCalledWith(...args: any[]): boolean; + notCalledWithMatch(...args: any[]): boolean; + returned(value: any): boolean; + threw(): boolean; + threw(type: string): boolean; + threw(obj: any): boolean; + callArg(pos: number): void; + callArgOn(pos: number, obj: any, ...args: any[]): void; + callArgWith(pos: number, ...args: any[]): void; + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + yield(...args: any[]): void; + yieldOn(obj: any, ...args: any[]): void; + yieldTo(property: string, ...args: any[]): void; + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SinonSpyCall extends SinonSpyCallApi { + calledBefore(call: SinonSpyCall): boolean; + calledAfter(call: SinonSpyCall): boolean; + calledWithNew(call: SinonSpyCall): boolean; + } + + interface SinonSpy extends SinonSpyCallApi { + // Properties + callCount: number; + called: boolean; + notCalled: boolean; + calledOnce: boolean; + calledTwice: boolean; + calledThrice: boolean; + firstCall: SinonSpyCall; + secondCall: SinonSpyCall; + thirdCall: SinonSpyCall; + lastCall: SinonSpyCall; + thisValues: any[]; + args: any[][]; + exceptions: any[]; + returnValues: any[]; + + // Methods + (...args: any[]): any; + calledBefore(anotherSpy: SinonSpy): boolean; + calledAfter(anotherSpy: SinonSpy): boolean; + calledWithNew(spy: SinonSpy): boolean; + withArgs(...args: any[]): SinonSpy; + alwaysCalledOn(obj: any): boolean; + alwaysCalledWith(...args: any[]): boolean; + alwaysCalledWithExactly(...args: any[]): boolean; + alwaysCalledWithMatch(...args: any[]): boolean; + neverCalledWith(...args: any[]): boolean; + neverCalledWithMatch(...args: any[]): boolean; + alwaysThrew(): boolean; + alwaysThrew(type: string): boolean; + alwaysThrew(obj: any): boolean; + alwaysReturned(): boolean; + invokeCallback(...args: any[]): void; + getCall(n: number): SinonSpyCall; + reset(): void; + printf(format: string, ...args: any[]): string; + restore(): void; + } + + interface SinonSpyStatic { + (): SinonSpy; + (func: any): SinonSpy; + (obj: any, method: string): SinonSpy; + } + + interface SinonStatic { + spy: SinonSpyStatic; + } + + interface SinonStub extends SinonSpy { + resetBehavior(): void; + returns(obj: any): SinonStub; + returnsArg(index: number): SinonStub; + throws(type?: string): SinonStub; + throws(obj: any): SinonStub; + callsArg(index: number): SinonStub; + callsArgOn(index: number, context: any): SinonStub; + callsArgWith(index: number, ...args: any[]): SinonStub; + callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; + callsArgAsync(index: number): SinonStub; + callsArgOnAsync(index: number, context: any): SinonStub; + callsArgWithAsync(index: number, ...args: any[]): SinonStub; + callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; + onCall(n: number): SinonStub; + onFirstCall(): SinonStub; + onSecondCall(): SinonStub; + onThirdCall(): SinonStub; + yields(...args: any[]): SinonStub; + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsTo(property: string, ...args: any[]): SinonStub; + yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; + yieldsAsync(...args: any[]): SinonStub; + yieldsOnAsync(context: any, ...args: any[]): SinonStub; + yieldsToAsync(property: string, ...args: any[]): SinonStub; + yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; + withArgs(...args: any[]): SinonStub; + } + + interface SinonStubStatic { + (): SinonStub; + (obj: any): SinonStub; + (obj: any, method: string): SinonStub; + (obj: any, method: string, func: any): SinonStub; + } + + interface SinonStatic { + stub: SinonStubStatic; + } + + interface SinonExpectation extends SinonStub { + atLeast(n: number): SinonExpectation; + atMost(n: number): SinonExpectation; + never(): SinonExpectation; + once(): SinonExpectation; + twice(): SinonExpectation; + thrice(): SinonExpectation; + exactly(n: number): SinonExpectation; + withArgs(...args: any[]): SinonExpectation; + withExactArgs(...args: any[]): SinonExpectation; + on(obj: any): SinonExpectation; + verify(): SinonExpectation; + restore(): void; + } + + interface SinonExpectationStatic { + create(methodName?: string): SinonExpectation; + } + + interface SinonMock { + expects(method: string): SinonExpectation; + restore(): void; + verify(): void; + } + + interface SinonMockStatic { + (): SinonExpectation; + (obj: any): SinonMock; + } + + interface SinonStatic { + expectation: SinonExpectationStatic; + mock: SinonMockStatic; + } + + interface SinonFakeTimers { + now: number; + create(now: number): SinonFakeTimers; + setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; + clearTimeout(id: number): void; + setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; + clearInterval(id: number): void; + tick(ms: number): number; + reset(): void; + Date(): Date; + Date(year: number): Date; + Date(year: number, month: number): Date; + Date(year: number, month: number, day: number): Date; + Date(year: number, month: number, day: number, hour: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; + restore(): void; + } + + interface SinonFakeTimersStatic { + (): SinonFakeTimers; + (...timers: string[]): SinonFakeTimers; + (now: number, ...timers: string[]): SinonFakeTimers; + } + + interface SinonStatic { + useFakeTimers: SinonFakeTimersStatic; + clock: SinonFakeTimers; + } + + interface SinonFakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; + } + + interface SinonFakeXMLHttpRequest { + // Properties + onCreate: (xhr: SinonFakeXMLHttpRequest) => void; + url: string; + method: string; + requestHeaders: any; + requestBody: string; + status: number; + statusText: string; + async: boolean; + username: string; + password: string; + withCredentials: boolean; + upload: SinonFakeUploadProgress; + responseXML: Document; + getResponseHeader(header: string): string; + getAllResponseHeaders(): any; + + // Methods + restore(): void; + useFilters: boolean; + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; + setResponseHeaders(headers: any): void; + setResponseBody(body: string): void; + respond(status: number, headers: any, body: string): void; + autoRespond(ms: number): void; + } + + interface SinonFakeXMLHttpRequestStatic { + (): SinonFakeXMLHttpRequest; + } + + interface SinonStatic { + useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + FakeXMLHttpRequest: SinonFakeXMLHttpRequest; + } + + interface SinonFakeServer { + // Properties + autoRespond: boolean; + autoRespondAfter: number; + fakeHTTPMethods: boolean; + getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; + requests: SinonFakeXMLHttpRequest[]; + + // Methods + respondWith(body: string): void; + respondWith(response: any[]): void; + respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(url: string, body: string): void; + respondWith(url: string, response: any[]): void; + respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(method: string, url: string, body: string): void; + respondWith(method: string, url: string, response: any[]): void; + respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(url: RegExp, body: string): void; + respondWith(url: RegExp, response: any[]): void; + respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(method: string, url: RegExp, body: string): void; + respondWith(method: string, url: RegExp, response: any[]): void; + respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respond(): void; + restore(): void; + } + + interface SinonFakeServerStatic { + create(): SinonFakeServer; + } + + interface SinonStatic { + fakeServer: SinonFakeServerStatic; + fakeServerWithClock: SinonFakeServerStatic; + } + + interface SinonExposeOptions { + prefix?: string; + includeFail?: boolean; + } + + interface SinonAssert { + // Properties + failException: string; + fail: (message?: string) => void; // Overridable + pass: (assertion: any) => void; // Overridable + + // Methods + notCalled(spy: SinonSpy): void; + called(spy: SinonSpy): void; + calledOnce(spy: SinonSpy): void; + calledTwice(spy: SinonSpy): void; + calledThrice(spy: SinonSpy): void; + callCount(spy: SinonSpy, count: number): void; + callOrder(...spies: SinonSpy[]): void; + calledOn(spy: SinonSpy, obj: any): void; + alwaysCalledOn(spy: SinonSpy, obj: any): void; + calledWith(spy: SinonSpy, ...args: any[]): void; + alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; + neverCalledWith(spy: SinonSpy, ...args: any[]): void; + calledWithExactly(spy: SinonSpy, ...args: any[]): void; + alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; + calledWithMatch(spy: SinonSpy, ...args: any[]): void; + alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + threw(spy: SinonSpy): void; + threw(spy: SinonSpy, exception: string): void; + threw(spy: SinonSpy, exception: any): void; + alwaysThrew(spy: SinonSpy): void; + alwaysThrew(spy: SinonSpy, exception: string): void; + alwaysThrew(spy: SinonSpy, exception: any): void; + expose(obj: any, options?: SinonExposeOptions): void; + } + + interface SinonStatic { + assert: SinonAssert; + } + + interface SinonMatcher { + and(expr: SinonMatcher): SinonMatcher; + or(expr: SinonMatcher): SinonMatcher; + } + + interface SinonMatch { + (value: number): SinonMatcher; + (value: string): SinonMatcher; + (expr: RegExp): SinonMatcher; + (obj: any): SinonMatcher; + (callback: (value: any) => boolean): SinonMatcher; + any: SinonMatcher; + defined: SinonMatcher; + truthy: SinonMatcher; + falsy: SinonMatcher; + bool: SinonMatcher; + number: SinonMatcher; + string: SinonMatcher; + object: SinonMatcher; + func: SinonMatcher; + array: SinonMatcher; + regexp: SinonMatcher; + date: SinonMatcher; + same(obj: any): SinonMatcher; + typeOf(type: string): SinonMatcher; + instanceOf(type: any): SinonMatcher; + has(property: string, expect?: any): SinonMatcher; + hasOwn(property: string, expect?: any): SinonMatcher; + } + + interface SinonStatic { + match: SinonMatch; + } + + interface SinonSandboxConfig { + injectInto?: any; + properties?: string[]; + useFakeTimers?: any; + useFakeServer?: any; + } + + interface SinonSandbox { + clock: SinonFakeTimers; + requests: SinonFakeXMLHttpRequest; + server: SinonFakeServer; + spy: SinonSpyStatic; + stub: SinonStubStatic; + mock: SinonMockStatic; + useFakeTimers: SinonFakeTimersStatic; + useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + useFakeServer(): SinonFakeServer; + restore(): void; + } + + interface SinonSandboxStatic { + create(): SinonSandbox; + create(config: SinonSandboxConfig): SinonSandbox; + } + + interface SinonStatic { + sandbox: SinonSandboxStatic; + } + + interface SinonTestConfig { + injectIntoThis?: boolean; + injectInto?: any; + properties?: string[]; + useFakeTimers?: boolean; + useFakeServer?: boolean; + } + + interface SinonTestWrapper extends SinonSandbox { + (...args: any[]): any; + } + + interface SinonStatic { + config: SinonTestConfig; + test(fn: (...args: any[]) => any): SinonTestWrapper; + testCase(tests: any): any; + } + + // Utility overridables + interface SinonStatic { + createStubInstance(constructor: any): SinonStub; + format(obj: any): string; + log(message: string): void; + restore(object: any): void; + } +} + +declare var sinon: Sinon.SinonStatic; + +declare module "sinon" { + export = sinon; +} \ No newline at end of file diff --git a/typings/main/ambient/superagent/index.d.ts b/typings/main/ambient/superagent/index.d.ts new file mode 100644 index 0000000..485a146 --- /dev/null +++ b/typings/main/ambient/superagent/index.d.ts @@ -0,0 +1,116 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/superagent/superagent.d.ts +// Type definitions for SuperAgent v1.4.0 +// Project: https://github.com/visionmedia/superagent +// Definitions by: Alex Varju +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "superagent" { + import stream = require('stream'); + + type CallbackHandler = (err: any, res: request.Response) => void; + + var request: request.SuperAgentStatic; + + namespace request { + interface SuperAgentStatic extends SuperAgent { + (url: string): SuperAgentRequest; + (method: string, url: string): SuperAgentRequest; + + agent(): SuperAgent; + } + + interface SuperAgent> extends stream.Stream { + get(url: string, callback?: CallbackHandler): Req; + post(url: string, callback?: CallbackHandler): Req; + put(url: string, callback?: CallbackHandler): Req; + head(url: string, callback?: CallbackHandler): Req; + del(url: string, callback?: CallbackHandler): Req; + delete(url: string, callback?: CallbackHandler): Req; + options(url: string, callback?: CallbackHandler): Req; + trace(url: string, callback?: CallbackHandler): Req; + copy(url: string, callback?: CallbackHandler): Req; + lock(url: string, callback?: CallbackHandler): Req; + mkcol(url: string, callback?: CallbackHandler): Req; + move(url: string, callback?: CallbackHandler): Req; + purge(url: string, callback?: CallbackHandler): Req; + propfind(url: string, callback?: CallbackHandler): Req; + proppatch(url: string, callback?: CallbackHandler): Req; + unlock(url: string, callback?: CallbackHandler): Req; + report(url: string, callback?: CallbackHandler): Req; + mkactivity(url: string, callback?: CallbackHandler): Req; + checkout(url: string, callback?: CallbackHandler): Req; + merge(url: string, callback?: CallbackHandler): Req; + // m-search(url: string, callback?: CallbackHandler): Req; + notify(url: string, callback?: CallbackHandler): Req; + subscribe(url: string, callback?: CallbackHandler): Req; + unsubscribe(url: string, callback?: CallbackHandler): Req; + patch(url: string, callback?: CallbackHandler): Req; + search(url: string, callback?: CallbackHandler): Req; + connect(url: string, callback?: CallbackHandler): Req; + + parse(fn: Function): Req; + saveCookies(res: Response): void; + attachCookies(req: Req): void; + } + + interface Response extends NodeJS.ReadableStream { + text: string; + body: any; + files: any; + header: any; + type: string; + charset: string; + status: number; + statusType: number; + info: boolean; + ok: boolean; + redirect: boolean; + clientError: boolean; + serverError: boolean; + error: Error; + accepted: boolean; + noContent: boolean; + badRequest: boolean; + unauthorized: boolean; + notAcceptable: boolean; + notFound: boolean; + forbidden: boolean; + get(header: string): string; + } + + interface Request> /* extends NodeJS.WritableStream */ { + abort(): void; + accept(type: string): Req; + attach(field: string, file: string, filename?: string): Req; + auth(user: string, name: string): Req; + buffer(val: boolean): Req; + clearTimeout(): Req; + end(callback?: CallbackHandler): Req; + field(name: string, val: string): Req; + get(field: string): string; + on(name: string, handler: Function): Req; + on(name: 'error', handler: (err: any) => void): Req; + part(): Req; + pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; + query(val: Object): Req; + redirects(n: number): Req; + send(data: string): Req; + send(data: Object): Req; + send(): Req; + set(field: string, val: string): Req; + set(field: Object): Req; + timeout(ms: number): Req; + type(val: string): Req; + use(fn: Function): Req; + withCredentials(): Req; + write(data: string, encoding?: string): Req; + write(data: Buffer, encoding?: string): Req; + } + interface SuperAgentRequest extends Request>>> {} + + } + + export = request; +} \ No newline at end of file diff --git a/typings/main/ambient/supertest/index.d.ts b/typings/main/ambient/supertest/index.d.ts new file mode 100644 index 0000000..682de62 --- /dev/null +++ b/typings/main/ambient/supertest/index.d.ts @@ -0,0 +1,40 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/supertest/supertest.d.ts +// Type definitions for SuperTest 0.14.0 +// Project: https://github.com/visionmedia/supertest +// Definitions by: Alex Varju +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module "supertest" { + import superagent = require('superagent'); + + type CallbackHandler = { (err: any, res: supertest.Response): void; }|{ (res: supertest.Response): void; }; + + function supertest(app: any): supertest.SuperTest; + + module supertest { + function agent(app?: any): supertest.SuperTest; + + interface SuperTest extends superagent.SuperAgent { + } + + interface Test extends superagent.Request { + url: string; + serverAddress(app: any, path: string): string; + expect(status: number, callback?: CallbackHandler): Test; + expect(status: number, body: string, callback?: CallbackHandler): Test; + expect(body: string, callback?: CallbackHandler): Test; + expect(body: RegExp, callback?: CallbackHandler): Test; + expect(body: Object, callback?: CallbackHandler): Test; + expect(field: string, val: string, callback?: CallbackHandler): Test; + expect(field: string, val: RegExp, callback?: CallbackHandler): Test; + expect(checker: (res: Response) => any): Test; + } + + interface Response extends superagent.Response { + } + } + + export = supertest; +} \ No newline at end of file diff --git a/typings/tsd.d.ts b/typings/tsd.d.ts deleted file mode 100644 index 1bf038c..0000000 --- a/typings/tsd.d.ts +++ /dev/null @@ -1,12 +0,0 @@ - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/typings/yadda/yadda.d.ts b/typings/yadda.d.ts similarity index 100% rename from typings/yadda/yadda.d.ts rename to typings/yadda.d.ts From 87032046f4adcb988fbb33f60da776eea8dfba1a Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Tue, 3 May 2016 18:52:37 +0000 Subject: [PATCH 03/13] updated all type script files to 1.8 --- examples/authentication/app.ts | 14 +- examples/authentication/resources/parent.ts | 22 +- examples/authentication/resources/sub.ts | 10 +- examples/authentication/resources/user.ts | 9 +- examples/customResource/app.ts | 13 +- examples/foods/app.ts | 15 +- examples/subresource/app.ts | 13 +- examples/subresource/resources/parent.ts | 36 +- examples/subresource/resources/ref.ts | 7 +- examples/subresource/resources/sub.ts | 10 +- src/authentication.ts | 42 +- src/authorizedResource.ts | 230 ++++++----- src/authorizedSubResource.ts | 15 +- src/index.ts | 29 +- src/resource.ts | 358 +++++++++--------- src/subResource.ts | 12 +- src/userResource.ts | 15 +- test/authentication/authentication.spec.ts | 2 +- .../definitions/authentication.steps.ts | 15 +- 19 files changed, 416 insertions(+), 451 deletions(-) diff --git a/examples/authentication/app.ts b/examples/authentication/app.ts index dd25642..c94ecb2 100644 --- a/examples/authentication/app.ts +++ b/examples/authentication/app.ts @@ -1,7 +1,9 @@ -import express = require('express'); -import restIO = require('../../src/index'); -import mongoose = require('mongoose'); -var app = express(); +import * as express from 'express'; +import RestIO from '../../src/index'; +import * as mongoose from 'mongoose'; + +export const app = express(); + var port = 4000; var db = new mongoose.Mongoose(); @@ -11,7 +13,7 @@ var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + mongoUrl += (process.env.DB || 'auth'); db.connect(mongoUrl); -new restIO(app, { +new RestIO(app, { db: db, resources: __dirname + '/resources' }); @@ -22,5 +24,3 @@ process.env.REST_IO_AES_KEY = process.env.REST_IO_AES_KEY || 'aes key which is s app.listen(port, () => { console.log('Server has started under port: ' + port); }); - -export = app; diff --git a/examples/authentication/resources/parent.ts b/examples/authentication/resources/parent.ts index 4779037..060c5d5 100644 --- a/examples/authentication/resources/parent.ts +++ b/examples/authentication/resources/parent.ts @@ -1,13 +1,11 @@ -import {AuthorizedResource} from '../../../src/authorizedResource'; +import AuthorizedResource from '../../../src/authorizedResource'; -var parentResource = new AuthorizedResource({ - name: 'parent', - model: { - name: String, - subs: [{ - name: String - }] - } -}); - -export = parentResource; \ No newline at end of file +export const parentResource = new AuthorizedResource({ + name: 'parent', + model: { + name: String, + subs: [{ + name: String + }] + } +}); diff --git a/examples/authentication/resources/sub.ts b/examples/authentication/resources/sub.ts index de27c0d..0f6c217 100644 --- a/examples/authentication/resources/sub.ts +++ b/examples/authentication/resources/sub.ts @@ -1,9 +1,7 @@ -import AuthorizedSubResource = require('../../../src/authorizedSubResource'); -import parent = require('./parent'); +import AuthorizedSubResource from '../../../src/authorizedSubResource'; +import { parentResource } from './parent'; -var sub = new AuthorizedSubResource({ +export const sub = new AuthorizedSubResource({ name: 'sub', - parentResource: parent + parentResource: parentResource }); - -module.exports = sub; diff --git a/examples/authentication/resources/user.ts b/examples/authentication/resources/user.ts index 5e96c82..56c3e5e 100644 --- a/examples/authentication/resources/user.ts +++ b/examples/authentication/resources/user.ts @@ -1,8 +1,7 @@ -import mongoose = require('mongoose'); -import Schema = mongoose.Schema; -import UserResource = require('../../../src/userResource'); +import { Schema } from 'mongoose'; +import UserResource from '../../../src/userResource'; -var user = new UserResource({ +export const user = new UserResource({ name: 'user', model: { userName: String, @@ -13,5 +12,3 @@ var user = new UserResource({ }] } }); - -export = user; diff --git a/examples/customResource/app.ts b/examples/customResource/app.ts index 32a841e..01bf0bd 100644 --- a/examples/customResource/app.ts +++ b/examples/customResource/app.ts @@ -1,7 +1,8 @@ -import express = require('express'); -import restIO = require('../../src/index'); -import mongoose = require('mongoose'); -var app = express(); +import * as express from 'express'; +import RestIO from '../../src/index'; +import * as mongoose from 'mongoose'; +export const app = express(); + var port = 3030; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; @@ -11,7 +12,7 @@ var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'customResource'); db.connect(mongoUrl); -new restIO(app, { +new RestIO(app, { db: db, resources: __dirname + '/resources' }); @@ -19,5 +20,3 @@ new restIO(app, { app.listen(port, () => { console.log('Server has started under port: ' + port); }); - -export = app; diff --git a/examples/foods/app.ts b/examples/foods/app.ts index 9896510..abcf8d8 100644 --- a/examples/foods/app.ts +++ b/examples/foods/app.ts @@ -1,9 +1,12 @@ -import express = require('express'); -import restIO = require('../../src/index'); -import mongoose = require('mongoose'); -var app = express(); +import * as express from 'express'; +import RestIO from '../../src/index'; +import * as mongoose from 'mongoose'; + +export const app = express(); + var port = 3000; -new restIO(app, { + +new RestIO(app, { resources: __dirname + '/resources' }); @@ -17,5 +20,3 @@ mongoose.connect(mongoUrl); app.listen(port, () => { console.log('Server has started under port: ' + port); }); - -export = app; diff --git a/examples/subresource/app.ts b/examples/subresource/app.ts index 6126623..5a3a49f 100644 --- a/examples/subresource/app.ts +++ b/examples/subresource/app.ts @@ -1,7 +1,8 @@ -import express = require('express'); -import restIO = require('../../src/index'); -import mongoose = require('mongoose'); -var app = express(); +import * as express from 'express'; +import RestIO from '../../src/index'; +import * as mongoose from 'mongoose'; + +export const app = express(); var port = 5050; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; @@ -11,7 +12,7 @@ var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'sub'); db.connect(mongoUrl); -new restIO(app, { +new RestIO(app, { db: db, resources: __dirname + '/resources' }); @@ -19,5 +20,3 @@ new restIO(app, { app.listen(port, () => { console.log('Server has started under port: ' + port); }); - -export = app; diff --git a/examples/subresource/resources/parent.ts b/examples/subresource/resources/parent.ts index 38dc935..7d88e26 100644 --- a/examples/subresource/resources/parent.ts +++ b/examples/subresource/resources/parent.ts @@ -1,20 +1,16 @@ -import mongoose = require('mongoose'); -import Schema = mongoose.Schema; -import resource = require('../../../src/resource'); -import Resource = resource.Resource; - -var parentResource = new Resource({ - name: 'parent', - model: { - name: String, - subs: [{ - name: String, - ref: { - type: Schema.Types.ObjectId, - ref: 'Ref' - } - }] - } -}); - -export = parentResource; \ No newline at end of file +import { Schema } from 'mongoose'; +import { Resource } from '../../../src/resource'; + +export const parentResource = new Resource({ + name: 'parent', + model: { + name: String, + subs: [{ + name: String, + ref: { + type: Schema.Types.ObjectId, + ref: 'Ref' + } + }] + } +}); diff --git a/examples/subresource/resources/ref.ts b/examples/subresource/resources/ref.ts index 4f1a535..2572d8d 100644 --- a/examples/subresource/resources/ref.ts +++ b/examples/subresource/resources/ref.ts @@ -1,11 +1,8 @@ -import resource = require('../../../src/resource'); -import Resource = resource.Resource; +import { Resource } from '../../../src/resource'; -var ref = new Resource({ +export const ref = new Resource({ name: 'ref', model: { name: String } }); - -export = ref; diff --git a/examples/subresource/resources/sub.ts b/examples/subresource/resources/sub.ts index a94cca7..bd360d5 100644 --- a/examples/subresource/resources/sub.ts +++ b/examples/subresource/resources/sub.ts @@ -1,10 +1,8 @@ -import SubResource = require('../../../src/subResource'); -import parent = require('./parent'); +import SubResource from '../../../src/subResource'; +import { parentResource } from './parent'; -var sub = new SubResource({ +export const sub = new SubResource({ name: 'sub', - parentResource: parent, + parentResource, populate: 'subs.ref' }); - -module.exports = sub; diff --git a/src/authentication.ts b/src/authentication.ts index ff53613..8d3e1b7 100644 --- a/src/authentication.ts +++ b/src/authentication.ts @@ -1,29 +1,25 @@ -module authentication { - var CryptoJS = require('crypto-js'); - var HMAC = require('crypto-js/hmac-sha256'); - var AES = require('crypto-js/aes'); +const CryptoJS = require('crypto-js'); +const { HmacSHA256, AES, enc } = CryptoJS; - export function encryptPassword(password: string) { - return HMAC(password, process.env.REST_IO_HMAC_KEY).toString(); - } +export function encryptPassword(password: string) { + return HmacSHA256(password, process.env.REST_IO_HMAC_KEY).toString(); +} - export function createAuthToken(userId: string) { - var authToken = AES.encrypt(userId + ';' + - new Date().getTime(), process.env.REST_IO_AES_KEY); - return authToken.toString(); - } +export function createAuthToken(userId: string) { + var authToken = AES.encrypt(userId + ';' + + new Date().getTime(), process.env.REST_IO_AES_KEY); + return authToken.toString(); +} - export function decryptAuthToken(authToken: string) { - var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); - var brokenMessage = decryptedMessage.toString(CryptoJS.enc.Utf8).split(';'); - if (brokenMessage.length !== 2) { - throw new Error('corrupt auth token'); - } - return { - id: brokenMessage[0], - createdAt: new Date(parseInt(brokenMessage[1], 10)) - }; +export function decryptAuthToken(authToken: string) { + var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); + const { id, createdAt } = decryptedMessage.toString(enc.Utf8).split(';'); + if (!id || !createdAt) { + throw new Error('corrupt auth token'); } + return { + id, + createdAt: new Date(parseInt(createdAt, 10)) + }; } -export = authentication; diff --git a/src/authorizedResource.ts b/src/authorizedResource.ts index 7db2f61..d66a3f6 100644 --- a/src/authorizedResource.ts +++ b/src/authorizedResource.ts @@ -1,138 +1,132 @@ -import {Resource, IResource} from './resource'; -import {Request, Router, Application, Response} from 'express'; - -import auth = require('./authentication'); -import mongoose = require('mongoose'); - -module authorizedResource { - - export var ROLES = { - USER: 'USER', - SUPER_USER: 'SUPER_USER', - MODERATOR: 'MODERATOR', - ADMIN: 'ADMIN' +import { Resource, IResource } from './resource'; +import { Request, Router, Application, Response } from 'express'; + +import * as auth from './authentication'; +import * as mongoose from 'mongoose'; + +export const ROLES = { + USER: 'USER', + SUPER_USER: 'SUPER_USER', + MODERATOR: 'MODERATOR', + ADMIN: 'ADMIN' +}; + +export default class AuthorizedResource extends Resource { + methodAccess: IMethodAccess; + maxDays: number = 7; + + permissions: IMethodAccess = { + getAll: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], + getById: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], + create: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], + update: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], + del: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN] }; - export class AuthorizedResource extends Resource { - methodAccess: IMethodAccess; - maxDays: number = 7; - - permissions: IMethodAccess = { - getAll: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], - getById: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], - create: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], - update: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], - del: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN] - }; - - isTokenExpired(createdAt: Date) { - var maxTokenLifeTime = new Date(); - maxTokenLifeTime.setDate(maxTokenLifeTime.getDate() - this.maxDays); - return createdAt < maxTokenLifeTime; - } + isTokenExpired(createdAt: Date) { + var maxTokenLifeTime = new Date(); + maxTokenLifeTime.setDate(maxTokenLifeTime.getDate() - this.maxDays); + return createdAt < maxTokenLifeTime; + } - getRoles(id: string) { - return this.db.model('User') - .findById(id) - .populate('roles') - .exec(); - } + getRoles(id: string) { + return this.db.model('User') + .findById(id) + .populate('roles') + .exec(); + } - hasAuthorizedRole(roles: Array, authorizedRoles: Array) { - var hasRole = false; - roles.forEach((role) => { - authorizedRoles.forEach((authRole: string) => { - if (role.name === authRole) { - hasRole = true; - } - }); + hasAuthorizedRole(roles: Array, authorizedRoles: Array) { + var hasRole = false; + roles.forEach((role) => { + authorizedRoles.forEach((authRole: string) => { + if (role.name === authRole) { + hasRole = true; + } }); - return hasRole; - } - - hasAccessRightsDefined(req: Request, authorizedRoles: Array) { - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); - if (authorizedRoles.length === 0) { - promise.resolve(null, null); - return promise; - } - } + }); + return hasRole; + } - isAuthorized(req: Request, authorizedRoles: Array) { - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); - if (authorizedRoles.length === 0) { - promise.resolve(null, null); - return promise; - } else if (!authToken) { - promise.resolve(new Error('no token found'), null); - return promise; - } - var tokenDetails = auth.decryptAuthToken(authToken); - return this.getRoles(tokenDetails.id) - .then((user: any) => { - if (this.isTokenExpired(tokenDetails.createdAt)) { - throw new Error('token expired'); - } - return user.roles; - }) - .then((roles: Array) => { - if (!this.hasAuthorizedRole(roles, authorizedRoles)) { - throw new Error('unauthorized'); - } - }); + hasAccessRightsDefined(req: Request, authorizedRoles: Array) { + var promise = new mongoose.Promise(); + var authToken = req.header('Authorization'); + if (authorizedRoles.length === 0) { + promise.resolve(null, null); + return promise; } + } - sendUnauthorized(error: Error, res: Response) { - res.status(401).send('unauthorized'); + isAuthorized(req: Request, authorizedRoles: Array) { + var promise = new mongoose.Promise(); + var authToken = req.header('Authorization'); + if (authorizedRoles.length === 0) { + promise.resolve(null, null); + return promise; + } else if (!authToken) { + promise.resolve(new Error('no token found'), null); + return promise; } + var tokenDetails = auth.decryptAuthToken(authToken); + return this.getRoles(tokenDetails.id) + .then((user: any) => { + if (this.isTokenExpired(tokenDetails.createdAt)) { + throw new Error('token expired'); + } + return user.roles; + }) + .then((roles: Array) => { + if (!this.hasAuthorizedRole(roles, authorizedRoles)) { + throw new Error('unauthorized'); + } + }); + } - baseGetAll = super.getAll; - baseGetById = super.getById; - baseCreate = super.create; - baseUpdate = super.update; - baseDel = super.del; - - getAll(req: Request, res: Response) { - this.isAuthorized(req, this.permissions.getAll) - .then(() => super.getAll(req, res), - (err) => this.sendUnauthorized(err, res)); - } + sendUnauthorized(error: Error, res: Response) { + res.status(401).send('unauthorized'); + } - getById(req: Request, res: Response) { - this.isAuthorized(req, this.permissions.getById) - .then(() => super.getById(req, res), - (err) => this.sendUnauthorized(err, res)); - } + baseGetAll = super.getAll; + baseGetById = super.getById; + baseCreate = super.create; + baseUpdate = super.update; + baseDel = super.del; - create(req: Request, res: Response) { - this.isAuthorized(req, this.permissions.create) - .then(() => super.create(req, res), - (err) => this.sendUnauthorized(err, res)); - } + getAll(req: Request, res: Response) { + this.isAuthorized(req, this.permissions.getAll) + .then(() => super.getAll(req, res), + (err) => this.sendUnauthorized(err, res)); + } - update(req: Request, res: Response) { - this.isAuthorized(req, this.permissions.update) - .then(() => super.update(req, res), - (err) => this.sendUnauthorized(err, res)); - } + getById(req: Request, res: Response) { + this.isAuthorized(req, this.permissions.getById) + .then(() => super.getById(req, res), + (err) => this.sendUnauthorized(err, res)); + } - del(req: Request, res: Response) { - this.isAuthorized(req, this.permissions.del) - .then(() => super.del(req, res), - (err) => this.sendUnauthorized(err, res)); - } + create(req: Request, res: Response) { + this.isAuthorized(req, this.permissions.create) + .then(() => super.create(req, res), + (err) => this.sendUnauthorized(err, res)); } - export interface IMethodAccess { - getAll: Array; - getById: Array; - create: Array; - update: Array; - del: Array; + update(req: Request, res: Response) { + this.isAuthorized(req, this.permissions.update) + .then(() => super.update(req, res), + (err) => this.sendUnauthorized(err, res)); } + del(req: Request, res: Response) { + this.isAuthorized(req, this.permissions.del) + .then(() => super.del(req, res), + (err) => this.sendUnauthorized(err, res)); + } } -export = authorizedResource; +export interface IMethodAccess { + getAll: Array; + getById: Array; + create: Array; + update: Array; + del: Array; +} diff --git a/src/authorizedSubResource.ts b/src/authorizedSubResource.ts index f1b6a3a..61bdd20 100644 --- a/src/authorizedSubResource.ts +++ b/src/authorizedSubResource.ts @@ -1,9 +1,10 @@ -import {AuthorizedResource} from './authorizedResource'; -import {Resource, IResource} from './resource'; -import {Request, Response} from 'express'; -import SubResource = require('./subResource'); +import AuthorizedResource from './authorizedResource'; +import { Resource, IResource } from './resource'; +import { Request, Response } from 'express'; +import SubResource from './subResource'; +import { Model, Document } from 'mongoose'; -class AuthorizedSubResource extends AuthorizedResource { +export default class AuthorizedSubResource extends AuthorizedResource { constructor(subResDef: ISubResource) { var resDef = { name: null, @@ -69,11 +70,9 @@ class AuthorizedSubResource extends AuthorizedResource { } } -interface ISubResource { +export interface ISubResource { name: string; plural?: string; parentResource: Resource; populate?: string; } - -export = AuthorizedSubResource; diff --git a/src/index.ts b/src/index.ts index e8b55e0..bcca426 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,18 +1,19 @@ -import {Mongoose} from 'mongoose'; -import express = require('express'); -import resource = require('./resource'); -import Resource = resource.Resource; -import bodyParser = require('body-parser'); -import UserResource = require('./userResource'); -import authorizedResource = require('./authorizedResource'); -import SubResource = require('./subResource'); -import AuthorizedSubResource = require('./authorizedSubResource'); -var autoloader = require('auto-loader'); +import { Mongoose } from 'mongoose'; +import * as express from 'express'; +import * as resource from './resource'; +import { Resource } from './resource'; +import * as bodyParser from 'body-parser'; +import UserResource from './userResource'; +import * as authorizedResource from './authorizedResource'; +import AuthorizedResource from './authorizedResource'; +import SubResource from './subResource'; +import AuthorizedSubResource from './authorizedSubResource'; +const autoloader = require('auto-loader'); -class RestIO { +export default class RestIO { static authorizedResource = authorizedResource; static UserResource = UserResource; - static AuthorizedResource = authorizedResource.AuthorizedResource; + static AuthorizedResource = AuthorizedResource; static SubResource = SubResource; static AuthorizedSubResource = AuthorizedSubResource; static Resource = Resource; @@ -33,9 +34,7 @@ class RestIO { } } -interface IRestIOConfig { +export interface IRestIOConfig { resources: string; db?: Mongoose; } - -export = RestIO; diff --git a/src/resource.ts b/src/resource.ts index 5ab8f3c..1afe152 100644 --- a/src/resource.ts +++ b/src/resource.ts @@ -1,212 +1,208 @@ -import express = require('express'); -import {Request, Router, Application, Response} from 'express'; - -import mongoose = require('mongoose'); -import {Mongoose, Schema, Model, Document, Types} from 'mongoose'; -import ObjectId = Types.ObjectId; - -import pluralize = require('pluralize'); - -module Resource { - // The app reference it used to register params. - var app; - var db: Mongoose; - - export class Resource { - static BASE_URL = '/api'; - - baseUrl: string = Resource.BASE_URL; - url: string; - parameterizedUrl: string; - model: Model; - resDef: IResource; - parentResource: Resource; - router: Router; - app: Application; - db: Mongoose; - paramId: string; - parentRef: string; - populate: string; - - constructor(resDef: IResource) { - if (!!resDef.parentResource) { - this.parentResource = resDef.parentResource; - this.baseUrl = resDef.parentResource.parameterizedUrl; - this.parentRef = resDef.parentRef || resDef.parentResource.resDef.name; - } - this.app = app; - this.db = db; - this.populate = resDef.populate; - this.model = this.createModel(resDef); - this.resDef = resDef; - this.setupRoutes(); - } +import * as express from 'express'; +import { Request, Router, Application, Response } from 'express'; + +import * as mongoose from 'mongoose'; +import { Mongoose, Schema, Model, Document, Types } from 'mongoose'; +const { ObjectId } = Types; + +import * as pluralize from 'pluralize'; + +// The app reference it used to register params. +var app; +var db: Mongoose; + +export class Resource { + static BASE_URL = '/api'; + + baseUrl: string = Resource.BASE_URL; + url: string; + parameterizedUrl: string; + model: Model; + resDef: IResource; + parentResource: Resource; + router: Router; + app: Application; + db: Mongoose; + paramId: string; + parentRef: string; + populate: string; + + constructor(resDef: IResource) { + if (!!resDef.parentResource) { + this.parentResource = resDef.parentResource; + this.baseUrl = resDef.parentResource.parameterizedUrl; + this.parentRef = resDef.parentRef || resDef.parentResource.resDef.name; + } + this.app = app; + this.db = db; + this.populate = resDef.populate; + this.model = this.createModel(resDef); + this.resDef = resDef; + this.setupRoutes(); + } - createModel(resDef: IResource) { - var schema = new Schema(resDef.model); - return this.db.model(this.toClassName(resDef.name), schema); - } + createModel(resDef: IResource) { + var schema = new Schema(resDef.model); + return this.db.model(this.toClassName(resDef.name), schema); + } - toClassName(name: string) { - return name.replace(/\w\S*/g, (namePart) => { - return namePart.charAt(0).toUpperCase() + namePart.substr(1).toLowerCase(); - }); - } + toClassName(name: string) { + return name.replace(/\w\S*/g, (namePart) => { + return namePart.charAt(0).toUpperCase() + namePart.substr(1).toLowerCase(); + }); + } - setupRoutes() { - this.url = `${this.baseUrl}/`; - this.resDef.plural = this.resDef.plural || pluralize.plural(this.resDef.name); - this.url += this.resDef.plural; - - this.paramId = `${this.resDef.name}Id`; - app.param(this.paramId, String); - this.parameterizedUrl = `${this.url}/:${this.paramId}`; - - this.router = express.Router(); - this.router - .route(this.url) - .get((req, res) => this.getAll(req, res)) - .post((req, res) => this.create(req, res)); - this.router - .route(this.parameterizedUrl) - .get((req, res) => this.getById(req, res)) - .put((req, res) => this.update(req, res)) - .delete((req, res) => this.del(req, res)); - this.setupRecursiveRoutes(); - app.use(this.router); - } + setupRoutes() { + this.url = `${this.baseUrl}/`; + this.resDef.plural = this.resDef.plural || pluralize.plural(this.resDef.name); + this.url += this.resDef.plural; + + this.paramId = `${this.resDef.name}Id`; + app.param(this.paramId, String); + this.parameterizedUrl = `${this.url}/:${this.paramId}`; + + this.router = express.Router(); + this.router + .route(this.url) + .get((req, res) => this.getAll(req, res)) + .post((req, res) => this.create(req, res)); + this.router + .route(this.parameterizedUrl) + .get((req, res) => this.getById(req, res)) + .put((req, res) => this.update(req, res)) + .delete((req, res) => this.del(req, res)); + this.setupRecursiveRoutes(); + app.use(this.router); + } - setupRecursiveRoutes() { - var resource: Resource = this.parentResource; - if (!!resource) { - // Ensure the getter on root level - this.router.route(`${Resource.BASE_URL}/${this.resDef.plural}`) + setupRecursiveRoutes() { + var resource: Resource = this.parentResource; + if (!!resource) { + // Ensure the getter on root level + this.router.route(`${Resource.BASE_URL}/${this.resDef.plural}`) + .get((req, res) => this.getAll(req, res)); + // Setup recursively on all parent resources a getter + while (!!resource && !!resource.parentRef) { + resource = resource.parentResource; + this.router.route(`${resource.url}/${this.resDef.plural}`) .get((req, res) => this.getAll(req, res)); - // Setup recursively on all parent resources a getter - while (!!resource && !!resource.parentRef) { - resource = resource.parentResource; - this.router.route(`${resource.url}/${this.resDef.plural}`) - .get((req, res) => this.getAll(req, res)); - } } } + } - getAll(req: Request, res: Response) { - try { - var query: Object = this.buildSearchQuery(req); - var getQuery = this.model.find(query); - getQuery - .populate(this.buildPopulateQuery(req)) - .exec() - .then((result: Array) => res.send(result), - (err: Error) => this.errorHandler(err, res)); - } catch (err) { - this.errorHandler(err, res) - } + getAll(req: Request, res: Response) { + try { + var query: Object = this.buildSearchQuery(req); + var getQuery = this.model.find(query); + getQuery + .populate(this.buildPopulateQuery(req)) + .exec() + .then((result: Array) => res.send(result), + (err: Error) => this.errorHandler(err, res)); + } catch (err) { + this.errorHandler(err, res) } + } - buildPopulateQuery(req: Request) { - if (typeof req.query.populate === 'string') { - return req.query.populate; - } else { - return `${this.parentRef} ${this.populate}`; - } + buildPopulateQuery(req: Request) { + if (typeof req.query.populate === 'string') { + return req.query.populate; + } else { + return `${this.parentRef} ${this.populate}`; } + } - buildSearchQuery(req: Request) { - var query = {}; - for (var attr in req.query) { - // ignore populate attribute - if (req.query.hasOwnProperty(attr) && attr !== 'populate') { - query[attr] = this.createQuery(req.query[attr]); - } + buildSearchQuery(req: Request) { + var query = {}; + for (var attr in req.query) { + // ignore populate attribute + if (req.query.hasOwnProperty(attr) && attr !== 'populate') { + query[attr] = this.createQuery(req.query[attr]); } - this.buildParentSearch(req, query); - return query; } + this.buildParentSearch(req, query); + return query; + } - createQuery(query: string) { - try { - return JSON.parse(query); - } catch (error) { - return this.createRegex(query); - } + createQuery(query: string) { + try { + return JSON.parse(query); + } catch (error) { + return this.createRegex(query); } + } - createRegex(query: string) { - if (!query.match(/\//)) { - query = `/${query}/`; - } - var splitQuery = query.split('/'); - var modifier = splitQuery.pop(); - splitQuery.shift(); - return new RegExp(splitQuery.join('/'), modifier); + createRegex(query: string) { + if (!query.match(/\//)) { + query = `/${query}/`; } + var splitQuery = query.split('/'); + var modifier = splitQuery.pop(); + splitQuery.shift(); + return new RegExp(splitQuery.join('/'), modifier); + } - buildParentSearch(req: Request, query) { - var resource: Resource = this; - while (!!resource.parentRef) { - var id = req.params[resource.parentResource.paramId]; - if (!!id) { - query[resource.parentRef] = new ObjectId(id); - } else { - break; - } - resource = resource.parentResource; + buildParentSearch(req: Request, query) { + var resource: Resource = this; + while (!!resource.parentRef) { + var id = req.params[resource.parentResource.paramId]; + if (!!id) { + query[resource.parentRef] = new ObjectId(id); + } else { + break; } - return query; - } - - getById(req: Request, res: Response) { - var id = req.params[this.paramId]; - this.model.findById(id) - .populate(this.buildPopulateQuery(req)) - .exec() - .then((model: Document) => res.send(model), - (err: Error) => this.errorHandler(err, res)); - } - - create(req: Request, res: Response) { - this.model.create(req.body) - .then((model: Document) => res.send(model), - (err: Error) => this.errorHandler(err, res)); + resource = resource.parentResource; } + return query; + } - update(req: Request, res: Response) { - var id = req.params[this.paramId]; - this.model.findByIdAndUpdate(id, req.body) - .exec() - .then((model: Document) => res.send(model), - (err: Error) => this.errorHandler(err, res)); - } + getById(req: Request, res: Response) { + var id = req.params[this.paramId]; + this.model.findById(id) + .populate(this.buildPopulateQuery(req)) + .exec() + .then((model: Document) => res.send(model), + (err: Error) => this.errorHandler(err, res)); + } - del(req: Request, res: Response) { - var id = req.params[this.paramId]; - this.model.findByIdAndRemove(id, req.body) - .exec() - .then((model: Document) => res.send(model), - (err: Error) => this.errorHandler(err, res)); - } + create(req: Request, res: Response) { + this.model.create(req.body) + .then((model: Document) => res.send(model), + (err: Error) => this.errorHandler(err, res)); + } - errorHandler(err: Error, res: Response) { - console.log(err); - res.status(500).send('internal server error'); - } + update(req: Request, res: Response) { + var id = req.params[this.paramId]; + this.model.findByIdAndUpdate(id, req.body) + .exec() + .then((model: Document) => res.send(model), + (err: Error) => this.errorHandler(err, res)); } - export interface IResource { - name: string; - model: any; - parentRef?: string; - populate?: string; - plural?: string; - parentResource?: Resource; + del(req: Request, res: Response) { + var id = req.params[this.paramId]; + this.model.findByIdAndRemove(id, req.body) + .exec() + .then((model: Document) => res.send(model), + (err: Error) => this.errorHandler(err, res)); } - export function registerApp(registerApp, connection: Mongoose) { - app = registerApp; - db = connection || mongoose; + errorHandler(err: Error, res: Response) { + console.log(err); + res.status(500).send('internal server error'); } } -export = Resource; +export interface IResource { + name: string; + model: any; + parentRef?: string; + populate?: string; + plural?: string; + parentResource?: Resource; +} + +export function registerApp(registerApp, connection: Mongoose) { + app = registerApp; + db = connection || mongoose; +} diff --git a/src/subResource.ts b/src/subResource.ts index 7a3ae3c..1fb34df 100644 --- a/src/subResource.ts +++ b/src/subResource.ts @@ -1,8 +1,8 @@ -import {Resource, IResource} from './resource'; -import {Request, Response} from 'express'; -import {Document} from 'mongoose'; +import { Resource, IResource } from './resource'; +import { Request, Response } from 'express'; +import { Document, Model } from 'mongoose'; -class SubResource extends Resource { +export default class SubResource extends Resource { constructor(subResDef: ISubResource) { var resDef = { name: null, @@ -101,11 +101,9 @@ class SubResource extends Resource { } } -interface ISubResource { +export interface ISubResource { name: string; plural?: string; parentResource: Resource; populate?: string; } - -export = SubResource; diff --git a/src/userResource.ts b/src/userResource.ts index a39f027..bd311ec 100644 --- a/src/userResource.ts +++ b/src/userResource.ts @@ -1,10 +1,11 @@ -import {AuthorizedResource, IMethodAccess, ROLES} from './authorizedResource'; -import {Resource, IResource} from './resource'; -import {Request, Router, Application, Response} from 'express'; -import {Model, Schema} from 'mongoose'; -import auth = require('./authentication'); +import AuthorizedResource from './authorizedResource'; +import { IMethodAccess, ROLES } from './authorizedResource'; +import { Resource, IResource } from './resource'; +import { Request, Router, Application, Response } from 'express'; +import { Model, Document, Schema } from 'mongoose'; +import * as auth from './authentication'; -class UserResource extends AuthorizedResource { +export default class UserResource extends AuthorizedResource { permissions: IMethodAccess = { getAll: [ROLES.USER, ROLES.SUPER_USER, ROLES.MODERATOR, ROLES.ADMIN], @@ -97,5 +98,3 @@ class UserResource extends AuthorizedResource { }, () => this.sendUnauthorized(new Error('cannot perform login'), res)); } } - -export = UserResource; diff --git a/test/authentication/authentication.spec.ts b/test/authentication/authentication.spec.ts index 776936f..925be1d 100644 --- a/test/authentication/authentication.spec.ts +++ b/test/authentication/authentication.spec.ts @@ -7,7 +7,7 @@ process.env.DB = 'authTest'; require('../../examples/authentication/app'); var library = require('./definitions/authentication.steps'); -import user = require('../../examples/authentication/resources/user'); +import { user } from '../../examples/authentication/resources/user'; new Yadda.FeatureFileSearch('test/authentication').each(function(file) { featureFile(file, function(feature) { diff --git a/test/authentication/definitions/authentication.steps.ts b/test/authentication/definitions/authentication.steps.ts index 00ae00f..f839949 100644 --- a/test/authentication/definitions/authentication.steps.ts +++ b/test/authentication/definitions/authentication.steps.ts @@ -9,9 +9,10 @@ import ObjectId = mongoose.Types.ObjectId; import auth = require('../../../src/authentication'); -import supertest = require('supertest'); +import { SuperTest, Response } from 'supertest'; +const supertest = require('supertest'); -import user = require('../../../examples/authentication/resources/user'); +import { user } from '../../../examples/authentication/resources/user'; function createIdBasedOnName(name: string) { var id = convertToHex(name); @@ -156,7 +157,7 @@ library }) .then('I expect to be logged in', (done) => { this.request - .end((req: supertest.SuperTest, res: supertest.Response) => { + .end((req: SuperTest, res: Response) => { expect(res.status).to.equal(200); expect(res.body.authToken).to.not.be.empty; done(); @@ -164,7 +165,7 @@ library }) .then('I expect to be unauthorized', (done) => { this.request - .end((req: supertest.SuperTest, res: supertest.Response) => { + .end((req: SuperTest, res: Response) => { expect(res.status).to.equal(401); expect(res.text).to.equal('unauthorized'); done(); @@ -172,7 +173,7 @@ library }) .then('I can see the user details', (done) => { this.request - .end((req: supertest.SuperTest, res: supertest.Response) => { + .end((req: SuperTest, res: Response) => { expect(res.status).to.equal(200); expect(res.body).to.be.ok; done(); @@ -180,7 +181,7 @@ library }) .then('I can not see the user details', (done) => { this.request - .end((req: supertest.SuperTest, res: supertest.Response) => { + .end((req: SuperTest, res: Response) => { expect(res.status).to.equal(401); expect(res.text).to.equal('unauthorized'); done(); @@ -188,7 +189,7 @@ library }) .then('the new user is created', (done) => { this.request - .end((req: supertest.SuperTest, res: supertest.Response) => { + .end((req: SuperTest, res: Response) => { expect(res.status).to.equal(200); expect(res.body._id).to.be.ok; done(); From 2c874c520822c35898079ce1f54b14c0a93ea903 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Tue, 3 May 2016 18:53:19 +0000 Subject: [PATCH 04/13] compiled new ts files --- lib/examples/authentication/app.js | 10 +- .../authentication/resources/parent.js | 4 +- lib/examples/authentication/resources/sub.js | 10 +- lib/examples/authentication/resources/user.js | 11 +- lib/examples/customResource/app.js | 10 +- .../resourceDefinitions/boomerangResource.js | 6 +- .../customResource/resources/boomerang.js | 1 + lib/examples/foods/app.js | 10 +- lib/examples/foods/resources/dish.js | 1 + lib/examples/foods/resources/food.js | 1 + lib/examples/foods/resources/list.js | 1 + lib/examples/subresource/app.js | 10 +- lib/examples/subresource/resources/parent.js | 12 +- lib/examples/subresource/resources/ref.js | 7 +- lib/examples/subresource/resources/sub.js | 10 +- lib/src/authentication.js | 52 ++- lib/src/authorizedResource.js | 223 ++++++------ lib/src/authorizedSubResource.js | 29 +- lib/src/index.js | 25 +- lib/src/resource.js | 317 +++++++++--------- lib/src/subResource.js | 9 +- lib/src/userResource.js | 18 +- .../authentication/authentication.spec.js | 5 +- .../authentication/authentication.specs.js | 20 -- .../definitions/authentication.steps.js | 5 +- .../definitions/customResource.steps.js | 1 + lib/test/foods/definitions/foods.steps.js | 1 + lib/test/subresource/definitions/sub.steps.js | 1 + 28 files changed, 396 insertions(+), 414 deletions(-) delete mode 100644 lib/test/authentication/authentication.specs.js diff --git a/lib/examples/authentication/app.js b/lib/examples/authentication/app.js index 00fa766..5d111b3 100644 --- a/lib/examples/authentication/app.js +++ b/lib/examples/authentication/app.js @@ -1,20 +1,20 @@ +"use strict"; var express = require('express'); -var restIO = require('../../src/index'); +var index_1 = require('../../src/index'); var mongoose = require('mongoose'); -var app = express(); +exports.app = express(); var port = 4000; var db = new mongoose.Mongoose(); var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; mongoUrl += (process.env.DB || 'auth'); db.connect(mongoUrl); -new restIO(app, { +new index_1.default(exports.app, { db: db, resources: __dirname + '/resources' }); process.env.REST_IO_HMAC_KEY = process.env.REST_IO_HMAC_KEY || 'hmac key which set via js to demo'; process.env.REST_IO_AES_KEY = process.env.REST_IO_AES_KEY || 'aes key which is set via js to demo'; -app.listen(port, function () { +exports.app.listen(port, function () { console.log('Server has started under port: ' + port); }); -module.exports = app; diff --git a/lib/examples/authentication/resources/parent.js b/lib/examples/authentication/resources/parent.js index 7eb66d8..e2d567f 100644 --- a/lib/examples/authentication/resources/parent.js +++ b/lib/examples/authentication/resources/parent.js @@ -1,5 +1,6 @@ +"use strict"; var authorizedResource_1 = require('../../../src/authorizedResource'); -var parentResource = new authorizedResource_1.AuthorizedResource({ +exports.parentResource = new authorizedResource_1.default({ name: 'parent', model: { name: String, @@ -8,4 +9,3 @@ var parentResource = new authorizedResource_1.AuthorizedResource({ }] } }); -module.exports = parentResource; diff --git a/lib/examples/authentication/resources/sub.js b/lib/examples/authentication/resources/sub.js index 9cd97dc..73121b5 100644 --- a/lib/examples/authentication/resources/sub.js +++ b/lib/examples/authentication/resources/sub.js @@ -1,7 +1,7 @@ -var AuthorizedSubResource = require('../../../src/authorizedSubResource'); -var parent = require('./parent'); -var sub = new AuthorizedSubResource({ +"use strict"; +var authorizedSubResource_1 = require('../../../src/authorizedSubResource'); +var parent_1 = require('./parent'); +exports.sub = new authorizedSubResource_1.default({ name: 'sub', - parentResource: parent + parentResource: parent_1.parentResource }); -module.exports = sub; diff --git a/lib/examples/authentication/resources/user.js b/lib/examples/authentication/resources/user.js index 3e41b6c..29e03ed 100644 --- a/lib/examples/authentication/resources/user.js +++ b/lib/examples/authentication/resources/user.js @@ -1,15 +1,14 @@ -var mongoose = require('mongoose'); -var Schema = mongoose.Schema; -var UserResource = require('../../../src/userResource'); -var user = new UserResource({ +"use strict"; +var mongoose_1 = require('mongoose'); +var userResource_1 = require('../../../src/userResource'); +exports.user = new userResource_1.default({ name: 'user', model: { userName: String, password: String, roles: [{ - type: Schema.Types.ObjectId, + type: mongoose_1.Schema.Types.ObjectId, ref: 'Role' }] } }); -module.exports = user; diff --git a/lib/examples/customResource/app.js b/lib/examples/customResource/app.js index 0c6b2d8..9af2903 100644 --- a/lib/examples/customResource/app.js +++ b/lib/examples/customResource/app.js @@ -1,18 +1,18 @@ +"use strict"; var express = require('express'); -var restIO = require('../../src/index'); +var index_1 = require('../../src/index'); var mongoose = require('mongoose'); -var app = express(); +exports.app = express(); var port = 3030; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'customResource'); db.connect(mongoUrl); -new restIO(app, { +new index_1.default(exports.app, { db: db, resources: __dirname + '/resources' }); -app.listen(port, function () { +exports.app.listen(port, function () { console.log('Server has started under port: ' + port); }); -module.exports = app; diff --git a/lib/examples/customResource/resourceDefinitions/boomerangResource.js b/lib/examples/customResource/resourceDefinitions/boomerangResource.js index 5bf8fe7..09d5d30 100644 --- a/lib/examples/customResource/resourceDefinitions/boomerangResource.js +++ b/lib/examples/customResource/resourceDefinitions/boomerangResource.js @@ -1,8 +1,8 @@ +"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var resource = require('../../../src/resource'); var Resource = resource.Resource; @@ -34,5 +34,5 @@ var BoomerangResource = (function (_super) { }); }; return BoomerangResource; -})(Resource); +}(Resource)); module.exports = BoomerangResource; diff --git a/lib/examples/customResource/resources/boomerang.js b/lib/examples/customResource/resources/boomerang.js index 0997373..4a15f02 100644 --- a/lib/examples/customResource/resources/boomerang.js +++ b/lib/examples/customResource/resources/boomerang.js @@ -1,3 +1,4 @@ +"use strict"; var BoomerangResource = require('../resourceDefinitions/boomerangResource'); var boomerang = new BoomerangResource({ name: 'boomerang', diff --git a/lib/examples/foods/app.js b/lib/examples/foods/app.js index c1e165f..97e6399 100644 --- a/lib/examples/foods/app.js +++ b/lib/examples/foods/app.js @@ -1,16 +1,16 @@ +"use strict"; var express = require('express'); -var restIO = require('../../src/index'); +var index_1 = require('../../src/index'); var mongoose = require('mongoose'); -var app = express(); +exports.app = express(); var port = 3000; -new restIO(app, { +new index_1.default(exports.app, { resources: __dirname + '/resources' }); var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; mongoUrl += (process.env.DB || 'foods'); mongoose.connect(mongoUrl); -app.listen(port, function () { +exports.app.listen(port, function () { console.log('Server has started under port: ' + port); }); -module.exports = app; diff --git a/lib/examples/foods/resources/dish.js b/lib/examples/foods/resources/dish.js index 1e8dccb..8ff0937 100644 --- a/lib/examples/foods/resources/dish.js +++ b/lib/examples/foods/resources/dish.js @@ -1,3 +1,4 @@ +"use strict"; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var resource = require('../../../src/resource'); diff --git a/lib/examples/foods/resources/food.js b/lib/examples/foods/resources/food.js index f983e03..413e137 100644 --- a/lib/examples/foods/resources/food.js +++ b/lib/examples/foods/resources/food.js @@ -1,3 +1,4 @@ +"use strict"; var resource = require('../../../src/resource'); var Resource = resource.Resource; var foodResource = new Resource({ diff --git a/lib/examples/foods/resources/list.js b/lib/examples/foods/resources/list.js index 92d1821..8b80bee 100644 --- a/lib/examples/foods/resources/list.js +++ b/lib/examples/foods/resources/list.js @@ -1,3 +1,4 @@ +"use strict"; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var resource = require('../../../src/resource'); diff --git a/lib/examples/subresource/app.js b/lib/examples/subresource/app.js index 0e3a603..7028ed1 100644 --- a/lib/examples/subresource/app.js +++ b/lib/examples/subresource/app.js @@ -1,18 +1,18 @@ +"use strict"; var express = require('express'); -var restIO = require('../../src/index'); +var index_1 = require('../../src/index'); var mongoose = require('mongoose'); -var app = express(); +exports.app = express(); var port = 5050; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'sub'); db.connect(mongoUrl); -new restIO(app, { +new index_1.default(exports.app, { db: db, resources: __dirname + '/resources' }); -app.listen(port, function () { +exports.app.listen(port, function () { console.log('Server has started under port: ' + port); }); -module.exports = app; diff --git a/lib/examples/subresource/resources/parent.js b/lib/examples/subresource/resources/parent.js index 75034af..626086d 100644 --- a/lib/examples/subresource/resources/parent.js +++ b/lib/examples/subresource/resources/parent.js @@ -1,18 +1,16 @@ -var mongoose = require('mongoose'); -var Schema = mongoose.Schema; -var resource = require('../../../src/resource'); -var Resource = resource.Resource; -var parentResource = new Resource({ +"use strict"; +var mongoose_1 = require('mongoose'); +var resource_1 = require('../../../src/resource'); +exports.parentResource = new resource_1.Resource({ name: 'parent', model: { name: String, subs: [{ name: String, ref: { - type: Schema.Types.ObjectId, + type: mongoose_1.Schema.Types.ObjectId, ref: 'Ref' } }] } }); -module.exports = parentResource; diff --git a/lib/examples/subresource/resources/ref.js b/lib/examples/subresource/resources/ref.js index 56e9513..6b7f07f 100644 --- a/lib/examples/subresource/resources/ref.js +++ b/lib/examples/subresource/resources/ref.js @@ -1,9 +1,8 @@ -var resource = require('../../../src/resource'); -var Resource = resource.Resource; -var ref = new Resource({ +"use strict"; +var resource_1 = require('../../../src/resource'); +exports.ref = new resource_1.Resource({ name: 'ref', model: { name: String } }); -module.exports = ref; diff --git a/lib/examples/subresource/resources/sub.js b/lib/examples/subresource/resources/sub.js index b9609f9..528482f 100644 --- a/lib/examples/subresource/resources/sub.js +++ b/lib/examples/subresource/resources/sub.js @@ -1,8 +1,8 @@ -var SubResource = require('../../../src/subResource'); -var parent = require('./parent'); -var sub = new SubResource({ +"use strict"; +var subResource_1 = require('../../../src/subResource'); +var parent_1 = require('./parent'); +exports.sub = new subResource_1.default({ name: 'sub', - parentResource: parent, + parentResource: parent_1.parentResource, populate: 'subs.ref' }); -module.exports = sub; diff --git a/lib/src/authentication.js b/lib/src/authentication.js index 972924a..78c73d9 100644 --- a/lib/src/authentication.js +++ b/lib/src/authentication.js @@ -1,29 +1,25 @@ -var authentication; -(function (authentication) { - var CryptoJS = require('crypto-js'); - var HMAC = require('crypto-js/hmac-sha256'); - var AES = require('crypto-js/aes'); - function encryptPassword(password) { - return HMAC(password, process.env.REST_IO_HMAC_KEY).toString(); +"use strict"; +var CryptoJS = require('crypto-js'); +var HmacSHA256 = CryptoJS.HmacSHA256, AES = CryptoJS.AES, enc = CryptoJS.enc; +function encryptPassword(password) { + return HmacSHA256(password, process.env.REST_IO_HMAC_KEY).toString(); +} +exports.encryptPassword = encryptPassword; +function createAuthToken(userId) { + var authToken = AES.encrypt(userId + ';' + + new Date().getTime(), process.env.REST_IO_AES_KEY); + return authToken.toString(); +} +exports.createAuthToken = createAuthToken; +function decryptAuthToken(authToken) { + var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); + var _a = decryptedMessage.toString(enc.Utf8).split(';'), id = _a.id, createdAt = _a.createdAt; + if (!id || !createdAt) { + throw new Error('corrupt auth token'); } - authentication.encryptPassword = encryptPassword; - function createAuthToken(userId) { - var authToken = AES.encrypt(userId + ';' + - new Date().getTime(), process.env.REST_IO_AES_KEY); - return authToken.toString(); - } - authentication.createAuthToken = createAuthToken; - function decryptAuthToken(authToken) { - var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); - var brokenMessage = decryptedMessage.toString(CryptoJS.enc.Utf8).split(';'); - if (brokenMessage.length !== 2) { - throw new Error('corrupt auth token'); - } - return { - id: brokenMessage[0], - createdAt: new Date(parseInt(brokenMessage[1], 10)) - }; - } - authentication.decryptAuthToken = decryptAuthToken; -})(authentication || (authentication = {})); -module.exports = authentication; + return { + id: id, + createdAt: new Date(parseInt(createdAt, 10)) + }; +} +exports.decryptAuthToken = decryptAuthToken; diff --git a/lib/src/authorizedResource.js b/lib/src/authorizedResource.js index 6e8e78f..f7b379b 100644 --- a/lib/src/authorizedResource.js +++ b/lib/src/authorizedResource.js @@ -1,124 +1,121 @@ +"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var resource_1 = require('./resource'); var auth = require('./authentication'); var mongoose = require('mongoose'); -var authorizedResource; -(function (authorizedResource) { - authorizedResource.ROLES = { - USER: 'USER', - SUPER_USER: 'SUPER_USER', - MODERATOR: 'MODERATOR', - ADMIN: 'ADMIN' - }; - var AuthorizedResource = (function (_super) { - __extends(AuthorizedResource, _super); - function AuthorizedResource() { - _super.apply(this, arguments); - this.maxDays = 7; - this.permissions = { - getAll: [authorizedResource.ROLES.USER, authorizedResource.ROLES.SUPER_USER, authorizedResource.ROLES.MODERATOR, authorizedResource.ROLES.ADMIN], - getById: [authorizedResource.ROLES.USER, authorizedResource.ROLES.SUPER_USER, authorizedResource.ROLES.MODERATOR, authorizedResource.ROLES.ADMIN], - create: [authorizedResource.ROLES.USER, authorizedResource.ROLES.SUPER_USER, authorizedResource.ROLES.MODERATOR, authorizedResource.ROLES.ADMIN], - update: [authorizedResource.ROLES.USER, authorizedResource.ROLES.SUPER_USER, authorizedResource.ROLES.MODERATOR, authorizedResource.ROLES.ADMIN], - del: [authorizedResource.ROLES.USER, authorizedResource.ROLES.SUPER_USER, authorizedResource.ROLES.MODERATOR, authorizedResource.ROLES.ADMIN] - }; - this.baseGetAll = _super.prototype.getAll; - this.baseGetById = _super.prototype.getById; - this.baseCreate = _super.prototype.create; - this.baseUpdate = _super.prototype.update; - this.baseDel = _super.prototype.del; - } - AuthorizedResource.prototype.isTokenExpired = function (createdAt) { - var maxTokenLifeTime = new Date(); - maxTokenLifeTime.setDate(maxTokenLifeTime.getDate() - this.maxDays); - return createdAt < maxTokenLifeTime; - }; - AuthorizedResource.prototype.getRoles = function (id) { - return this.db.model('User') - .findById(id) - .populate('roles') - .exec(); +exports.ROLES = { + USER: 'USER', + SUPER_USER: 'SUPER_USER', + MODERATOR: 'MODERATOR', + ADMIN: 'ADMIN' +}; +var AuthorizedResource = (function (_super) { + __extends(AuthorizedResource, _super); + function AuthorizedResource() { + _super.apply(this, arguments); + this.maxDays = 7; + this.permissions = { + getAll: [exports.ROLES.USER, exports.ROLES.SUPER_USER, exports.ROLES.MODERATOR, exports.ROLES.ADMIN], + getById: [exports.ROLES.USER, exports.ROLES.SUPER_USER, exports.ROLES.MODERATOR, exports.ROLES.ADMIN], + create: [exports.ROLES.USER, exports.ROLES.SUPER_USER, exports.ROLES.MODERATOR, exports.ROLES.ADMIN], + update: [exports.ROLES.USER, exports.ROLES.SUPER_USER, exports.ROLES.MODERATOR, exports.ROLES.ADMIN], + del: [exports.ROLES.USER, exports.ROLES.SUPER_USER, exports.ROLES.MODERATOR, exports.ROLES.ADMIN] }; - AuthorizedResource.prototype.hasAuthorizedRole = function (roles, authorizedRoles) { - var hasRole = false; - roles.forEach(function (role) { - authorizedRoles.forEach(function (authRole) { - if (role.name === authRole) { - hasRole = true; - } - }); + this.baseGetAll = _super.prototype.getAll; + this.baseGetById = _super.prototype.getById; + this.baseCreate = _super.prototype.create; + this.baseUpdate = _super.prototype.update; + this.baseDel = _super.prototype.del; + } + AuthorizedResource.prototype.isTokenExpired = function (createdAt) { + var maxTokenLifeTime = new Date(); + maxTokenLifeTime.setDate(maxTokenLifeTime.getDate() - this.maxDays); + return createdAt < maxTokenLifeTime; + }; + AuthorizedResource.prototype.getRoles = function (id) { + return this.db.model('User') + .findById(id) + .populate('roles') + .exec(); + }; + AuthorizedResource.prototype.hasAuthorizedRole = function (roles, authorizedRoles) { + var hasRole = false; + roles.forEach(function (role) { + authorizedRoles.forEach(function (authRole) { + if (role.name === authRole) { + hasRole = true; + } }); - return hasRole; - }; - AuthorizedResource.prototype.hasAccessRightsDefined = function (req, authorizedRoles) { - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); - if (authorizedRoles.length === 0) { - promise.resolve(null, null); - return promise; - } - }; - AuthorizedResource.prototype.isAuthorized = function (req, authorizedRoles) { - var _this = this; - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); - if (authorizedRoles.length === 0) { - promise.resolve(null, null); - return promise; + }); + return hasRole; + }; + AuthorizedResource.prototype.hasAccessRightsDefined = function (req, authorizedRoles) { + var promise = new mongoose.Promise(); + var authToken = req.header('Authorization'); + if (authorizedRoles.length === 0) { + promise.resolve(null, null); + return promise; + } + }; + AuthorizedResource.prototype.isAuthorized = function (req, authorizedRoles) { + var _this = this; + var promise = new mongoose.Promise(); + var authToken = req.header('Authorization'); + if (authorizedRoles.length === 0) { + promise.resolve(null, null); + return promise; + } + else if (!authToken) { + promise.resolve(new Error('no token found'), null); + return promise; + } + var tokenDetails = auth.decryptAuthToken(authToken); + return this.getRoles(tokenDetails.id) + .then(function (user) { + if (_this.isTokenExpired(tokenDetails.createdAt)) { + throw new Error('token expired'); } - else if (!authToken) { - promise.resolve(new Error('no token found'), null); - return promise; + return user.roles; + }) + .then(function (roles) { + if (!_this.hasAuthorizedRole(roles, authorizedRoles)) { + throw new Error('unauthorized'); } - var tokenDetails = auth.decryptAuthToken(authToken); - return this.getRoles(tokenDetails.id) - .then(function (user) { - if (_this.isTokenExpired(tokenDetails.createdAt)) { - throw new Error('token expired'); - } - return user.roles; - }) - .then(function (roles) { - if (!_this.hasAuthorizedRole(roles, authorizedRoles)) { - throw new Error('unauthorized'); - } - }); - }; - AuthorizedResource.prototype.sendUnauthorized = function (error, res) { - res.status(401).send('unauthorized'); - }; - AuthorizedResource.prototype.getAll = function (req, res) { - var _this = this; - this.isAuthorized(req, this.permissions.getAll) - .then(function () { return _super.prototype.getAll.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); - }; - AuthorizedResource.prototype.getById = function (req, res) { - var _this = this; - this.isAuthorized(req, this.permissions.getById) - .then(function () { return _super.prototype.getById.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); - }; - AuthorizedResource.prototype.create = function (req, res) { - var _this = this; - this.isAuthorized(req, this.permissions.create) - .then(function () { return _super.prototype.create.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); - }; - AuthorizedResource.prototype.update = function (req, res) { - var _this = this; - this.isAuthorized(req, this.permissions.update) - .then(function () { return _super.prototype.update.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); - }; - AuthorizedResource.prototype.del = function (req, res) { - var _this = this; - this.isAuthorized(req, this.permissions.del) - .then(function () { return _super.prototype.del.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); - }; - return AuthorizedResource; - })(resource_1.Resource); - authorizedResource.AuthorizedResource = AuthorizedResource; -})(authorizedResource || (authorizedResource = {})); -module.exports = authorizedResource; + }); + }; + AuthorizedResource.prototype.sendUnauthorized = function (error, res) { + res.status(401).send('unauthorized'); + }; + AuthorizedResource.prototype.getAll = function (req, res) { + var _this = this; + this.isAuthorized(req, this.permissions.getAll) + .then(function () { return _super.prototype.getAll.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + }; + AuthorizedResource.prototype.getById = function (req, res) { + var _this = this; + this.isAuthorized(req, this.permissions.getById) + .then(function () { return _super.prototype.getById.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + }; + AuthorizedResource.prototype.create = function (req, res) { + var _this = this; + this.isAuthorized(req, this.permissions.create) + .then(function () { return _super.prototype.create.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + }; + AuthorizedResource.prototype.update = function (req, res) { + var _this = this; + this.isAuthorized(req, this.permissions.update) + .then(function () { return _super.prototype.update.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + }; + AuthorizedResource.prototype.del = function (req, res) { + var _this = this; + this.isAuthorized(req, this.permissions.del) + .then(function () { return _super.prototype.del.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + }; + return AuthorizedResource; +}(resource_1.Resource)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = AuthorizedResource; diff --git a/lib/src/authorizedSubResource.js b/lib/src/authorizedSubResource.js index ec520e3..c2d932f 100644 --- a/lib/src/authorizedSubResource.js +++ b/lib/src/authorizedSubResource.js @@ -1,11 +1,11 @@ +"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var authorizedResource_1 = require('./authorizedResource'); -var SubResource = require('./subResource'); +var subResource_1 = require('./subResource'); var AuthorizedSubResource = (function (_super) { __extends(AuthorizedSubResource, _super); function AuthorizedSubResource(subResDef) { @@ -26,40 +26,41 @@ var AuthorizedSubResource = (function (_super) { AuthorizedSubResource.prototype.getAll = function (req, res) { var _this = this; this.isAuthorized(req, this.permissions.getAll) - .then(function () { return SubResource.prototype.getAll.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + .then(function () { return subResource_1.default.prototype.getAll.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); }; AuthorizedSubResource.prototype.getById = function (req, res) { var _this = this; this.isAuthorized(req, this.permissions.getById) - .then(function () { return SubResource.prototype.getById.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + .then(function () { return subResource_1.default.prototype.getById.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); }; AuthorizedSubResource.prototype.create = function (req, res) { var _this = this; this.isAuthorized(req, this.permissions.create) - .then(function () { return SubResource.prototype.create.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + .then(function () { return subResource_1.default.prototype.create.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); }; AuthorizedSubResource.prototype.update = function (req, res) { var _this = this; this.isAuthorized(req, this.permissions.update) - .then(function () { return SubResource.prototype.update.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + .then(function () { return subResource_1.default.prototype.update.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); }; AuthorizedSubResource.prototype.del = function (req, res) { var _this = this; this.isAuthorized(req, this.permissions.del) - .then(function () { return SubResource.prototype.del.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); + .then(function () { return subResource_1.default.prototype.del.call(_this, req, res); }, function (err) { return _this.sendUnauthorized(err, res); }); }; AuthorizedSubResource.prototype.createProjectionQuery = function (req) { - return SubResource.prototype.createProjectionQuery.call(this, req); + return subResource_1.default.prototype.createProjectionQuery.call(this, req); }; AuthorizedSubResource.prototype.createPullQuery = function (req) { - return SubResource.prototype.createPullQuery.call(this, req); + return subResource_1.default.prototype.createPullQuery.call(this, req); }; AuthorizedSubResource.prototype.createFindQuery = function (req) { - return SubResource.prototype.createFindQuery.call(this, req); + return subResource_1.default.prototype.createFindQuery.call(this, req); }; AuthorizedSubResource.prototype.createSubUpdateQuery = function (req) { - return SubResource.prototype.createSubUpdateQuery.call(this, req); + return subResource_1.default.prototype.createSubUpdateQuery.call(this, req); }; return AuthorizedSubResource; -})(authorizedResource_1.AuthorizedResource); -module.exports = AuthorizedSubResource; +}(authorizedResource_1.default)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = AuthorizedSubResource; diff --git a/lib/src/index.js b/lib/src/index.js index 5b8c0ac..7737546 100644 --- a/lib/src/index.js +++ b/lib/src/index.js @@ -1,10 +1,12 @@ +"use strict"; var resource = require('./resource'); -var Resource = resource.Resource; +var resource_1 = require('./resource'); var bodyParser = require('body-parser'); -var UserResource = require('./userResource'); +var userResource_1 = require('./userResource'); var authorizedResource = require('./authorizedResource'); -var SubResource = require('./subResource'); -var AuthorizedSubResource = require('./authorizedSubResource'); +var authorizedResource_1 = require('./authorizedResource'); +var subResource_1 = require('./subResource'); +var authorizedSubResource_1 = require('./authorizedSubResource'); var autoloader = require('auto-loader'); var RestIO = (function () { function RestIO(app, config) { @@ -21,11 +23,12 @@ var RestIO = (function () { return resource; } RestIO.authorizedResource = authorizedResource; - RestIO.UserResource = UserResource; - RestIO.AuthorizedResource = authorizedResource.AuthorizedResource; - RestIO.SubResource = SubResource; - RestIO.AuthorizedSubResource = AuthorizedSubResource; - RestIO.Resource = Resource; + RestIO.UserResource = userResource_1.default; + RestIO.AuthorizedResource = authorizedResource_1.default; + RestIO.SubResource = subResource_1.default; + RestIO.AuthorizedSubResource = authorizedSubResource_1.default; + RestIO.Resource = resource_1.Resource; return RestIO; -})(); -module.exports = RestIO; +}()); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = RestIO; diff --git a/lib/src/resource.js b/lib/src/resource.js index 4d21954..92dd437 100644 --- a/lib/src/resource.js +++ b/lib/src/resource.js @@ -1,172 +1,169 @@ +"use strict"; var express = require('express'); var mongoose = require('mongoose'); var mongoose_1 = require('mongoose'); var ObjectId = mongoose_1.Types.ObjectId; var pluralize = require('pluralize'); -var Resource; -(function (Resource_1) { - var app; - var db; - var Resource = (function () { - function Resource(resDef) { - this.baseUrl = Resource.BASE_URL; - if (!!resDef.parentResource) { - this.parentResource = resDef.parentResource; - this.baseUrl = resDef.parentResource.parameterizedUrl; - this.parentRef = resDef.parentRef || resDef.parentResource.resDef.name; - } - this.app = app; - this.db = db; - this.populate = resDef.populate; - this.model = this.createModel(resDef); - this.resDef = resDef; - this.setupRoutes(); +var app; +var db; +var Resource = (function () { + function Resource(resDef) { + this.baseUrl = Resource.BASE_URL; + if (!!resDef.parentResource) { + this.parentResource = resDef.parentResource; + this.baseUrl = resDef.parentResource.parameterizedUrl; + this.parentRef = resDef.parentRef || resDef.parentResource.resDef.name; } - Resource.prototype.createModel = function (resDef) { - var schema = new mongoose_1.Schema(resDef.model); - return this.db.model(this.toClassName(resDef.name), schema); - }; - Resource.prototype.toClassName = function (name) { - return name.replace(/\w\S*/g, function (namePart) { - return namePart.charAt(0).toUpperCase() + namePart.substr(1).toLowerCase(); - }); - }; - Resource.prototype.setupRoutes = function () { - var _this = this; - this.url = this.baseUrl + "/"; - this.resDef.plural = this.resDef.plural || pluralize.plural(this.resDef.name); - this.url += this.resDef.plural; - this.paramId = this.resDef.name + "Id"; - app.param(this.paramId, String); - this.parameterizedUrl = this.url + "/:" + this.paramId; - this.router = express.Router(); - this.router - .route(this.url) - .get(function (req, res) { return _this.getAll(req, res); }) - .post(function (req, res) { return _this.create(req, res); }); - this.router - .route(this.parameterizedUrl) - .get(function (req, res) { return _this.getById(req, res); }) - .put(function (req, res) { return _this.update(req, res); }) - .delete(function (req, res) { return _this.del(req, res); }); - this.setupRecursiveRoutes(); - app.use(this.router); - }; - Resource.prototype.setupRecursiveRoutes = function () { - var _this = this; - var resource = this.parentResource; - if (!!resource) { - this.router.route(Resource.BASE_URL + "/" + this.resDef.plural) + this.app = app; + this.db = db; + this.populate = resDef.populate; + this.model = this.createModel(resDef); + this.resDef = resDef; + this.setupRoutes(); + } + Resource.prototype.createModel = function (resDef) { + var schema = new mongoose_1.Schema(resDef.model); + return this.db.model(this.toClassName(resDef.name), schema); + }; + Resource.prototype.toClassName = function (name) { + return name.replace(/\w\S*/g, function (namePart) { + return namePart.charAt(0).toUpperCase() + namePart.substr(1).toLowerCase(); + }); + }; + Resource.prototype.setupRoutes = function () { + var _this = this; + this.url = this.baseUrl + "/"; + this.resDef.plural = this.resDef.plural || pluralize.plural(this.resDef.name); + this.url += this.resDef.plural; + this.paramId = this.resDef.name + "Id"; + app.param(this.paramId, String); + this.parameterizedUrl = this.url + "/:" + this.paramId; + this.router = express.Router(); + this.router + .route(this.url) + .get(function (req, res) { return _this.getAll(req, res); }) + .post(function (req, res) { return _this.create(req, res); }); + this.router + .route(this.parameterizedUrl) + .get(function (req, res) { return _this.getById(req, res); }) + .put(function (req, res) { return _this.update(req, res); }) + .delete(function (req, res) { return _this.del(req, res); }); + this.setupRecursiveRoutes(); + app.use(this.router); + }; + Resource.prototype.setupRecursiveRoutes = function () { + var _this = this; + var resource = this.parentResource; + if (!!resource) { + this.router.route(Resource.BASE_URL + "/" + this.resDef.plural) + .get(function (req, res) { return _this.getAll(req, res); }); + while (!!resource && !!resource.parentRef) { + resource = resource.parentResource; + this.router.route(resource.url + "/" + this.resDef.plural) .get(function (req, res) { return _this.getAll(req, res); }); - while (!!resource && !!resource.parentRef) { - resource = resource.parentResource; - this.router.route(resource.url + "/" + this.resDef.plural) - .get(function (req, res) { return _this.getAll(req, res); }); - } - } - }; - Resource.prototype.getAll = function (req, res) { - var _this = this; - try { - var query = this.buildSearchQuery(req); - var getQuery = this.model.find(query); - getQuery - .populate(this.buildPopulateQuery(req)) - .exec() - .then(function (result) { return res.send(result); }, function (err) { return _this.errorHandler(err, res); }); } - catch (err) { - this.errorHandler(err, res); + } + }; + Resource.prototype.getAll = function (req, res) { + var _this = this; + try { + var query = this.buildSearchQuery(req); + var getQuery = this.model.find(query); + getQuery + .populate(this.buildPopulateQuery(req)) + .exec() + .then(function (result) { return res.send(result); }, function (err) { return _this.errorHandler(err, res); }); + } + catch (err) { + this.errorHandler(err, res); + } + }; + Resource.prototype.buildPopulateQuery = function (req) { + if (typeof req.query.populate === 'string') { + return req.query.populate; + } + else { + return this.parentRef + " " + this.populate; + } + }; + Resource.prototype.buildSearchQuery = function (req) { + var query = {}; + for (var attr in req.query) { + if (req.query.hasOwnProperty(attr) && attr !== 'populate') { + query[attr] = this.createQuery(req.query[attr]); } - }; - Resource.prototype.buildPopulateQuery = function (req) { - if (typeof req.query.populate === 'string') { - return req.query.populate; + } + this.buildParentSearch(req, query); + return query; + }; + Resource.prototype.createQuery = function (query) { + try { + return JSON.parse(query); + } + catch (error) { + return this.createRegex(query); + } + }; + Resource.prototype.createRegex = function (query) { + if (!query.match(/\//)) { + query = "/" + query + "/"; + } + var splitQuery = query.split('/'); + var modifier = splitQuery.pop(); + splitQuery.shift(); + return new RegExp(splitQuery.join('/'), modifier); + }; + Resource.prototype.buildParentSearch = function (req, query) { + var resource = this; + while (!!resource.parentRef) { + var id = req.params[resource.parentResource.paramId]; + if (!!id) { + query[resource.parentRef] = new ObjectId(id); } else { - return this.parentRef + " " + this.populate; - } - }; - Resource.prototype.buildSearchQuery = function (req) { - var query = {}; - for (var attr in req.query) { - if (req.query.hasOwnProperty(attr) && attr !== 'populate') { - query[attr] = this.createQuery(req.query[attr]); - } - } - this.buildParentSearch(req, query); - return query; - }; - Resource.prototype.createQuery = function (query) { - try { - return JSON.parse(query); - } - catch (error) { - return this.createRegex(query); - } - }; - Resource.prototype.createRegex = function (query) { - if (!query.match(/\//)) { - query = "/" + query + "/"; - } - var splitQuery = query.split('/'); - var modifier = splitQuery.pop(); - splitQuery.shift(); - return new RegExp(splitQuery.join('/'), modifier); - }; - Resource.prototype.buildParentSearch = function (req, query) { - var resource = this; - while (!!resource.parentRef) { - var id = req.params[resource.parentResource.paramId]; - if (!!id) { - query[resource.parentRef] = new ObjectId(id); - } - else { - break; - } - resource = resource.parentResource; + break; } - return query; - }; - Resource.prototype.getById = function (req, res) { - var _this = this; - var id = req.params[this.paramId]; - this.model.findById(id) - .populate(this.buildPopulateQuery(req)) - .exec() - .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); - }; - Resource.prototype.create = function (req, res) { - var _this = this; - this.model.create(req.body) - .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); - }; - Resource.prototype.update = function (req, res) { - var _this = this; - var id = req.params[this.paramId]; - this.model.findByIdAndUpdate(id, req.body) - .exec() - .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); - }; - Resource.prototype.del = function (req, res) { - var _this = this; - var id = req.params[this.paramId]; - this.model.findByIdAndRemove(id, req.body) - .exec() - .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); - }; - Resource.prototype.errorHandler = function (err, res) { - console.log(err); - res.status(500).send('internal server error'); - }; - Resource.BASE_URL = '/api'; - return Resource; - })(); - Resource_1.Resource = Resource; - function registerApp(registerApp, connection) { - app = registerApp; - db = connection || mongoose; - } - Resource_1.registerApp = registerApp; -})(Resource || (Resource = {})); -module.exports = Resource; + resource = resource.parentResource; + } + return query; + }; + Resource.prototype.getById = function (req, res) { + var _this = this; + var id = req.params[this.paramId]; + this.model.findById(id) + .populate(this.buildPopulateQuery(req)) + .exec() + .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); + }; + Resource.prototype.create = function (req, res) { + var _this = this; + this.model.create(req.body) + .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); + }; + Resource.prototype.update = function (req, res) { + var _this = this; + var id = req.params[this.paramId]; + this.model.findByIdAndUpdate(id, req.body) + .exec() + .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); + }; + Resource.prototype.del = function (req, res) { + var _this = this; + var id = req.params[this.paramId]; + this.model.findByIdAndRemove(id, req.body) + .exec() + .then(function (model) { return res.send(model); }, function (err) { return _this.errorHandler(err, res); }); + }; + Resource.prototype.errorHandler = function (err, res) { + console.log(err); + res.status(500).send('internal server error'); + }; + Resource.BASE_URL = '/api'; + return Resource; +}()); +exports.Resource = Resource; +function registerApp(registerApp, connection) { + app = registerApp; + db = connection || mongoose; +} +exports.registerApp = registerApp; diff --git a/lib/src/subResource.js b/lib/src/subResource.js index 5fcda7a..6720531 100644 --- a/lib/src/subResource.js +++ b/lib/src/subResource.js @@ -1,8 +1,8 @@ +"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var resource_1 = require('./resource'); var SubResource = (function (_super) { @@ -92,5 +92,6 @@ var SubResource = (function (_super) { return setQuery; }; return SubResource; -})(resource_1.Resource); -module.exports = SubResource; +}(resource_1.Resource)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = SubResource; diff --git a/lib/src/userResource.js b/lib/src/userResource.js index 1825d41..1c4f9c6 100644 --- a/lib/src/userResource.js +++ b/lib/src/userResource.js @@ -1,10 +1,11 @@ +"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var authorizedResource_1 = require('./authorizedResource'); +var authorizedResource_2 = require('./authorizedResource'); var mongoose_1 = require('mongoose'); var auth = require('./authentication'); var UserResource = (function (_super) { @@ -12,11 +13,11 @@ var UserResource = (function (_super) { function UserResource() { _super.apply(this, arguments); this.permissions = { - getAll: [authorizedResource_1.ROLES.USER, authorizedResource_1.ROLES.SUPER_USER, authorizedResource_1.ROLES.MODERATOR, authorizedResource_1.ROLES.ADMIN], - getById: [authorizedResource_1.ROLES.USER, authorizedResource_1.ROLES.SUPER_USER, authorizedResource_1.ROLES.MODERATOR, authorizedResource_1.ROLES.ADMIN], + getAll: [authorizedResource_2.ROLES.USER, authorizedResource_2.ROLES.SUPER_USER, authorizedResource_2.ROLES.MODERATOR, authorizedResource_2.ROLES.ADMIN], + getById: [authorizedResource_2.ROLES.USER, authorizedResource_2.ROLES.SUPER_USER, authorizedResource_2.ROLES.MODERATOR, authorizedResource_2.ROLES.ADMIN], create: [], - update: [authorizedResource_1.ROLES.MODERATOR, authorizedResource_1.ROLES.ADMIN], - del: [authorizedResource_1.ROLES.ADMIN] + update: [authorizedResource_2.ROLES.MODERATOR, authorizedResource_2.ROLES.ADMIN], + del: [authorizedResource_2.ROLES.ADMIN] }; } UserResource.prototype.createModel = function (resDef) { @@ -99,5 +100,6 @@ var UserResource = (function (_super) { }, function () { return _this.sendUnauthorized(new Error('cannot perform login'), res); }); }; return UserResource; -})(authorizedResource_1.AuthorizedResource); -module.exports = UserResource; +}(authorizedResource_1.default)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = UserResource; diff --git a/lib/test/authentication/authentication.spec.js b/lib/test/authentication/authentication.spec.js index 613affb..4917d02 100644 --- a/lib/test/authentication/authentication.spec.js +++ b/lib/test/authentication/authentication.spec.js @@ -1,15 +1,16 @@ +"use strict"; var Yadda = require('yadda'); Yadda.plugins.mocha.ScenarioLevelPlugin.init(); var mongoose = require('mongoose'); process.env.DB = 'authTest'; require('../../examples/authentication/app'); var library = require('./definitions/authentication.steps'); -var user = require('../../examples/authentication/resources/user'); +var user_1 = require('../../examples/authentication/resources/user'); new Yadda.FeatureFileSearch('test/authentication').each(function (file) { featureFile(file, function (feature) { var yadda = Yadda.createInstance(library); afterEach(function (done) { - user.db.connection.db.dropDatabase(function (err, result) { + user_1.user.db.connection.db.dropDatabase(function (err, result) { done(); }); }); diff --git a/lib/test/authentication/authentication.specs.js b/lib/test/authentication/authentication.specs.js deleted file mode 100644 index cfb4440..0000000 --- a/lib/test/authentication/authentication.specs.js +++ /dev/null @@ -1,20 +0,0 @@ -var Yadda = require('yadda'); -Yadda.plugins.mocha.ScenarioLevelPlugin.init(); -var mongoose = require('mongoose'); -process.env.DB = 'customTest'; -console.log('lol'); -require('../../examples/authentication/app'); -var library = require('./definitions/authentication.steps'); -new Yadda.FeatureFileSearch('test/authentication').each(function (file) { - featureFile(file, function (feature) { - var yadda = Yadda.createInstance(library); - afterEach(function (done) { - mongoose.connection.db.dropDatabase(function (err, result) { - done(); - }); - }); - scenarios(feature.scenarios, function (scenario, done) { - yadda.run(scenario.steps, done); - }); - }); -}); diff --git a/lib/test/authentication/definitions/authentication.steps.js b/lib/test/authentication/definitions/authentication.steps.js index 6b4c776..1b429ef 100644 --- a/lib/test/authentication/definitions/authentication.steps.js +++ b/lib/test/authentication/definitions/authentication.steps.js @@ -1,3 +1,4 @@ +"use strict"; var _this = this; var English = require('yadda').localisation.English; var library = English.library(); @@ -8,7 +9,7 @@ var mongoose = require('mongoose'); var ObjectId = mongoose.Types.ObjectId; var auth = require('../../../src/authentication'); var supertest = require('supertest'); -var user = require('../../../examples/authentication/resources/user'); +var user_1 = require('../../../examples/authentication/resources/user'); function createIdBasedOnName(name) { var id = convertToHex(name); var i = 0; @@ -46,7 +47,7 @@ library }) .given('', function (done) { return done(); }) .given('<(.*)>', function (role, done) { - user.db.model('Role').create({ + user_1.user.db.model('Role').create({ _id: new ObjectId(createIdBasedOnName(role)), name: role }, function () { return done(); }); diff --git a/lib/test/customResource/definitions/customResource.steps.js b/lib/test/customResource/definitions/customResource.steps.js index aeb835e..d30a3cb 100644 --- a/lib/test/customResource/definitions/customResource.steps.js +++ b/lib/test/customResource/definitions/customResource.steps.js @@ -1,3 +1,4 @@ +"use strict"; var _this = this; var English = require('yadda').localisation.English; var library = English.library(); diff --git a/lib/test/foods/definitions/foods.steps.js b/lib/test/foods/definitions/foods.steps.js index c769753..ccd5c90 100644 --- a/lib/test/foods/definitions/foods.steps.js +++ b/lib/test/foods/definitions/foods.steps.js @@ -1,3 +1,4 @@ +"use strict"; var _this = this; var English = require('yadda').localisation.English; var library = English.library(); diff --git a/lib/test/subresource/definitions/sub.steps.js b/lib/test/subresource/definitions/sub.steps.js index c6cda30..54a4d49 100644 --- a/lib/test/subresource/definitions/sub.steps.js +++ b/lib/test/subresource/definitions/sub.steps.js @@ -1,3 +1,4 @@ +"use strict"; var _this = this; var English = require('yadda').localisation.English; var library = English.library(); From d106b1eefd88d0c6f6456375138d6ee7d07dffbe Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 18:54:36 +0200 Subject: [PATCH 05/13] added peer dependencies to dev dependencies --- package.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 48a96f5..fed5e80 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "framework" ], "author": "Andy Tang ", - "contributors":[ + "contributors": [ "Dominik Kukacka", "Stefan Schacherl " ], @@ -52,10 +52,14 @@ "mongoose": "^4.0.5" }, "devDependencies": { + "auto-loader": "^0.2.0", + "body-parser": "^1.15.0", "chai": "^2.3.0", "chai-things": "^0.2.0", + "express": "^4.13.4", "mocha": "^2.2.5", "mocha-better-spec-reporter": "^2.0.1", + "mongoose": "^4.4.14", "parallelshell": "^1.1.1", "rimraf": "^2.3.4", "sinon": "^1.14.1", From 945212e2e1077ead144d5682d2be05106772b355 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 19:49:47 +0200 Subject: [PATCH 06/13] added wercker for easier development --- .gitignore | 2 ++ wercker.yml | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/.gitignore b/.gitignore index 2306783..a2b1b54 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +_builds/ +_steps/ build node_modules npm-debug.log diff --git a/wercker.yml b/wercker.yml index f7082be..dddd7d3 100644 --- a/wercker.yml +++ b/wercker.yml @@ -13,6 +13,11 @@ box: node services: - id: mongo +dev: + steps: + - npm-install + - npm-test + build: # The steps that will be executed on build # Steps make up the actions in your pipeline From 2293109d96ff8a25028b274ad98a63a90f718b9f Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 20:18:37 +0200 Subject: [PATCH 07/13] fixed authorization descryption - destructured the array incorrectly --- lib/src/authentication.js | 2 +- src/authentication.ts | 3 +- tsconfig.json | 4 + typings/browser.d.ts | 12 - .../browser/ambient/body-parser/index.d.ts | 139 - typings/browser/ambient/chai/index.d.ts | 310 --- typings/browser/ambient/express/index.d.ts | 1099 -------- typings/browser/ambient/mocha/index.d.ts | 168 -- typings/browser/ambient/mongoose/index.d.ts | 461 ---- typings/browser/ambient/node/index.d.ts | 2377 ----------------- typings/browser/ambient/pluralize/index.d.ts | 67 - typings/browser/ambient/sinon-chai/index.d.ts | 84 - typings/browser/ambient/sinon/index.d.ts | 422 --- typings/browser/ambient/superagent/index.d.ts | 116 - typings/browser/ambient/supertest/index.d.ts | 40 - typings/main.d.ts | 2 +- wercker.yml | 5 +- 17 files changed, 11 insertions(+), 5300 deletions(-) delete mode 100644 typings/browser.d.ts delete mode 100644 typings/browser/ambient/body-parser/index.d.ts delete mode 100644 typings/browser/ambient/chai/index.d.ts delete mode 100644 typings/browser/ambient/express/index.d.ts delete mode 100644 typings/browser/ambient/mocha/index.d.ts delete mode 100644 typings/browser/ambient/mongoose/index.d.ts delete mode 100644 typings/browser/ambient/node/index.d.ts delete mode 100644 typings/browser/ambient/pluralize/index.d.ts delete mode 100644 typings/browser/ambient/sinon-chai/index.d.ts delete mode 100644 typings/browser/ambient/sinon/index.d.ts delete mode 100644 typings/browser/ambient/superagent/index.d.ts delete mode 100644 typings/browser/ambient/supertest/index.d.ts diff --git a/lib/src/authentication.js b/lib/src/authentication.js index 78c73d9..d44997b 100644 --- a/lib/src/authentication.js +++ b/lib/src/authentication.js @@ -13,7 +13,7 @@ function createAuthToken(userId) { exports.createAuthToken = createAuthToken; function decryptAuthToken(authToken) { var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); - var _a = decryptedMessage.toString(enc.Utf8).split(';'), id = _a.id, createdAt = _a.createdAt; + var _a = decryptedMessage.toString(enc.Utf8).split(';'), id = _a[0], createdAt = _a[1]; if (!id || !createdAt) { throw new Error('corrupt auth token'); } diff --git a/src/authentication.ts b/src/authentication.ts index 8d3e1b7..5317ed3 100644 --- a/src/authentication.ts +++ b/src/authentication.ts @@ -13,7 +13,7 @@ export function createAuthToken(userId: string) { export function decryptAuthToken(authToken: string) { var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); - const { id, createdAt } = decryptedMessage.toString(enc.Utf8).split(';'); + const [ id, createdAt ] = decryptedMessage.toString(enc.Utf8).split(';'); if (!id || !createdAt) { throw new Error('corrupt auth token'); } @@ -22,4 +22,3 @@ export function decryptAuthToken(authToken: string) { createdAt: new Date(parseInt(createdAt, 10)) }; } - diff --git a/tsconfig.json b/tsconfig.json index a185bc7..7e73c17 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,6 +19,7 @@ "files": [ "definitions/rest-io.d.ts", "typings/main.d.ts", + "typings/yadda.d.ts", "examples/authentication/app.ts", "examples/authentication/resources/parent.ts", "examples/authentication/resources/sub.ts", @@ -54,5 +55,8 @@ "indentSize": 2, "tabSize": 2, "convertTabsToSpaces": true + }, + "atom": { + "rewriteTsconfig": true } } diff --git a/typings/browser.d.ts b/typings/browser.d.ts deleted file mode 100644 index 75524d2..0000000 --- a/typings/browser.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/typings/browser/ambient/body-parser/index.d.ts b/typings/browser/ambient/body-parser/index.d.ts deleted file mode 100644 index 56d3cc2..0000000 --- a/typings/browser/ambient/body-parser/index.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/body-parser/body-parser.d.ts -// Type definitions for body-parser -// Project: http://expressjs.com -// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -declare module "body-parser" { - import express = require('express'); - - /** - * bodyParser: use individual json/urlencoded middlewares - * @deprecated - */ - - function bodyParser(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - receiver?: (key: string, value: any) => any; - /** - * parse extended syntax with the qs module. (default: true) - */ - extended?: boolean; - }): express.RequestHandler; - - module bodyParser { - export function json(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'json') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - receiver?: (key: string, value: any) => any; - }): express.RequestHandler; - - export function raw(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - }): express.RequestHandler; - - export function text(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * the default charset to parse as, if not specified in content-type. (default: 'utf-8') - */ - defaultCharset?: string; - }): express.RequestHandler; - - export function urlencoded(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * parse extended syntax with the qs module. (default: true) - */ - extended?: boolean; - }): express.RequestHandler; - } - - export = bodyParser; -} \ No newline at end of file diff --git a/typings/browser/ambient/chai/index.d.ts b/typings/browser/ambient/chai/index.d.ts deleted file mode 100644 index 4ab4d27..0000000 --- a/typings/browser/ambient/chai/index.d.ts +++ /dev/null @@ -1,310 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/chai/chai.d.ts -// Type definitions for chai 2.0.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): any; - assert: AssertStatic; - config: Config; - } - - export interface ExpectStatic extends AssertionStatic { - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - a: TypeComparison; - an: TypeComparison; - include: Include; - contain: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - length: Length; - lengthOf: Length; - match(regexp: RegExp|string, message?: string): Assertion; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo(method: string, message?: string): Assertion; - itself: Assertion; - satisfy(matcher: Function, message?: string): Assertion; - closeTo(expected: number, delta: number, message?: string): Assertion; - members: Members; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - - equal(act: any, exp: any, msg?: string): void; - notEqual(act: any, exp: any, msg?: string): void; - - strictEqual(act: any, exp: any, msg?: string): void; - notStrictEqual(act: any, exp: any, msg?: string): void; - - deepEqual(act: any, exp: any, msg?: string): void; - notDeepEqual(act: any, exp: any, msg?: string): void; - - isTrue(val: any, msg?: string): void; - isFalse(val: any, msg?: string): void; - - isNull(val: any, msg?: string): void; - isNotNull(val: any, msg?: string): void; - - isUndefined(val: any, msg?: string): void; - isDefined(val: any, msg?: string): void; - - isFunction(val: any, msg?: string): void; - isNotFunction(val: any, msg?: string): void; - - isObject(val: any, msg?: string): void; - isNotObject(val: any, msg?: string): void; - - isArray(val: any, msg?: string): void; - isNotArray(val: any, msg?: string): void; - - isString(val: any, msg?: string): void; - isNotString(val: any, msg?: string): void; - - isNumber(val: any, msg?: string): void; - isNotNumber(val: any, msg?: string): void; - - isBoolean(val: any, msg?: string): void; - isNotBoolean(val: any, msg?: string): void; - - typeOf(val: any, type: string, msg?: string): void; - notTypeOf(val: any, type: string, msg?: string): void; - - instanceOf(val: any, type: Function, msg?: string): void; - notInstanceOf(val: any, type: Function, msg?: string): void; - - include(exp: string, inc: any, msg?: string): void; - include(exp: any[], inc: any, msg?: string): void; - - notInclude(exp: string, inc: any, msg?: string): void; - notInclude(exp: any[], inc: any, msg?: string): void; - - match(exp: any, re: RegExp, msg?: string): void; - notMatch(exp: any, re: RegExp, msg?: string): void; - - property(obj: Object, prop: string, msg?: string): void; - notProperty(obj: Object, prop: string, msg?: string): void; - deepProperty(obj: Object, prop: string, msg?: string): void; - notDeepProperty(obj: Object, prop: string, msg?: string): void; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - - lengthOf(exp: any, len: number, msg?: string): void; - //alias frenzy - throw(fn: Function, msg?: string): void; - throw(fn: Function, regExp: RegExp): void; - throw(fn: Function, errType: Function, msg?: string): void; - throw(fn: Function, errType: Function, regExp: RegExp): void; - - throws(fn: Function, msg?: string): void; - throws(fn: Function, regExp: RegExp): void; - throws(fn: Function, errType: Function, msg?: string): void; - throws(fn: Function, errType: Function, regExp: RegExp): void; - - Throw(fn: Function, msg?: string): void; - Throw(fn: Function, regExp: RegExp): void; - Throw(fn: Function, errType: Function, msg?: string): void; - Throw(fn: Function, errType: Function, regExp: RegExp): void; - - doesNotThrow(fn: Function, msg?: string): void; - doesNotThrow(fn: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, errType: Function, msg?: string): void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - - operator(val: any, operator: string, val2: any, msg?: string): void; - closeTo(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(set1: any[], set2: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - } - - export interface Config { - includeStack: boolean; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} \ No newline at end of file diff --git a/typings/browser/ambient/express/index.d.ts b/typings/browser/ambient/express/index.d.ts deleted file mode 100644 index a5a0c5b..0000000 --- a/typings/browser/ambient/express/index.d.ts +++ /dev/null @@ -1,1099 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/express/express.d.ts -// Type definitions for Express 4.x -// Project: http://expressjs.com -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* =================== USAGE =================== - - import express = require('express'); - var app = express(); - - =============================================== */ - - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - - -declare module "express" { - import http = require('http'); - - function e(): e.Express; - - module e { - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - } - - interface IRouterMatcher { - (name: string, ...handlers: RequestHandler[]): T; - (name: RegExp, ...handlers: RequestHandler[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - - route(path: string): IRoute; - - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler): T; - } - - export function Router(options?: any): Router; - - export interface Router extends IRouter {} - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.ServerRequest, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get (name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Check if the given `charset` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param charset - */ - acceptsCharset(charset: string): boolean; - - /** - * Check if the given `lang` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param lang - */ - acceptsLanguage(lang: string): boolean; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - */ - acceptedLanguages: any[]; - - /** - * Return an array of Accepted charsets - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 - * ['unicode-1-1', 'iso-8859-5'] - */ - acceptedCharsets: any[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - files: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

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

hey

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

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get (field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; - - locals: any; - - charset: string; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: Function): any; - } - - interface RequestHandler { - (req: Request, res: Response, next: Function): any; - } - - interface Handler extends RequestHandler {} - - interface RequestParamHandler { - (req: Request, res: Response, next: Function, param: any): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string, ...handlers: RequestHandler[]): Application; - (name: RegExp, ...handlers: RequestHandler[]): Application; - }; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - route(path: string): IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } - - /** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - * @param root - * @param options - */ - function static(root: string, options?: any): RequestHandler; - } - - export = e; -} \ No newline at end of file diff --git a/typings/browser/ambient/mocha/index.d.ts b/typings/browser/ambient/mocha/index.d.ts deleted file mode 100644 index c4fdd8d..0000000 --- a/typings/browser/ambient/mocha/index.d.ts +++ /dev/null @@ -1,168 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mocha/mocha.d.ts -// Type definitions for mocha 2.0.1 -// Project: http://mochajs.org/ -// Definitions by: Kazi Manzur Rashid , otiai10 , jt000 -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Mocha { - // Setup mocha with the given setting options. - setup(options: MochaSetupOptions): Mocha; - - //Run tests and invoke `fn()` when complete. - run(callback?: () => void): void; - - // Set reporter as function - reporter(reporter: () => void): Mocha; - - // Set reporter, defaults to "dot" - reporter(reporter: string): Mocha; - - // Enable growl support. - growl(): Mocha -} - -interface MochaSetupOptions { - //milliseconds to wait before considering a test slow - slow?: number; - - // timeout in milliseconds - timeout?: number; - - // ui name "bdd", "tdd", "exports" etc - ui?: string; - - //array of accepted globals - globals?: any[]; - - // reporter instance (function or string), defaults to `mocha.reporters.Dot` - reporter?: any; - - // bail on the first test failure - bail?: boolean; - - // ignore global leaks - ignoreLeaks?: boolean; - - // grep string or regexp to filter tests with - grep?: any; -} - -interface MochaDone { - (error?: Error): void; -} - -declare var mocha: Mocha; - -declare var describe: { - (description: string, spec: () => void): void; - only(description: string, spec: () => void): void; - skip(description: string, spec: () => void): void; - timeout(ms: number): void; -} - -// alias for `describe` -declare var context: { - (contextTitle: string, spec: () => void): void; - only(contextTitle: string, spec: () => void): void; - skip(contextTitle: string, spec: () => void): void; - timeout(ms: number): void; -}; - -// alias for `describe` -declare var suite: { - (suiteTitle: string, spec: () => void): void; - only(suiteTitle: string, spec: () => void): void; - skip(suiteTitle: string, spec: () => void): void; - timeout(ms: number): void; -}; - -declare var it: { - (expectation: string, assertion?: () => void): void; - (expectation: string, assertion?: (done: MochaDone) => void): void; - only(expectation: string, assertion?: () => void): void; - only(expectation: string, assertion?: (done: MochaDone) => void): void; - skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: MochaDone) => void): void; - timeout(ms: number): void; -}; - -// alias for `it` -declare var test: { - (expectation: string, assertion?: () => void): void; - (expectation: string, assertion?: (done: MochaDone) => void): void; - only(expectation: string, assertion?: () => void): void; - only(expectation: string, assertion?: (done: MochaDone) => void): void; - skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: MochaDone) => void): void; - timeout(ms: number): void; -}; - -declare function before(action: () => void): void; - -declare function before(action: (done: MochaDone) => void): void; - -declare function setup(action: () => void): void; - -declare function setup(action: (done: MochaDone) => void): void; - -declare function after(action: () => void): void; - -declare function after(action: (done: MochaDone) => void): void; - -declare function teardown(action: () => void): void; - -declare function teardown(action: (done: MochaDone) => void): void; - -declare function beforeEach(action: () => void): void; - -declare function beforeEach(action: (done: MochaDone) => void): void; - -declare function suiteSetup(action: () => void): void; - -declare function suiteSetup(action: (done: MochaDone) => void): void; - -declare function afterEach(action: () => void): void; - -declare function afterEach(action: (done: MochaDone) => void): void; - -declare function suiteTeardown(action: () => void): void; - -declare function suiteTeardown(action: (done: MochaDone) => void): void; - -declare module "mocha" { - - class Mocha { - constructor(options?: { - grep?: RegExp; - ui?: string; - reporter?: string; - timeout?: number; - bail?: boolean; - }); - - bail(value?: boolean): Mocha; - addFile(file: string): Mocha; - reporter(value: string): Mocha; - ui(value: string): Mocha; - grep(value: string): Mocha; - grep(value: RegExp): Mocha; - invert(): Mocha; - ignoreLeaks(value: boolean): Mocha; - checkLeaks(): Mocha; - growl(): Mocha; - globals(value: string): Mocha; - globals(values: string[]): Mocha; - useColors(value: boolean): Mocha; - useInlineDiffs(value: boolean): Mocha; - timeout(value: number): Mocha; - slow(value: number): Mocha; - enableTimeouts(value: boolean): Mocha; - asyncOnly(value: boolean): Mocha; - noHighlighting(value: boolean): Mocha; - - run(onComplete?: (failures: number) => void): void; - } - - export = Mocha; -} \ No newline at end of file diff --git a/typings/browser/ambient/mongoose/index.d.ts b/typings/browser/ambient/mongoose/index.d.ts deleted file mode 100644 index eda050c..0000000 --- a/typings/browser/ambient/mongoose/index.d.ts +++ /dev/null @@ -1,461 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/mongoose/mongoose.d.ts -// Type definitions for Mongoose 3.8.5 -// Project: http://mongoosejs.com/ -// Definitions by: horiuchi -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -declare module "mongoose" { - function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; - function createConnection(): Connection; - function createConnection(uri: string, options?: ConnectionOption): Connection; - function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; - function disconnect(callback?: (err?: any) => void): Mongoose; - - function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - function modelNames(): string[]; - function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; - - function get(key: string): any; - function set(key: string, value: any): void; - - var mongo: any; - var mquery: any; - var version: string; - var connection: Connection; - - export class Mongoose { - connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; - createConnection(): Connection; - createConnection(uri: string, options?: Object): Connection; - createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; - disconnect(callback?: (err?: any) => void): Mongoose; - get(key: string): any; - model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - modelNames(): string[]; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; - set(key: string, value: any): void; - - mongo: any; - mquery: any; - version: string; - connection: Connection; - } - - export interface Connection extends NodeJS.EventEmitter { - constructor(base: Mongoose): Connection; - - close(callback?: (err: any) => void): Connection; - collection(name: string, options?: Object): Collection; - model(name: string, schema?: Schema, collection?: string): Model; - modelNames(): string[]; - open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection; - openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection; - - db: any; - collections: {[index: string]: Collection}; - readyState: number; - } - export interface ConnectionOption { - db?: any; - server?: any; - replset?: any; - user?: string; - pass?: string; - auth?: any; - } - export interface ConnectionSetOption extends ConnectionOption { - mongos?: boolean; - } - - export interface Collection { - } - - - export class SchemaType { } - export class VirtualType { - get(fn: Function): VirtualType; - set(fn: Function): VirtualType; - } - export module Types { - export class ObjectId { - constructor(id: string|number); - toHexString(): string; - equals(other: ObjectId): boolean; - getTimestamp(): Date; - isValid(): boolean; - static createFromTime(time: number): ObjectId; - static createFromHexString(hexString: string): ObjectId; - } - } - - export class Schema { - static Types: { - String: String; - ObjectId: Types.ObjectId; - OId: Types.ObjectId; - Mixed: any; - }; - constructor(schema?: Object, options?: Object); - - add(obj: Object, prefix?: string): void; - eachPath(fn: (path: string, type: any) => void): Schema; - get(key: string): any; - index(fields: Object, options?: Object): Schema; - indexes(): void; - method(name: string, fn: Function): Schema; - method(method: Object): Schema; - path(path: string): any; - path(path: string, constructor: any): Schema; - pathType(path: string): string; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; - post(method: string, fn: Function): Schema; - pre(method: string, callback: Function): Schema; - requiredPaths(): string[]; - set(key: string, value: any): void; - static(name: string, fn: Function): Schema; - virtual(name: string, options?: Object): VirtualType; - virtualpath(name: string): VirtualType; - } - export interface SchemaOption { - autoIndex?: boolean; - bufferCommands?: boolean; - capped?: boolean; - collection?: string; - id?: boolean; - _id?: boolean; - minimize?: boolean; - read?: string; - safe?: boolean; - shardKey?: boolean; - strict?: boolean; - toJSON?: Object; - toObject?: Object; - versionKey?: boolean; - } - - export interface Model extends NodeJS.EventEmitter { - new(doc: Object): T; - - aggregate(...aggregations: Object[]): Aggregate; - aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; - count(conditions: Object, callback?: (err: any, count: number) => void): Query; - - create(doc: Object, fn?: (err: any, res: T) => void): Promise; - create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; - create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; - discriminator(name: string, schema: Schema): Model; - distinct(field: string, callback?: (err: any, res: T[]) => void): Query; - distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; - ensureIndexes(callback: (err: any) => void): Promise; - - find(cond: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; - findById(id: string, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - - geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query; - geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query; - geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; - increment(): T; - mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - model(name: string): Model; - - populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; - populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; - update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - remove(cond: Object, callback?: (err: any) => void): Query<{}>; - save(callback?: (err: any, result: T, numberAffected: number) => void): Query; - where(path: string, val?: Object): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - base: Mongoose; - collection: Collection; - db: any; - discriminators: any; - modelName: string; - schema: Schema; - } - export interface FindAndUpdateOption { - new?: boolean; - upsert?: boolean; - sort?: Object; - select?: Object; - } - export interface GeoSearchOption { - near: number[]; - maxDistance: number; - limit?: number; - lean?: boolean; - } - export interface MapReduceOption { - map: () => void; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceOption2 { - map: string; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceResult { - _id: Key; - value: Val; - } - - export class Query { - exec(callback?: (err: any, res: T) => void): Promise; - exec(operation: string, callback?: (err: any, res: T) => void): Promise; - exec(operation: Function, callback?: (err: any, res: T) => void): Promise; - - all(val: number): Query; - all(path: string, val: number): Query; - and(array: Object[]): Query; - box(val: Object): Query; - box(a: number[], b: number[]): Query; - batchSize(val: number): Query; - cast(model: Model, obj: Object): U; - //center(): Query; - //centerSphere(path: string, val: Object): Query; - circle(area: Object): Query; - circle(path: string, area: Object): Query; - comment(val: any): Query; - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; - distinct(callback?: (err: any, res: T) => void): Query; - distinct(field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; - elemMatch(criteria: Object): Query; - elemMatch(criteria: (elem: Query) => void): Query; - elemMatch(path: string, criteria: Object): Query; - elemMatch(path: string, criteria: (elem: Query) => void): Query; - equals(val: Object): Query; - exists(val?: boolean): Query; - exists(path: string, val?: boolean): Query; - find(callback?: (err: any, res: T) => void): Query; - find(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOne(callback?: (err: any, res: T) => void): Query; - findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - geometry(object: Object): Query; - gt(val: number): Query; - gt(path: string, val: number): Query; - gte(val: number): Query; - gte(path: string, val: number): Query; - hint(val: Object): Query; - in(val: any[]): Query; - in(path: string, val: any[]): Query; - intersects(arg?: Object): Query; - lean(bool?: boolean): Query; - limit(val: number): Query; - lt(val: number): Query; - lt(path: string, val: number): Query; - lte(val: number): Query; - lte(path: string, val: number): Query; - maxDistance(val: number): Query; - maxDistance(path: string, val: number): Query; - maxScan(val: number): Query; - merge(source: Query): Query; - merge(source: Object): Query; - mod(val: number[]): Query; - mod(path: string, val: number[]): Query; - ne(val: any): Query; - ne(path: string, val: any): Query; - near(val: Object): Query; - near(path: string, val: Object): Query; - nearSphere(val: Object): Query; - nearSphere(path: string, val: Object): Query; - nin(val: any[]): Query; - nin(path: string, val: any[]): Query; - nor(array: Object[]): Query; - or(array: Object[]): Query; - polygon(...coordinatePairs: number[][]): Query; - polygon(path: string, ...coordinatePairs: number[][]): Query; - populate(path: string, select?: string, match?: Object, options?: Object): Query; - populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; - populate(opt: PopulateOption): Query; - read(pref: string, tags?: Object[]): Query; - regex(val: RegExp): Query; - regex(path: string, val: RegExp): Query; - remove(callback?: (err: any, res: T) => void): Query; - remove(criteria: Object, callback?: (err: any, res: T) => void): Query; - select(arg: string): Query; - select(arg: Object): Query; - setOptions(options: Object): Query; - size(val: number): Query; - size(path: string, val: number): Query; - skip(val: number): Query; - slaveOk(v?: boolean): Query; - slice(val: number): Query; - slice(val: number[]): Query; - slice(path: string, val: number): Query; - slice(path: string, val: number[]): Query; - snapshot(v?: boolean): Query; - sort(arg: Object): Query; - sort(arg: string): Query; - stream(options?: { transform?: Function; }): QueryStream; - tailable(v?: boolean): Query; - toConstructor(): Query; - update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - where(path?: string, val?: any): Query; - where(path?: Object, val?: any): Query; - within(val?: Object): Query; - within(coordinate: number[], ...coordinatePairs: number[][]): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - static use$geoWithin: boolean; - } - - export interface PopulateOption { - path: string; - select?: string; - model?: string; - match?: Object; - options?: Object; - } - - export interface QueryStream extends NodeJS.EventEmitter { - destory(err?: any): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - paused: number; - readable: boolean; - } - - export interface Document { - id?: string; - _id: Types.ObjectId; - - equals(doc: Document): boolean; - get(path: string, type?: new(...args: any[]) => any): any; - inspect(options?: Object): string; - invalidate(path: string, errorMsg: string, value: any): void; - invalidate(path: string, error: Error, value: any): void; - isDirectModified(path: string): boolean; - isInit(path: string): boolean; - isModified(path?: string): boolean; - isSelected(path: string): boolean; - markModified(path: string): void; - modifiedPaths(): string[]; - populate(callback?: (err: any, res: T) => void): Document; - populate(path?: string, callback?: (err: any, res: T) => void): Document; - populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; - populated(path: string): any; - remove(callback?: (err: any) => void): Query; - save(callback?: (err: any, res: T) => void): void; - set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; - set(path: string, val: any, options?: Object): void; - set(value: Object): void; - toJSON(options?: Object): Object; - toObject(options?: Object): Object; - toString(): string; - update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; - validate(cb: (err: any) => void): void; - - isNew: boolean; - errors: Object; - schema: Object; - } - - - export class Aggregate { - constructor(...options: Object[]); - - append(...options: Object[]): Aggregate; - group(arg: Object): Aggregate; - limit(num: number): Aggregate; - match(arg: Object): Aggregate; - near(parameters: Object): Aggregate; - project(arg: string): Aggregate; - project(arg: Object): Aggregate; - select(filter: string): Aggregate; - skip(num: number): Aggregate; - sort(arg: string): Aggregate; - sort(arg: Object): Aggregate; - unwind(fiels: string, ...rest: string[]): Aggregate; - - exec(callback?: (err: any, result: T) => void): Promise; - read(pref: string, ...tags: Object[]): Aggregate; - } - - export class Promise { - constructor(fn?: (err: any, result: T) => void); - - then(onFulFill: (result: T) => void, onReject?: (err: any) => void): Promise; - end(): void; - - fulfill(result: T): Promise; - reject(err: any): Promise; - resolve(err: any, result: T): Promise; - - onFulfill(listener: (result: T) => void): Promise; - onReject(listener: (err: any) => void): Promise; - onResolve(listener: (err: any, result: T) => void): Promise; - on(event: string, listener: Function): Promise; - - // Deprecated methods. - addBack(listener: (err: any, result: T) => void): Promise; - addCallback(listener: (result: T) => void): Promise; - addErrback(listener: (err: any) => void): Promise; - complete(result: T): Promise; - error(err: any): Promise; - } - -} \ No newline at end of file diff --git a/typings/browser/ambient/node/index.d.ts b/typings/browser/ambient/node/index.d.ts deleted file mode 100644 index e9b4c3d..0000000 --- a/typings/browser/ambient/node/index.d.ts +++ /dev/null @@ -1,2377 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4f479b281cb116de213cc5301f273018c13c7267/node/node.d.ts -// Type definitions for Node.js v4.x -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/************************************************ -* * -* Node.js v4.x API * -* * -************************************************/ - -interface Error { - stack?: string; -} - - -// 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 {} - -/************************************************ -* * -* GLOBAL * -* * -************************************************/ -declare var process: NodeJS.Process; -declare var global: NodeJS.Global; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearTimeout(timeoutId: NodeJS.Timer): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearInterval(intervalId: NodeJS.Timer): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; -declare function clearImmediate(immediateId: any): void; - -interface NodeRequireFunction { - (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve(id:string): string; - cache: any; - extensions: any; - main: any; -} - -declare var require: NodeRequire; - -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: any; - children: any[]; -} - -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; -}; - - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer {} - -/** - * 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; -}; - -/************************************************ -* * -* GLOBAL INTERFACES * -* * -************************************************/ -declare namespace NodeJS { - 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; - 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; - listenerCount(type: string): number; - } - - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string|Buffer; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - 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; - 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 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; - - 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 Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - openssl: string; - }; - 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[]; - domain: Domain; - - // 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 Timer { - ref() : void; - unref() : void; - } -} - -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - 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): Buffer; - // TODO: encoding param - indexOf(value: string | number | Buffer, byteOffset?: number): number; - // TODO: entries - // TODO: includes - // TODO: keys - // TODO: values -} - -/************************************************ -* * -* MODULES * -* * -************************************************/ -declare module "buffer" { - 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 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; -} - -declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated - static defaultMaxListeners: 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; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } -} - -declare module "http" { - 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 Server extends events.EventEmitter, net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - } - /** - * @deprecated Use IncomingMessage - */ - export interface ServerRequest extends IncomingMessage { - connection: net.Socket; - } - export interface ServerResponse extends events.EventEmitter, 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; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - 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 ClientRequest extends events.EventEmitter, 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 events.EventEmitter, stream.Readable { - httpVersion: string; - 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; - } - /** - * @deprecated Use IncomingMessage - */ - export interface ClientResponse extends IncomingMessage { } - - 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; - - 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; - } - - 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; -} - -declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } - - export interface Address { - address: string; - port: number; - addressType: string; - } - - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): 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 - }; - - // 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; } - - 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 deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function unzipSync(buf: Buffer, 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 tmpdir(): string; - export function homedir(): string; - export function endianness(): string; - 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 var EOL: string; -} - -declare module "https" { - 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 RequestOptions extends http.RequestOptions{ - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } - - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): 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; -} - -declare module "repl" { - import * as stream from "stream"; - import * as events from "events"; - - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): events.EventEmitter; -} - -declare module "readline" { - 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 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; - } - - export interface CompleterResult { - completions: string[]; - line: 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 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"; - - 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): void; - disconnect(): void; - unref(): void; - } - - 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 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 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 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 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 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?: 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?: any; // string | Object - 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; -} - -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[]; -} - -declare module "net" { - 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; - - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): void; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): void; - resume(): 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; - - // 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 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 Socket { - 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(handle: any, backlog?: number, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - listen(options: ListenOptions, 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; - } - 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"; - - interface RemoteInfo { - address: string; - port: number; - size: number; - } - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - close(): 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; - } -} - -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; - } - - export interface ReadStream extends stream.Readable { - close(): void; - } - export interface WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - } - - /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /** - * Synchronous rename - * @param oldPath - * @param newPath - */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string, 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, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string, 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, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, 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, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, 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): Stats; - export function lstatSync(path: string): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, 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. - */ - export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous unlink - deletes the file specified in {path} - * - * @param path - */ - export function unlinkSync(path: string): 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. - */ - export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path - */ - export function rmdirSync(path: string): 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. - */ - export function mkdir(path: string, 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. - */ - export function mkdir(path: string, 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. - */ - export function mkdir(path: string, 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, 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, mode?: string): void; - export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function utimesSync(path: string, 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, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; - /** Constant for fs.access(). File is visible to the calling process. */ - export var F_OK: number; - /** Constant for fs.access(). File can be read by the calling process. */ - export var R_OK: number; - /** Constant for fs.access(). File can be written by the calling process. */ - export var W_OK: number; - /** Constant for fs.access(). File can be executed by the calling process. */ - export var X_OK: number; - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string, 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, mode ?: number): void; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - }): WriteStream; -} - -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:\' - */ - 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: any[]): 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: 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; - /** - * 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; - 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" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; - } - 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"; - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - host?: string; - port?: number; - pfx?: any; //string or buffer - key?: any; //string or buffer - passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array - ciphers?: string; - honorCipherOrder?: any; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; - } - - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer - passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer - rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer - servername?: string; - } - - export interface Server extends net.Server { - close(): 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 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?: any; //string | buffer - key?: any; //string | buffer - passphrase?: string; - cert?: any; // string | buffer - ca?: any; // string | buffer - crl?: any; // 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: TlsOptions, 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" { - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: any; //string | string array - crl: any; //string | string array - 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): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - export interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; - digest(): Buffer; - } - 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: "utf8"|"ascii"|"binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; - update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - getAuthTag(): Buffer; - } - 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: "binary"|"base64"|"hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; - update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; - setAuthTag(tag: Buffer): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - export interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_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 getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - 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) : 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 RsaPublicKey { - key: string; - padding?: any; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: any; - } - export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer -} - -declare module "stream" { - import * as events from "events"; - - export class Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } - - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - 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; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _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 DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _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 ReadableOptions, WritableOptions {} - - // 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); - _transform(chunk: any, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - 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 {} -} - -declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; - } - - 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; -} - -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; - - 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 = internal; -} - -declare module "tty" { - 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; - } -} - -declare module "domain" { - 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; - } - - 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_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: 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; -} \ No newline at end of file diff --git a/typings/browser/ambient/pluralize/index.d.ts b/typings/browser/ambient/pluralize/index.d.ts deleted file mode 100644 index 43daef9..0000000 --- a/typings/browser/ambient/pluralize/index.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/101a5daef4fc42eca0d447ba5d080248f80daf90/pluralize/pluralize.d.ts -// Type definitions for pluralize -// Project: https://www.npmjs.com/package/pluralize -// Definitions by: Syu Kato -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface PluralizeStatic { - /** - * Pluralize or singularize a word based on the passed in count. - * - * @param word - * @param count - * @param inclusive - */ - (word: string, count?: number, inclusive?: boolean): string; - - /** - * Pluralize a word based. - * - * @param word - */ - plural(word: string): string; - - /** - * Singularize a word based. - * - * @param word - */ - singular(word: string): string; - - /** - * Add a pluralization rule to the collection. - * - * @param rule - * @param replacement - */ - addPluralRule(rule: string|RegExp, replacemant: string): void; - - /** - * Add a singularization rule to the collection. - * - * @param rule - * @param replacement - */ - addSingularRule(rule: string|RegExp, replacemant: string): void; - - /** - * Add an irregular word definition. - * - * @param single - * @param plural - */ - addIrregularRule(single: string, plural: string): void; - - /** - * Add an uncountable word rule. - * - * @param word - */ - addUncountableRule(word: string|RegExp): void; -} - -declare module "pluralize" { - export = pluralize; -} -declare var pluralize: PluralizeStatic; \ No newline at end of file diff --git a/typings/browser/ambient/sinon-chai/index.d.ts b/typings/browser/ambient/sinon-chai/index.d.ts deleted file mode 100644 index 0b923d7..0000000 --- a/typings/browser/ambient/sinon-chai/index.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon-chai/sinon-chai.d.ts -// Type definitions for sinon-chai 2.7.0 -// Project: https://github.com/domenic/sinon-chai -// Definitions by: Kazi Manzur Rashid , Jed Mao -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -declare module Chai { - - interface LanguageChains { - always: Assertion; - } - - interface Assertion { - /** - * true if the spy was called at least once. - */ - called: Assertion; - /** - * @param count The number of recorded calls. - */ - callCount(count: number): Assertion; - /** - * true if the spy was called exactly once. - */ - calledOnce: Assertion; - /** - * true if the spy was called exactly twice. - */ - calledTwice: Assertion; - /** - * true if the spy was called exactly thrice. - */ - calledThrice: Assertion; - /** - * Returns true if the spy was called before anotherSpy. - */ - calledBefore(anotherSpy: Sinon.SinonSpy): Assertion; - /** - * Returns true if the spy was called after anotherSpy. - */ - calledAfter(anotherSpy: Sinon.SinonSpy): Assertion; - /** - * Returns true if spy/stub was called with the new operator. Beware that - * this is inferred based on the value of the this object and the spy - * function's prototype, so it may give false positives if you actively - * return the right kind of object. - */ - calledWithNew: Assertion; - /** - * Returns true if context was this for this call. - */ - calledOn(context: any): Assertion; - /** - * Returns true if call received provided arguments (and possibly others). - */ - calledWith(...args: any[]): Assertion; - /** - * Returns true if call received provided arguments and no others. - */ - calledWithExactly(...args: any[]): Assertion; - /** - * Returns true if call received matching arguments (and possibly others). - * This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). - */ - calledWithMatch(...args: any[]): Assertion; - /** - * Returns true if spy returned the provided value at least once. Uses - * deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) - * for strict comparison (see matchers). - */ - returned(obj: any): Assertion; - /** - * Returns true if spy threw the provided exception object at least once. - */ - thrown(obj?: Error|typeof Error|string): Assertion; - } -} - -declare module "sinon-chai" { - function sinonChai(chai: any, utils: any): void; - export = sinonChai; -} \ No newline at end of file diff --git a/typings/browser/ambient/sinon/index.d.ts b/typings/browser/ambient/sinon/index.d.ts deleted file mode 100644 index 4b743f9..0000000 --- a/typings/browser/ambient/sinon/index.d.ts +++ /dev/null @@ -1,422 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/sinon/sinon.d.ts -// Type definitions for Sinon 1.8.1 -// Project: http://sinonjs.org/ -// Definitions by: William Sears -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module Sinon { - interface SinonSpyCallApi { - // Properties - thisValue: any; - args: any[]; - exception: any; - returnValue: any; - - // Methods - calledOn(obj: any): boolean; - calledWith(...args: any[]): boolean; - calledWithExactly(...args: any[]): boolean; - calledWithMatch(...args: any[]): boolean; - notCalledWith(...args: any[]): boolean; - notCalledWithMatch(...args: any[]): boolean; - returned(value: any): boolean; - threw(): boolean; - threw(type: string): boolean; - threw(obj: any): boolean; - callArg(pos: number): void; - callArgOn(pos: number, obj: any, ...args: any[]): void; - callArgWith(pos: number, ...args: any[]): void; - callArgOnWith(pos: number, obj: any, ...args: any[]): void; - yield(...args: any[]): void; - yieldOn(obj: any, ...args: any[]): void; - yieldTo(property: string, ...args: any[]): void; - yieldToOn(property: string, obj: any, ...args: any[]): void; - } - - interface SinonSpyCall extends SinonSpyCallApi { - calledBefore(call: SinonSpyCall): boolean; - calledAfter(call: SinonSpyCall): boolean; - calledWithNew(call: SinonSpyCall): boolean; - } - - interface SinonSpy extends SinonSpyCallApi { - // Properties - callCount: number; - called: boolean; - notCalled: boolean; - calledOnce: boolean; - calledTwice: boolean; - calledThrice: boolean; - firstCall: SinonSpyCall; - secondCall: SinonSpyCall; - thirdCall: SinonSpyCall; - lastCall: SinonSpyCall; - thisValues: any[]; - args: any[][]; - exceptions: any[]; - returnValues: any[]; - - // Methods - (...args: any[]): any; - calledBefore(anotherSpy: SinonSpy): boolean; - calledAfter(anotherSpy: SinonSpy): boolean; - calledWithNew(spy: SinonSpy): boolean; - withArgs(...args: any[]): SinonSpy; - alwaysCalledOn(obj: any): boolean; - alwaysCalledWith(...args: any[]): boolean; - alwaysCalledWithExactly(...args: any[]): boolean; - alwaysCalledWithMatch(...args: any[]): boolean; - neverCalledWith(...args: any[]): boolean; - neverCalledWithMatch(...args: any[]): boolean; - alwaysThrew(): boolean; - alwaysThrew(type: string): boolean; - alwaysThrew(obj: any): boolean; - alwaysReturned(): boolean; - invokeCallback(...args: any[]): void; - getCall(n: number): SinonSpyCall; - reset(): void; - printf(format: string, ...args: any[]): string; - restore(): void; - } - - interface SinonSpyStatic { - (): SinonSpy; - (func: any): SinonSpy; - (obj: any, method: string): SinonSpy; - } - - interface SinonStatic { - spy: SinonSpyStatic; - } - - interface SinonStub extends SinonSpy { - resetBehavior(): void; - returns(obj: any): SinonStub; - returnsArg(index: number): SinonStub; - throws(type?: string): SinonStub; - throws(obj: any): SinonStub; - callsArg(index: number): SinonStub; - callsArgOn(index: number, context: any): SinonStub; - callsArgWith(index: number, ...args: any[]): SinonStub; - callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; - callsArgAsync(index: number): SinonStub; - callsArgOnAsync(index: number, context: any): SinonStub; - callsArgWithAsync(index: number, ...args: any[]): SinonStub; - callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; - onCall(n: number): SinonStub; - onFirstCall(): SinonStub; - onSecondCall(): SinonStub; - onThirdCall(): SinonStub; - yields(...args: any[]): SinonStub; - yieldsOn(context: any, ...args: any[]): SinonStub; - yieldsTo(property: string, ...args: any[]): SinonStub; - yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; - yieldsAsync(...args: any[]): SinonStub; - yieldsOnAsync(context: any, ...args: any[]): SinonStub; - yieldsToAsync(property: string, ...args: any[]): SinonStub; - yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; - withArgs(...args: any[]): SinonStub; - } - - interface SinonStubStatic { - (): SinonStub; - (obj: any): SinonStub; - (obj: any, method: string): SinonStub; - (obj: any, method: string, func: any): SinonStub; - } - - interface SinonStatic { - stub: SinonStubStatic; - } - - interface SinonExpectation extends SinonStub { - atLeast(n: number): SinonExpectation; - atMost(n: number): SinonExpectation; - never(): SinonExpectation; - once(): SinonExpectation; - twice(): SinonExpectation; - thrice(): SinonExpectation; - exactly(n: number): SinonExpectation; - withArgs(...args: any[]): SinonExpectation; - withExactArgs(...args: any[]): SinonExpectation; - on(obj: any): SinonExpectation; - verify(): SinonExpectation; - restore(): void; - } - - interface SinonExpectationStatic { - create(methodName?: string): SinonExpectation; - } - - interface SinonMock { - expects(method: string): SinonExpectation; - restore(): void; - verify(): void; - } - - interface SinonMockStatic { - (): SinonExpectation; - (obj: any): SinonMock; - } - - interface SinonStatic { - expectation: SinonExpectationStatic; - mock: SinonMockStatic; - } - - interface SinonFakeTimers { - now: number; - create(now: number): SinonFakeTimers; - setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; - clearTimeout(id: number): void; - setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; - clearInterval(id: number): void; - tick(ms: number): number; - reset(): void; - Date(): Date; - Date(year: number): Date; - Date(year: number, month: number): Date; - Date(year: number, month: number, day: number): Date; - Date(year: number, month: number, day: number, hour: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; - restore(): void; - } - - interface SinonFakeTimersStatic { - (): SinonFakeTimers; - (...timers: string[]): SinonFakeTimers; - (now: number, ...timers: string[]): SinonFakeTimers; - } - - interface SinonStatic { - useFakeTimers: SinonFakeTimersStatic; - clock: SinonFakeTimers; - } - - interface SinonFakeUploadProgress { - eventListeners: { - progress: any[]; - load: any[]; - abort: any[]; - error: any[]; - }; - - addEventListener(event: string, listener: (e: Event) => any): void; - removeEventListener(event: string, listener: (e: Event) => any): void; - dispatchEvent(event: Event): void; - } - - interface SinonFakeXMLHttpRequest { - // Properties - onCreate: (xhr: SinonFakeXMLHttpRequest) => void; - url: string; - method: string; - requestHeaders: any; - requestBody: string; - status: number; - statusText: string; - async: boolean; - username: string; - password: string; - withCredentials: boolean; - upload: SinonFakeUploadProgress; - responseXML: Document; - getResponseHeader(header: string): string; - getAllResponseHeaders(): any; - - // Methods - restore(): void; - useFilters: boolean; - addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; - setResponseHeaders(headers: any): void; - setResponseBody(body: string): void; - respond(status: number, headers: any, body: string): void; - autoRespond(ms: number): void; - } - - interface SinonFakeXMLHttpRequestStatic { - (): SinonFakeXMLHttpRequest; - } - - interface SinonStatic { - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - FakeXMLHttpRequest: SinonFakeXMLHttpRequest; - } - - interface SinonFakeServer { - // Properties - autoRespond: boolean; - autoRespondAfter: number; - fakeHTTPMethods: boolean; - getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; - requests: SinonFakeXMLHttpRequest[]; - - // Methods - respondWith(body: string): void; - respondWith(response: any[]): void; - respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(url: string, body: string): void; - respondWith(url: string, response: any[]): void; - respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(method: string, url: string, body: string): void; - respondWith(method: string, url: string, response: any[]): void; - respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(url: RegExp, body: string): void; - respondWith(url: RegExp, response: any[]): void; - respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respondWith(method: string, url: RegExp, body: string): void; - respondWith(method: string, url: RegExp, response: any[]): void; - respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; - respond(): void; - restore(): void; - } - - interface SinonFakeServerStatic { - create(): SinonFakeServer; - } - - interface SinonStatic { - fakeServer: SinonFakeServerStatic; - fakeServerWithClock: SinonFakeServerStatic; - } - - interface SinonExposeOptions { - prefix?: string; - includeFail?: boolean; - } - - interface SinonAssert { - // Properties - failException: string; - fail: (message?: string) => void; // Overridable - pass: (assertion: any) => void; // Overridable - - // Methods - notCalled(spy: SinonSpy): void; - called(spy: SinonSpy): void; - calledOnce(spy: SinonSpy): void; - calledTwice(spy: SinonSpy): void; - calledThrice(spy: SinonSpy): void; - callCount(spy: SinonSpy, count: number): void; - callOrder(...spies: SinonSpy[]): void; - calledOn(spy: SinonSpy, obj: any): void; - alwaysCalledOn(spy: SinonSpy, obj: any): void; - calledWith(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; - neverCalledWith(spy: SinonSpy, ...args: any[]): void; - calledWithExactly(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; - calledWithMatch(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; - threw(spy: SinonSpy): void; - threw(spy: SinonSpy, exception: string): void; - threw(spy: SinonSpy, exception: any): void; - alwaysThrew(spy: SinonSpy): void; - alwaysThrew(spy: SinonSpy, exception: string): void; - alwaysThrew(spy: SinonSpy, exception: any): void; - expose(obj: any, options?: SinonExposeOptions): void; - } - - interface SinonStatic { - assert: SinonAssert; - } - - interface SinonMatcher { - and(expr: SinonMatcher): SinonMatcher; - or(expr: SinonMatcher): SinonMatcher; - } - - interface SinonMatch { - (value: number): SinonMatcher; - (value: string): SinonMatcher; - (expr: RegExp): SinonMatcher; - (obj: any): SinonMatcher; - (callback: (value: any) => boolean): SinonMatcher; - any: SinonMatcher; - defined: SinonMatcher; - truthy: SinonMatcher; - falsy: SinonMatcher; - bool: SinonMatcher; - number: SinonMatcher; - string: SinonMatcher; - object: SinonMatcher; - func: SinonMatcher; - array: SinonMatcher; - regexp: SinonMatcher; - date: SinonMatcher; - same(obj: any): SinonMatcher; - typeOf(type: string): SinonMatcher; - instanceOf(type: any): SinonMatcher; - has(property: string, expect?: any): SinonMatcher; - hasOwn(property: string, expect?: any): SinonMatcher; - } - - interface SinonStatic { - match: SinonMatch; - } - - interface SinonSandboxConfig { - injectInto?: any; - properties?: string[]; - useFakeTimers?: any; - useFakeServer?: any; - } - - interface SinonSandbox { - clock: SinonFakeTimers; - requests: SinonFakeXMLHttpRequest; - server: SinonFakeServer; - spy: SinonSpyStatic; - stub: SinonStubStatic; - mock: SinonMockStatic; - useFakeTimers: SinonFakeTimersStatic; - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - useFakeServer(): SinonFakeServer; - restore(): void; - } - - interface SinonSandboxStatic { - create(): SinonSandbox; - create(config: SinonSandboxConfig): SinonSandbox; - } - - interface SinonStatic { - sandbox: SinonSandboxStatic; - } - - interface SinonTestConfig { - injectIntoThis?: boolean; - injectInto?: any; - properties?: string[]; - useFakeTimers?: boolean; - useFakeServer?: boolean; - } - - interface SinonTestWrapper extends SinonSandbox { - (...args: any[]): any; - } - - interface SinonStatic { - config: SinonTestConfig; - test(fn: (...args: any[]) => any): SinonTestWrapper; - testCase(tests: any): any; - } - - // Utility overridables - interface SinonStatic { - createStubInstance(constructor: any): SinonStub; - format(obj: any): string; - log(message: string): void; - restore(object: any): void; - } -} - -declare var sinon: Sinon.SinonStatic; - -declare module "sinon" { - export = sinon; -} \ No newline at end of file diff --git a/typings/browser/ambient/superagent/index.d.ts b/typings/browser/ambient/superagent/index.d.ts deleted file mode 100644 index 485a146..0000000 --- a/typings/browser/ambient/superagent/index.d.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/superagent/superagent.d.ts -// Type definitions for SuperAgent v1.4.0 -// Project: https://github.com/visionmedia/superagent -// Definitions by: Alex Varju -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare module "superagent" { - import stream = require('stream'); - - type CallbackHandler = (err: any, res: request.Response) => void; - - var request: request.SuperAgentStatic; - - namespace request { - interface SuperAgentStatic extends SuperAgent { - (url: string): SuperAgentRequest; - (method: string, url: string): SuperAgentRequest; - - agent(): SuperAgent; - } - - interface SuperAgent> extends stream.Stream { - get(url: string, callback?: CallbackHandler): Req; - post(url: string, callback?: CallbackHandler): Req; - put(url: string, callback?: CallbackHandler): Req; - head(url: string, callback?: CallbackHandler): Req; - del(url: string, callback?: CallbackHandler): Req; - delete(url: string, callback?: CallbackHandler): Req; - options(url: string, callback?: CallbackHandler): Req; - trace(url: string, callback?: CallbackHandler): Req; - copy(url: string, callback?: CallbackHandler): Req; - lock(url: string, callback?: CallbackHandler): Req; - mkcol(url: string, callback?: CallbackHandler): Req; - move(url: string, callback?: CallbackHandler): Req; - purge(url: string, callback?: CallbackHandler): Req; - propfind(url: string, callback?: CallbackHandler): Req; - proppatch(url: string, callback?: CallbackHandler): Req; - unlock(url: string, callback?: CallbackHandler): Req; - report(url: string, callback?: CallbackHandler): Req; - mkactivity(url: string, callback?: CallbackHandler): Req; - checkout(url: string, callback?: CallbackHandler): Req; - merge(url: string, callback?: CallbackHandler): Req; - // m-search(url: string, callback?: CallbackHandler): Req; - notify(url: string, callback?: CallbackHandler): Req; - subscribe(url: string, callback?: CallbackHandler): Req; - unsubscribe(url: string, callback?: CallbackHandler): Req; - patch(url: string, callback?: CallbackHandler): Req; - search(url: string, callback?: CallbackHandler): Req; - connect(url: string, callback?: CallbackHandler): Req; - - parse(fn: Function): Req; - saveCookies(res: Response): void; - attachCookies(req: Req): void; - } - - interface Response extends NodeJS.ReadableStream { - text: string; - body: any; - files: any; - header: any; - type: string; - charset: string; - status: number; - statusType: number; - info: boolean; - ok: boolean; - redirect: boolean; - clientError: boolean; - serverError: boolean; - error: Error; - accepted: boolean; - noContent: boolean; - badRequest: boolean; - unauthorized: boolean; - notAcceptable: boolean; - notFound: boolean; - forbidden: boolean; - get(header: string): string; - } - - interface Request> /* extends NodeJS.WritableStream */ { - abort(): void; - accept(type: string): Req; - attach(field: string, file: string, filename?: string): Req; - auth(user: string, name: string): Req; - buffer(val: boolean): Req; - clearTimeout(): Req; - end(callback?: CallbackHandler): Req; - field(name: string, val: string): Req; - get(field: string): string; - on(name: string, handler: Function): Req; - on(name: 'error', handler: (err: any) => void): Req; - part(): Req; - pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; - query(val: Object): Req; - redirects(n: number): Req; - send(data: string): Req; - send(data: Object): Req; - send(): Req; - set(field: string, val: string): Req; - set(field: Object): Req; - timeout(ms: number): Req; - type(val: string): Req; - use(fn: Function): Req; - withCredentials(): Req; - write(data: string, encoding?: string): Req; - write(data: Buffer, encoding?: string): Req; - } - interface SuperAgentRequest extends Request>>> {} - - } - - export = request; -} \ No newline at end of file diff --git a/typings/browser/ambient/supertest/index.d.ts b/typings/browser/ambient/supertest/index.d.ts deleted file mode 100644 index 682de62..0000000 --- a/typings/browser/ambient/supertest/index.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Generated by typings -// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/8c7444882a2bc2ab87387f8f736a7d97e89b9c90/supertest/supertest.d.ts -// Type definitions for SuperTest 0.14.0 -// Project: https://github.com/visionmedia/supertest -// Definitions by: Alex Varju -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -declare module "supertest" { - import superagent = require('superagent'); - - type CallbackHandler = { (err: any, res: supertest.Response): void; }|{ (res: supertest.Response): void; }; - - function supertest(app: any): supertest.SuperTest; - - module supertest { - function agent(app?: any): supertest.SuperTest; - - interface SuperTest extends superagent.SuperAgent { - } - - interface Test extends superagent.Request { - url: string; - serverAddress(app: any, path: string): string; - expect(status: number, callback?: CallbackHandler): Test; - expect(status: number, body: string, callback?: CallbackHandler): Test; - expect(body: string, callback?: CallbackHandler): Test; - expect(body: RegExp, callback?: CallbackHandler): Test; - expect(body: Object, callback?: CallbackHandler): Test; - expect(field: string, val: string, callback?: CallbackHandler): Test; - expect(field: string, val: RegExp, callback?: CallbackHandler): Test; - expect(checker: (res: Response) => any): Test; - } - - interface Response extends superagent.Response { - } - } - - export = supertest; -} \ No newline at end of file diff --git a/typings/main.d.ts b/typings/main.d.ts index 3b7c164..02ef1a3 100644 --- a/typings/main.d.ts +++ b/typings/main.d.ts @@ -1,3 +1,4 @@ +/// /// /// /// @@ -9,4 +10,3 @@ /// /// /// -/// diff --git a/wercker.yml b/wercker.yml index dddd7d3..19227b1 100644 --- a/wercker.yml +++ b/wercker.yml @@ -16,7 +16,10 @@ services: dev: steps: - npm-install - - npm-test + - internal/shell: + code: | + npm run ts + npm test build: # The steps that will be executed on build From 5789c7a30d1a32abf36ae16bc5b293c39cff80cc Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 20:31:43 +0200 Subject: [PATCH 08/13] fixed all tests --- lib/test/subresource/subresource.spec.js | 5 +++-- test/subresource/subresource.spec.ts | 2 +- wercker.yml | 3 +-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/test/subresource/subresource.spec.js b/lib/test/subresource/subresource.spec.js index 312bc45..cc6abfa 100644 --- a/lib/test/subresource/subresource.spec.js +++ b/lib/test/subresource/subresource.spec.js @@ -1,15 +1,16 @@ +"use strict"; var Yadda = require('yadda'); Yadda.plugins.mocha.ScenarioLevelPlugin.init(); var mongoose = require('mongoose'); process.env.DB = 'subTest'; require('../../examples/subresource/app'); var library = require('./definitions/sub.steps'); -var parentResource = require('../../examples/subresource/resources/parent'); +var parent_1 = require('../../examples/subresource/resources/parent'); new Yadda.FeatureFileSearch('test/subresource').each(function (file) { featureFile(file, function (feature) { var yadda = Yadda.createInstance(library); afterEach(function (done) { - parentResource.db.connection.db.dropDatabase(function (err, result) { + parent_1.parentResource.db.connection.db.dropDatabase(function (err, result) { done(); }); }); diff --git a/test/subresource/subresource.spec.ts b/test/subresource/subresource.spec.ts index 656aa67..4afac3a 100644 --- a/test/subresource/subresource.spec.ts +++ b/test/subresource/subresource.spec.ts @@ -8,7 +8,7 @@ process.env.DB = 'subTest'; require('../../examples/subresource/app'); var library = require('./definitions/sub.steps'); -var parentResource = require('../../examples/subresource/resources/parent'); +import { parentResource } from '../../examples/subresource/resources/parent'; new Yadda.FeatureFileSearch('test/subresource').each(function(file) { featureFile(file, function(feature) { diff --git a/wercker.yml b/wercker.yml index 19227b1..08d9161 100644 --- a/wercker.yml +++ b/wercker.yml @@ -18,8 +18,7 @@ dev: - npm-install - internal/shell: code: | - npm run ts - npm test + npm run test-watch build: # The steps that will be executed on build From b7b678ca00e7c801802a7732b47cedb032c7701d Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 20:41:05 +0200 Subject: [PATCH 09/13] using wercker for watching files --- wercker.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/wercker.yml b/wercker.yml index 08d9161..f660fd4 100644 --- a/wercker.yml +++ b/wercker.yml @@ -16,9 +16,11 @@ services: dev: steps: - npm-install - - internal/shell: + - internal/watch: code: | - npm run test-watch + npm run ts + npm test + reload: true build: # The steps that will be executed on build From 4c6f3452bdb529c269cf1754b17ac31ff26c85e5 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 20:45:49 +0200 Subject: [PATCH 10/13] updated code to es6 standard --- lib/src/authentication.js | 3 +-- lib/src/authorizedResource.js | 16 +++++++------ lib/src/userResource.js | 4 ++-- lib/test/subresource/subresource.spec.js | 8 +++---- src/authentication.ts | 6 ++--- src/authorizedResource.ts | 26 ++++++++++---------- src/authorizedSubResource.ts | 4 ++-- src/index.ts | 4 ++-- src/resource.ts | 30 ++++++++++++------------ src/subResource.ts | 16 ++++++------- src/userResource.ts | 10 ++++---- test/subresource/subresource.spec.ts | 25 +++++++++----------- 12 files changed, 74 insertions(+), 78 deletions(-) diff --git a/lib/src/authentication.js b/lib/src/authentication.js index d44997b..a2398a3 100644 --- a/lib/src/authentication.js +++ b/lib/src/authentication.js @@ -6,8 +6,7 @@ function encryptPassword(password) { } exports.encryptPassword = encryptPassword; function createAuthToken(userId) { - var authToken = AES.encrypt(userId + ';' + - new Date().getTime(), process.env.REST_IO_AES_KEY); + var authToken = AES.encrypt(userId + ";" + new Date().getTime(), process.env.REST_IO_AES_KEY); return authToken.toString(); } exports.createAuthToken = createAuthToken; diff --git a/lib/src/authorizedResource.js b/lib/src/authorizedResource.js index f7b379b..348611a 100644 --- a/lib/src/authorizedResource.js +++ b/lib/src/authorizedResource.js @@ -44,9 +44,10 @@ var AuthorizedResource = (function (_super) { }; AuthorizedResource.prototype.hasAuthorizedRole = function (roles, authorizedRoles) { var hasRole = false; - roles.forEach(function (role) { + roles.forEach(function (_a) { + var name = _a.name; authorizedRoles.forEach(function (authRole) { - if (role.name === authRole) { + if (name === authRole) { hasRole = true; } }); @@ -73,13 +74,14 @@ var AuthorizedResource = (function (_super) { promise.resolve(new Error('no token found'), null); return promise; } - var tokenDetails = auth.decryptAuthToken(authToken); - return this.getRoles(tokenDetails.id) - .then(function (user) { - if (_this.isTokenExpired(tokenDetails.createdAt)) { + var _a = auth.decryptAuthToken(authToken), id = _a.id, createdAt = _a.createdAt; + return this.getRoles(id) + .then(function (_a) { + var roles = _a.roles; + if (_this.isTokenExpired(createdAt)) { throw new Error('token expired'); } - return user.roles; + return roles; }) .then(function (roles) { if (!_this.hasAuthorizedRole(roles, authorizedRoles)) { diff --git a/lib/src/userResource.js b/lib/src/userResource.js index 1c4f9c6..708aec5 100644 --- a/lib/src/userResource.js +++ b/lib/src/userResource.js @@ -48,8 +48,8 @@ var UserResource = (function (_super) { }; UserResource.prototype.isSelf = function (req) { var authToken = req.header('Authorization'); - var tokenDetails = auth.decryptAuthToken(authToken); - return tokenDetails.id === req.params.userId; + var id = auth.decryptAuthToken(authToken).id; + return id === req.params.userId; }; UserResource.prototype.create = function (req, res) { req.body.password = auth.encryptPassword(req.body.password); diff --git a/lib/test/subresource/subresource.spec.js b/lib/test/subresource/subresource.spec.js index cc6abfa..20fcea5 100644 --- a/lib/test/subresource/subresource.spec.js +++ b/lib/test/subresource/subresource.spec.js @@ -1,7 +1,6 @@ "use strict"; var Yadda = require('yadda'); Yadda.plugins.mocha.ScenarioLevelPlugin.init(); -var mongoose = require('mongoose'); process.env.DB = 'subTest'; require('../../examples/subresource/app'); var library = require('./definitions/sub.steps'); @@ -10,12 +9,11 @@ new Yadda.FeatureFileSearch('test/subresource').each(function (file) { featureFile(file, function (feature) { var yadda = Yadda.createInstance(library); afterEach(function (done) { - parent_1.parentResource.db.connection.db.dropDatabase(function (err, result) { - done(); - }); + return parent_1.parentResource.db.connection.db + .dropDatabase(function (err, result) { return done(); }); }); scenarios(feature.scenarios, function (scenario, done) { - yadda.run(scenario.steps, done); + return yadda.run(scenario.steps, done); }); }); }); diff --git a/src/authentication.ts b/src/authentication.ts index 5317ed3..ee16a9c 100644 --- a/src/authentication.ts +++ b/src/authentication.ts @@ -6,13 +6,13 @@ export function encryptPassword(password: string) { } export function createAuthToken(userId: string) { - var authToken = AES.encrypt(userId + ';' + - new Date().getTime(), process.env.REST_IO_AES_KEY); + const authToken = AES.encrypt(`${userId};${new Date().getTime()}`, + process.env.REST_IO_AES_KEY); return authToken.toString(); } export function decryptAuthToken(authToken: string) { - var decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); + const decryptedMessage = AES.decrypt(authToken, process.env.REST_IO_AES_KEY); const [ id, createdAt ] = decryptedMessage.toString(enc.Utf8).split(';'); if (!id || !createdAt) { throw new Error('corrupt auth token'); diff --git a/src/authorizedResource.ts b/src/authorizedResource.ts index d66a3f6..2786e64 100644 --- a/src/authorizedResource.ts +++ b/src/authorizedResource.ts @@ -24,7 +24,7 @@ export default class AuthorizedResource extends Resource { }; isTokenExpired(createdAt: Date) { - var maxTokenLifeTime = new Date(); + const maxTokenLifeTime = new Date(); maxTokenLifeTime.setDate(maxTokenLifeTime.getDate() - this.maxDays); return createdAt < maxTokenLifeTime; } @@ -37,10 +37,10 @@ export default class AuthorizedResource extends Resource { } hasAuthorizedRole(roles: Array, authorizedRoles: Array) { - var hasRole = false; - roles.forEach((role) => { + let hasRole = false; + roles.forEach(({ name }) => { authorizedRoles.forEach((authRole: string) => { - if (role.name === authRole) { + if (name === authRole) { hasRole = true; } }); @@ -49,8 +49,8 @@ export default class AuthorizedResource extends Resource { } hasAccessRightsDefined(req: Request, authorizedRoles: Array) { - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); + const promise = new mongoose.Promise(); + const authToken = req.header('Authorization'); if (authorizedRoles.length === 0) { promise.resolve(null, null); return promise; @@ -58,8 +58,8 @@ export default class AuthorizedResource extends Resource { } isAuthorized(req: Request, authorizedRoles: Array) { - var promise = new mongoose.Promise(); - var authToken = req.header('Authorization'); + const promise = new mongoose.Promise(); + const authToken = req.header('Authorization'); if (authorizedRoles.length === 0) { promise.resolve(null, null); return promise; @@ -67,13 +67,13 @@ export default class AuthorizedResource extends Resource { promise.resolve(new Error('no token found'), null); return promise; } - var tokenDetails = auth.decryptAuthToken(authToken); - return this.getRoles(tokenDetails.id) - .then((user: any) => { - if (this.isTokenExpired(tokenDetails.createdAt)) { + const { id, createdAt } = auth.decryptAuthToken(authToken); + return this.getRoles(id) + .then(({ roles }: any) => { + if (this.isTokenExpired(createdAt)) { throw new Error('token expired'); } - return user.roles; + return roles; }) .then((roles: Array) => { if (!this.hasAuthorizedRole(roles, authorizedRoles)) { diff --git a/src/authorizedSubResource.ts b/src/authorizedSubResource.ts index 61bdd20..b858f04 100644 --- a/src/authorizedSubResource.ts +++ b/src/authorizedSubResource.ts @@ -6,11 +6,11 @@ import { Model, Document } from 'mongoose'; export default class AuthorizedSubResource extends AuthorizedResource { constructor(subResDef: ISubResource) { - var resDef = { + const resDef = { name: null, model: null }; - for (var prop in subResDef) { + for (let prop in subResDef) { if (subResDef.hasOwnProperty(prop)) { resDef[prop] = subResDef[prop]; } diff --git a/src/index.ts b/src/index.ts index bcca426..f5681f8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,8 +22,8 @@ export default class RestIO { app.use(bodyParser.json()); resource.registerApp(app, config.db); if (!!config) { - var resources: Object = autoloader.load(config.resources); - for (var i in resources) { + const resources: Object = autoloader.load(config.resources); + for (let i in resources) { if (resources.hasOwnProperty(i)) { // access to trigger getter of auto-loader resources[i]; diff --git a/src/resource.ts b/src/resource.ts index 1afe152..4741985 100644 --- a/src/resource.ts +++ b/src/resource.ts @@ -8,8 +8,8 @@ const { ObjectId } = Types; import * as pluralize from 'pluralize'; // The app reference it used to register params. -var app; -var db: Mongoose; +let app; +let db: Mongoose; export class Resource { static BASE_URL = '/api'; @@ -42,7 +42,7 @@ export class Resource { } createModel(resDef: IResource) { - var schema = new Schema(resDef.model); + const schema = new Schema(resDef.model); return this.db.model(this.toClassName(resDef.name), schema); } @@ -76,7 +76,7 @@ export class Resource { } setupRecursiveRoutes() { - var resource: Resource = this.parentResource; + let resource: Resource = this.parentResource; if (!!resource) { // Ensure the getter on root level this.router.route(`${Resource.BASE_URL}/${this.resDef.plural}`) @@ -92,8 +92,8 @@ export class Resource { getAll(req: Request, res: Response) { try { - var query: Object = this.buildSearchQuery(req); - var getQuery = this.model.find(query); + const query: Object = this.buildSearchQuery(req); + const getQuery = this.model.find(query); getQuery .populate(this.buildPopulateQuery(req)) .exec() @@ -113,8 +113,8 @@ export class Resource { } buildSearchQuery(req: Request) { - var query = {}; - for (var attr in req.query) { + const query = {}; + for (let attr in req.query) { // ignore populate attribute if (req.query.hasOwnProperty(attr) && attr !== 'populate') { query[attr] = this.createQuery(req.query[attr]); @@ -136,16 +136,16 @@ export class Resource { if (!query.match(/\//)) { query = `/${query}/`; } - var splitQuery = query.split('/'); - var modifier = splitQuery.pop(); + const splitQuery = query.split('/'); + const modifier = splitQuery.pop(); splitQuery.shift(); return new RegExp(splitQuery.join('/'), modifier); } buildParentSearch(req: Request, query) { - var resource: Resource = this; + let resource: Resource = this; while (!!resource.parentRef) { - var id = req.params[resource.parentResource.paramId]; + const id = req.params[resource.parentResource.paramId]; if (!!id) { query[resource.parentRef] = new ObjectId(id); } else { @@ -157,7 +157,7 @@ export class Resource { } getById(req: Request, res: Response) { - var id = req.params[this.paramId]; + const id = req.params[this.paramId]; this.model.findById(id) .populate(this.buildPopulateQuery(req)) .exec() @@ -172,7 +172,7 @@ export class Resource { } update(req: Request, res: Response) { - var id = req.params[this.paramId]; + const id = req.params[this.paramId]; this.model.findByIdAndUpdate(id, req.body) .exec() .then((model: Document) => res.send(model), @@ -180,7 +180,7 @@ export class Resource { } del(req: Request, res: Response) { - var id = req.params[this.paramId]; + const id = req.params[this.paramId]; this.model.findByIdAndRemove(id, req.body) .exec() .then((model: Document) => res.send(model), diff --git a/src/subResource.ts b/src/subResource.ts index 1fb34df..6f5b32c 100644 --- a/src/subResource.ts +++ b/src/subResource.ts @@ -4,11 +4,11 @@ import { Document, Model } from 'mongoose'; export default class SubResource extends Resource { constructor(subResDef: ISubResource) { - var resDef = { + const resDef = { name: null, model: null }; - for (var prop in subResDef) { + for (let prop in subResDef) { if (subResDef.hasOwnProperty(prop)) { resDef[prop] = subResDef[prop]; } @@ -39,7 +39,7 @@ export default class SubResource extends Resource { } createProjectionQuery(req: Request) { - var projection = {}; + const projection = {}; projection[this.resDef.plural] = { $elemMatch: { _id: req.params[this.paramId] @@ -49,7 +49,7 @@ export default class SubResource extends Resource { } create(req: Request, res: Response) { - var pushQuery = {}; + const pushQuery = {}; pushQuery[this.resDef.plural] = req.body; this.model.findByIdAndUpdate(req.params[this.parentResource.paramId], { $push: pushQuery @@ -67,7 +67,7 @@ export default class SubResource extends Resource { } createPullQuery(req: Request) { - var pullQuery = {}; + const pullQuery = {}; pullQuery[this.resDef.plural] = { _id: req.params[this.paramId] }; @@ -83,7 +83,7 @@ export default class SubResource extends Resource { } createFindQuery(req: Request) { - var findQuery = { + const findQuery = { _id: req.params[this.parentResource.paramId] }; findQuery[`${this.resDef.plural}._id`] = req.params[this.paramId]; @@ -91,8 +91,8 @@ export default class SubResource extends Resource { } createSubUpdateQuery(req: Request) { - var setQuery = {}; - for (var prop in req.body) { + const setQuery = {}; + for (let prop in req.body) { if (req.body.hasOwnProperty(prop)) { setQuery[`${this.resDef.plural}.$.${prop}`] = req.body[prop]; } diff --git a/src/userResource.ts b/src/userResource.ts index bd311ec..a1427c5 100644 --- a/src/userResource.ts +++ b/src/userResource.ts @@ -31,7 +31,7 @@ export default class UserResource extends AuthorizedResource { } createRoleModel() { - var roleSchema = new Schema({ + const roleSchema = new Schema({ name: String }); this.db.model('Role', roleSchema); @@ -45,9 +45,9 @@ export default class UserResource extends AuthorizedResource { } isSelf(req: Request) { - var authToken = req.header('Authorization'); - var tokenDetails = auth.decryptAuthToken(authToken); - return tokenDetails.id === req.params.userId; + const authToken = req.header('Authorization'); + const { id } = auth.decryptAuthToken(authToken); + return id === req.params.userId; } create(req: Request, res: Response) { @@ -81,7 +81,7 @@ export default class UserResource extends AuthorizedResource { } login(req: Request, res: Response) { - var password = auth.encryptPassword(req.body.password); + const password = auth.encryptPassword(req.body.password); this.model.findOne({ userName: new RegExp('^' + req.body.userName + '$', 'i'), password: password diff --git a/test/subresource/subresource.spec.ts b/test/subresource/subresource.spec.ts index 4afac3a..2dfb7a0 100644 --- a/test/subresource/subresource.spec.ts +++ b/test/subresource/subresource.spec.ts @@ -1,27 +1,24 @@ -var Yadda = require('yadda'); +const Yadda = require('yadda'); Yadda.plugins.mocha.ScenarioLevelPlugin.init(); -var mongoose = require('mongoose'); +import * as mongoose from 'mongoose'; process.env.DB = 'subTest'; require('../../examples/subresource/app'); -var library = require('./definitions/sub.steps'); +const library = require('./definitions/sub.steps'); import { parentResource } from '../../examples/subresource/resources/parent'; -new Yadda.FeatureFileSearch('test/subresource').each(function(file) { - featureFile(file, function(feature) { - var yadda = Yadda.createInstance(library); +new Yadda.FeatureFileSearch('test/subresource').each((file) => { + featureFile(file, (feature) => { + const yadda = Yadda.createInstance(library); - afterEach((done) => { - parentResource.db.connection.db.dropDatabase(function(err, result) { - done(); - }); - }); + afterEach((done) => + parentResource.db.connection.db + .dropDatabase((err, result) => done())); - scenarios(feature.scenarios, function(scenario, done) { - yadda.run(scenario.steps, done); - }); + scenarios(feature.scenarios, (scenario, done) => + yadda.run(scenario.steps, done)); }); }); From 0fa48b896271caf1f25a3ffedd432b5aed25bca0 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Wed, 4 May 2016 21:29:49 +0200 Subject: [PATCH 11/13] updated examples to adhere to the es6 standards --- examples/authentication/app.ts | 12 ++++++------ examples/customResource/app.ts | 14 +++++++------- .../resourceDefinitions/boomerangResource.ts | 13 +++---------- examples/customResource/resources/boomerang.ts | 8 ++------ examples/foods/app.ts | 11 +++++------ examples/foods/resources/dish.ts | 14 +++++--------- examples/foods/resources/food.ts | 4 +--- examples/foods/resources/list.ts | 4 +--- examples/subresource/app.ts | 12 ++++++------ lib/examples/authentication/app.js | 6 +++--- lib/examples/customResource/app.js | 6 +++--- .../resourceDefinitions/boomerangResource.js | 8 ++++---- .../customResource/resources/boomerang.js | 5 ++--- lib/examples/foods/app.js | 6 +++--- lib/examples/foods/resources/dish.js | 15 ++++++--------- lib/examples/foods/resources/food.js | 3 +-- lib/examples/foods/resources/list.js | 3 +-- lib/examples/subresource/app.js | 6 +++--- lib/test/foods/definitions/foods.steps.js | 12 ++++++------ test/foods/definitions/foods.steps.ts | 6 +++--- 20 files changed, 71 insertions(+), 97 deletions(-) diff --git a/examples/authentication/app.ts b/examples/authentication/app.ts index c94ecb2..2238544 100644 --- a/examples/authentication/app.ts +++ b/examples/authentication/app.ts @@ -4,23 +4,23 @@ import * as mongoose from 'mongoose'; export const app = express(); -var port = 4000; +const port = 4000; -var db = new mongoose.Mongoose(); -var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +const db = new mongoose.Mongoose(); +const host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; +let mongoUrl = `mongodb://${host}:${process.env.MONGO_PORT || '27017'}/`; mongoUrl += (process.env.DB || 'auth'); db.connect(mongoUrl); new RestIO(app, { db: db, - resources: __dirname + '/resources' + resources: `${__dirname}/resources` }); process.env.REST_IO_HMAC_KEY = process.env.REST_IO_HMAC_KEY || 'hmac key which set via js to demo'; process.env.REST_IO_AES_KEY = process.env.REST_IO_AES_KEY || 'aes key which is set via js to demo'; app.listen(port, () => { - console.log('Server has started under port: ' + port); + console.log(`Server has started under port: ${port}`); }); diff --git a/examples/customResource/app.ts b/examples/customResource/app.ts index 01bf0bd..409e1c8 100644 --- a/examples/customResource/app.ts +++ b/examples/customResource/app.ts @@ -3,20 +3,20 @@ import RestIO from '../../src/index'; import * as mongoose from 'mongoose'; export const app = express(); -var port = 3030; +const port = 3030; -var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +const host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; +let mongoUrl = `mongodb://${host}:${process.env.MONGO_PORT || '27017'}/`; -var db = new mongoose.Mongoose(); +const db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'customResource'); db.connect(mongoUrl); new RestIO(app, { - db: db, - resources: __dirname + '/resources' + db, + resources: `${__dirname}/resources` }); app.listen(port, () => { - console.log('Server has started under port: ' + port); + console.log(`Server has started under port: ${port}`); }); diff --git a/examples/customResource/resourceDefinitions/boomerangResource.ts b/examples/customResource/resourceDefinitions/boomerangResource.ts index 2d10b7c..1cf6f5f 100644 --- a/examples/customResource/resourceDefinitions/boomerangResource.ts +++ b/examples/customResource/resourceDefinitions/boomerangResource.ts @@ -1,13 +1,8 @@ -import resource = require('../../../src/resource'); -import Resource = resource.Resource; +import { Resource } from '../../../src/resource'; -import express = require('express'); -import Request = express.Request; -import Router = express.Router; -import Application = express.Application; -import Response = express.Response; +import { Request, Router, Application, Response } from 'express'; -class BoomerangResource extends Resource { +export default class BoomerangResource extends Resource { setupRoutes() { super.setupRoutes(); this.router @@ -34,5 +29,3 @@ class BoomerangResource extends Resource { }); } } - -export = BoomerangResource; diff --git a/examples/customResource/resources/boomerang.ts b/examples/customResource/resources/boomerang.ts index b77aae3..0b56013 100644 --- a/examples/customResource/resources/boomerang.ts +++ b/examples/customResource/resources/boomerang.ts @@ -1,12 +1,8 @@ -import mongoose = require('mongoose'); -import Schema = mongoose.Schema; -import BoomerangResource = require('../resourceDefinitions/boomerangResource'); +import BoomerangResource from '../resourceDefinitions/boomerangResource'; -var boomerang = new BoomerangResource({ +export const boomerang = new BoomerangResource({ name: 'boomerang', model: { name: String } }); - -module.exports = boomerang; diff --git a/examples/foods/app.ts b/examples/foods/app.ts index abcf8d8..4f60811 100644 --- a/examples/foods/app.ts +++ b/examples/foods/app.ts @@ -4,19 +4,18 @@ import * as mongoose from 'mongoose'; export const app = express(); -var port = 3000; +const port = 3000; new RestIO(app, { - resources: __dirname + '/resources' + resources: `${__dirname}/resources` }); -var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; - +const host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; +let mongoUrl = `mongodb://${host}:${process.env.MONGO_PORT || '27017'}/`; mongoUrl += (process.env.DB || 'foods'); mongoose.connect(mongoUrl); app.listen(port, () => { - console.log('Server has started under port: ' + port); + console.log(`Server has started under port: ${port}`); }); diff --git a/examples/foods/resources/dish.ts b/examples/foods/resources/dish.ts index c11d3f7..a0ffa96 100644 --- a/examples/foods/resources/dish.ts +++ b/examples/foods/resources/dish.ts @@ -1,10 +1,8 @@ -import mongoose = require('mongoose'); -import Schema = mongoose.Schema; -import resource = require('../../../src/resource'); -import Resource = resource.Resource; -import Food = require('./food'); +import { Schema } from 'mongoose'; +import { Resource } from '../../../src/resource'; +import { food } from './food'; -var dish = new Resource({ +export const dish = new Resource({ name: 'dish', model: { name: String, @@ -13,8 +11,6 @@ var dish = new Resource({ ref: 'Food' } }, - parentResource: Food, + parentResource: food, parentRef: 'mainIngredient' }); - -export = dish; diff --git a/examples/foods/resources/food.ts b/examples/foods/resources/food.ts index 0d56b6a..07da01f 100644 --- a/examples/foods/resources/food.ts +++ b/examples/foods/resources/food.ts @@ -3,12 +3,10 @@ import Schema = mongoose.Schema; import resource = require('../../../src/resource'); import Resource = resource.Resource; -var foodResource = new Resource({ +export const food = new Resource({ name: 'food', model: { name: String, weight: Number } }); - -export = foodResource; diff --git a/examples/foods/resources/list.ts b/examples/foods/resources/list.ts index a156d39..fcc3cc6 100644 --- a/examples/foods/resources/list.ts +++ b/examples/foods/resources/list.ts @@ -3,7 +3,7 @@ import Schema = mongoose.Schema; import resource = require('../../../src/resource'); import Resource = resource.Resource; -var listResource = new Resource({ +export const list = new Resource({ name: 'list', populate: 'foods', model: { @@ -14,5 +14,3 @@ var listResource = new Resource({ }] } }); - -export = listResource; diff --git a/examples/subresource/app.ts b/examples/subresource/app.ts index 5a3a49f..d9e85ce 100644 --- a/examples/subresource/app.ts +++ b/examples/subresource/app.ts @@ -3,20 +3,20 @@ import RestIO from '../../src/index'; import * as mongoose from 'mongoose'; export const app = express(); -var port = 5050; +const port = 5050; -var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +const host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; +let mongoUrl = `mongodb://${host}:${process.env.MONGO_PORT || '27017'}/`; -var db = new mongoose.Mongoose(); +const db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'sub'); db.connect(mongoUrl); new RestIO(app, { db: db, - resources: __dirname + '/resources' + resources: `${__dirname}/resources` }); app.listen(port, () => { - console.log('Server has started under port: ' + port); + console.log(`Server has started under port: ${port}`); }); diff --git a/lib/examples/authentication/app.js b/lib/examples/authentication/app.js index 5d111b3..6f7f671 100644 --- a/lib/examples/authentication/app.js +++ b/lib/examples/authentication/app.js @@ -6,15 +6,15 @@ exports.app = express(); var port = 4000; var db = new mongoose.Mongoose(); var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +var mongoUrl = "mongodb://" + host + ":" + (process.env.MONGO_PORT || '27017') + "/"; mongoUrl += (process.env.DB || 'auth'); db.connect(mongoUrl); new index_1.default(exports.app, { db: db, - resources: __dirname + '/resources' + resources: __dirname + "/resources" }); process.env.REST_IO_HMAC_KEY = process.env.REST_IO_HMAC_KEY || 'hmac key which set via js to demo'; process.env.REST_IO_AES_KEY = process.env.REST_IO_AES_KEY || 'aes key which is set via js to demo'; exports.app.listen(port, function () { - console.log('Server has started under port: ' + port); + console.log("Server has started under port: " + port); }); diff --git a/lib/examples/customResource/app.js b/lib/examples/customResource/app.js index 9af2903..df41c62 100644 --- a/lib/examples/customResource/app.js +++ b/lib/examples/customResource/app.js @@ -5,14 +5,14 @@ var mongoose = require('mongoose'); exports.app = express(); var port = 3030; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +var mongoUrl = "mongodb://" + host + ":" + (process.env.MONGO_PORT || '27017') + "/"; var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'customResource'); db.connect(mongoUrl); new index_1.default(exports.app, { db: db, - resources: __dirname + '/resources' + resources: __dirname + "/resources" }); exports.app.listen(port, function () { - console.log('Server has started under port: ' + port); + console.log("Server has started under port: " + port); }); diff --git a/lib/examples/customResource/resourceDefinitions/boomerangResource.js b/lib/examples/customResource/resourceDefinitions/boomerangResource.js index 09d5d30..b040cae 100644 --- a/lib/examples/customResource/resourceDefinitions/boomerangResource.js +++ b/lib/examples/customResource/resourceDefinitions/boomerangResource.js @@ -4,8 +4,7 @@ var __extends = (this && this.__extends) || function (d, b) { function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; -var resource = require('../../../src/resource'); -var Resource = resource.Resource; +var resource_1 = require('../../../src/resource'); var BoomerangResource = (function (_super) { __extends(BoomerangResource, _super); function BoomerangResource() { @@ -34,5 +33,6 @@ var BoomerangResource = (function (_super) { }); }; return BoomerangResource; -}(Resource)); -module.exports = BoomerangResource; +}(resource_1.Resource)); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = BoomerangResource; diff --git a/lib/examples/customResource/resources/boomerang.js b/lib/examples/customResource/resources/boomerang.js index 4a15f02..7444f06 100644 --- a/lib/examples/customResource/resources/boomerang.js +++ b/lib/examples/customResource/resources/boomerang.js @@ -1,9 +1,8 @@ "use strict"; -var BoomerangResource = require('../resourceDefinitions/boomerangResource'); -var boomerang = new BoomerangResource({ +var boomerangResource_1 = require('../resourceDefinitions/boomerangResource'); +exports.boomerang = new boomerangResource_1.default({ name: 'boomerang', model: { name: String } }); -module.exports = boomerang; diff --git a/lib/examples/foods/app.js b/lib/examples/foods/app.js index 97e6399..eff11b3 100644 --- a/lib/examples/foods/app.js +++ b/lib/examples/foods/app.js @@ -5,12 +5,12 @@ var mongoose = require('mongoose'); exports.app = express(); var port = 3000; new index_1.default(exports.app, { - resources: __dirname + '/resources' + resources: __dirname + "/resources" }); var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +var mongoUrl = "mongodb://" + host + ":" + (process.env.MONGO_PORT || '27017') + "/"; mongoUrl += (process.env.DB || 'foods'); mongoose.connect(mongoUrl); exports.app.listen(port, function () { - console.log('Server has started under port: ' + port); + console.log("Server has started under port: " + port); }); diff --git a/lib/examples/foods/resources/dish.js b/lib/examples/foods/resources/dish.js index 8ff0937..6d8f0ae 100644 --- a/lib/examples/foods/resources/dish.js +++ b/lib/examples/foods/resources/dish.js @@ -1,19 +1,16 @@ "use strict"; -var mongoose = require('mongoose'); -var Schema = mongoose.Schema; -var resource = require('../../../src/resource'); -var Resource = resource.Resource; -var Food = require('./food'); -var dish = new Resource({ +var mongoose_1 = require('mongoose'); +var resource_1 = require('../../../src/resource'); +var food_1 = require('./food'); +exports.dish = new resource_1.Resource({ name: 'dish', model: { name: String, mainIngredient: { - type: Schema.Types.ObjectId, + type: mongoose_1.Schema.Types.ObjectId, ref: 'Food' } }, - parentResource: Food, + parentResource: food_1.food, parentRef: 'mainIngredient' }); -module.exports = dish; diff --git a/lib/examples/foods/resources/food.js b/lib/examples/foods/resources/food.js index 413e137..46a4783 100644 --- a/lib/examples/foods/resources/food.js +++ b/lib/examples/foods/resources/food.js @@ -1,11 +1,10 @@ "use strict"; var resource = require('../../../src/resource'); var Resource = resource.Resource; -var foodResource = new Resource({ +exports.food = new Resource({ name: 'food', model: { name: String, weight: Number } }); -module.exports = foodResource; diff --git a/lib/examples/foods/resources/list.js b/lib/examples/foods/resources/list.js index 8b80bee..30f6c54 100644 --- a/lib/examples/foods/resources/list.js +++ b/lib/examples/foods/resources/list.js @@ -3,7 +3,7 @@ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var resource = require('../../../src/resource'); var Resource = resource.Resource; -var listResource = new Resource({ +exports.list = new Resource({ name: 'list', populate: 'foods', model: { @@ -14,4 +14,3 @@ var listResource = new Resource({ }] } }); -module.exports = listResource; diff --git a/lib/examples/subresource/app.js b/lib/examples/subresource/app.js index 7028ed1..730b5c5 100644 --- a/lib/examples/subresource/app.js +++ b/lib/examples/subresource/app.js @@ -5,14 +5,14 @@ var mongoose = require('mongoose'); exports.app = express(); var port = 5050; var host = process.env.MONGO_PORT_27017_TCP_ADDR || 'localhost'; -var mongoUrl = 'mongodb://' + host + ':' + (process.env.MONGO_PORT || '27017') + '/'; +var mongoUrl = "mongodb://" + host + ":" + (process.env.MONGO_PORT || '27017') + "/"; var db = new mongoose.Mongoose(); mongoUrl += (process.env.DB || 'sub'); db.connect(mongoUrl); new index_1.default(exports.app, { db: db, - resources: __dirname + '/resources' + resources: __dirname + "/resources" }); exports.app.listen(port, function () { - console.log('Server has started under port: ' + port); + console.log("Server has started under port: " + port); }); diff --git a/lib/test/foods/definitions/foods.steps.js b/lib/test/foods/definitions/foods.steps.js index ccd5c90..1aab3cf 100644 --- a/lib/test/foods/definitions/foods.steps.js +++ b/lib/test/foods/definitions/foods.steps.js @@ -5,12 +5,12 @@ var library = English.library(); var chai = require('chai'); chai.use(require('chai-things')); var expect = chai.expect; -var food = require('../../../examples/foods/resources/food'); -var Food = food.model; -var list = require('../../../examples/foods/resources/list'); -var List = list.model; -var dish = require('../../../examples/foods/resources/dish'); -var Dish = dish.model; +var food_1 = require('../../../examples/foods/resources/food'); +var Food = food_1.food.model; +var list_1 = require('../../../examples/foods/resources/list'); +var List = list_1.list.model; +var dish_1 = require('../../../examples/foods/resources/dish'); +var Dish = dish_1.dish.model; var supertest = require('supertest'); function createIdBasedOnName(name) { var id = convertToHex(name); diff --git a/test/foods/definitions/foods.steps.ts b/test/foods/definitions/foods.steps.ts index e92f901..a4deae7 100644 --- a/test/foods/definitions/foods.steps.ts +++ b/test/foods/definitions/foods.steps.ts @@ -4,11 +4,11 @@ import chai = require('chai'); chai.use(require('chai-things')); var expect = chai.expect; -import food = require('../../../examples/foods/resources/food'); +import { food } from '../../../examples/foods/resources/food'; var Food = food.model; -import list = require('../../../examples/foods/resources/list'); +import { list } from '../../../examples/foods/resources/list'; var List = list.model; -import dish = require('../../../examples/foods/resources/dish'); +import { dish } from '../../../examples/foods/resources/dish'; var Dish = dish.model; import supertest = require('supertest'); From 20065dc21960273c0ba6774a62bc8ae7d260bc4a Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Thu, 5 May 2016 08:13:54 +0200 Subject: [PATCH 12/13] preparing for release 4.1.0 --- .gitignore | 2 + README.md | 8 ++-- lib/examples/authentication/app.d.ts | 2 + .../authentication/resources/parent.d.ts | 2 + .../authentication/resources/sub.d.ts | 2 + .../authentication/resources/user.d.ts | 2 + lib/examples/customResource/app.d.ts | 2 + .../boomerangResource.d.ts | 9 ++++ .../customResource/resources/boomerang.d.ts | 2 + lib/examples/foods/app.d.ts | 2 + lib/examples/foods/resources/dish.d.ts | 2 + lib/examples/foods/resources/food.d.ts | 2 + lib/examples/foods/resources/list.d.ts | 2 + lib/examples/subresource/app.d.ts | 2 + .../subresource/resources/parent.d.ts | 2 + lib/examples/subresource/resources/ref.d.ts | 2 + lib/examples/subresource/resources/sub.d.ts | 2 + lib/src/authentication.d.ts | 6 +++ lib/src/authorizedResource.d.ts | 37 ++++++++++++++++ lib/src/authorizedSubResource.d.ts | 23 ++++++++++ lib/src/index.d.ts | 20 +++++++++ lib/src/resource.d.ts | 43 +++++++++++++++++++ lib/src/subResource.d.ts | 24 +++++++++++ lib/src/userResource.d.ts | 17 ++++++++ .../authentication/authentication.spec.d.ts | 0 .../definitions/authentication.steps.d.ts | 2 + .../customResource/customResource.spec.d.ts | 3 ++ .../definitions/customResource.steps.d.ts | 2 + lib/test/foods/definitions/foods.steps.d.ts | 0 lib/test/foods/foods.spec.d.ts | 3 ++ .../subresource/definitions/sub.steps.d.ts | 0 lib/test/subresource/subresource.spec.d.ts | 0 package.json | 17 +++----- wercker.yml | 7 ++- 34 files changed, 235 insertions(+), 16 deletions(-) create mode 100644 lib/examples/authentication/app.d.ts create mode 100644 lib/examples/authentication/resources/parent.d.ts create mode 100644 lib/examples/authentication/resources/sub.d.ts create mode 100644 lib/examples/authentication/resources/user.d.ts create mode 100644 lib/examples/customResource/app.d.ts create mode 100644 lib/examples/customResource/resourceDefinitions/boomerangResource.d.ts create mode 100644 lib/examples/customResource/resources/boomerang.d.ts create mode 100644 lib/examples/foods/app.d.ts create mode 100644 lib/examples/foods/resources/dish.d.ts create mode 100644 lib/examples/foods/resources/food.d.ts create mode 100644 lib/examples/foods/resources/list.d.ts create mode 100644 lib/examples/subresource/app.d.ts create mode 100644 lib/examples/subresource/resources/parent.d.ts create mode 100644 lib/examples/subresource/resources/ref.d.ts create mode 100644 lib/examples/subresource/resources/sub.d.ts create mode 100644 lib/src/authentication.d.ts create mode 100644 lib/src/authorizedResource.d.ts create mode 100644 lib/src/authorizedSubResource.d.ts create mode 100644 lib/src/index.d.ts create mode 100644 lib/src/resource.d.ts create mode 100644 lib/src/subResource.d.ts create mode 100644 lib/src/userResource.d.ts create mode 100644 lib/test/authentication/authentication.spec.d.ts create mode 100644 lib/test/authentication/definitions/authentication.steps.d.ts create mode 100644 lib/test/customResource/customResource.spec.d.ts create mode 100644 lib/test/customResource/definitions/customResource.steps.d.ts create mode 100644 lib/test/foods/definitions/foods.steps.d.ts create mode 100644 lib/test/foods/foods.spec.d.ts create mode 100644 lib/test/subresource/definitions/sub.steps.d.ts create mode 100644 lib/test/subresource/subresource.spec.d.ts diff --git a/.gitignore b/.gitignore index a2b1b54..5a196b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +_cache/ +_projects/ _builds/ _steps/ build diff --git a/README.md b/README.md index e8a7d19..69a6953 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ Small extendable REST framework for express and mongoose. [![wercker status](htt $ npm install rest-io --save ``` -## New in v4.0.0 -- all resources are [searchable](/docs/search.md) -- all resources have [population](/docs/populate.md) controllable +## New in v4.1.0 +- Updated to Typescript 1.8 +- Updated to Typings from TSD ## Features - Custom Resource declarations @@ -24,6 +24,8 @@ $ npm install rest-io --save - Typescript definitions - Sub Documents can be populated - pluralize used for automatic pluralizing +- all resources are [searchable](/docs/search.md) +- all resources have [population](/docs/populate.md) controllable Roadmap - More default operations: diff --git a/lib/examples/authentication/app.d.ts b/lib/examples/authentication/app.d.ts new file mode 100644 index 0000000..d8302b9 --- /dev/null +++ b/lib/examples/authentication/app.d.ts @@ -0,0 +1,2 @@ +import * as express from 'express'; +export declare const app: express.Express; diff --git a/lib/examples/authentication/resources/parent.d.ts b/lib/examples/authentication/resources/parent.d.ts new file mode 100644 index 0000000..8b672b1 --- /dev/null +++ b/lib/examples/authentication/resources/parent.d.ts @@ -0,0 +1,2 @@ +import AuthorizedResource from '../../../src/authorizedResource'; +export declare const parentResource: AuthorizedResource; diff --git a/lib/examples/authentication/resources/sub.d.ts b/lib/examples/authentication/resources/sub.d.ts new file mode 100644 index 0000000..b7af1bd --- /dev/null +++ b/lib/examples/authentication/resources/sub.d.ts @@ -0,0 +1,2 @@ +import AuthorizedSubResource from '../../../src/authorizedSubResource'; +export declare const sub: AuthorizedSubResource; diff --git a/lib/examples/authentication/resources/user.d.ts b/lib/examples/authentication/resources/user.d.ts new file mode 100644 index 0000000..4966257 --- /dev/null +++ b/lib/examples/authentication/resources/user.d.ts @@ -0,0 +1,2 @@ +import UserResource from '../../../src/userResource'; +export declare const user: UserResource; diff --git a/lib/examples/customResource/app.d.ts b/lib/examples/customResource/app.d.ts new file mode 100644 index 0000000..d8302b9 --- /dev/null +++ b/lib/examples/customResource/app.d.ts @@ -0,0 +1,2 @@ +import * as express from 'express'; +export declare const app: express.Express; diff --git a/lib/examples/customResource/resourceDefinitions/boomerangResource.d.ts b/lib/examples/customResource/resourceDefinitions/boomerangResource.d.ts new file mode 100644 index 0000000..fd2648e --- /dev/null +++ b/lib/examples/customResource/resourceDefinitions/boomerangResource.d.ts @@ -0,0 +1,9 @@ +import { Resource } from '../../../src/resource'; +import { Request, Response } from 'express'; +export default class BoomerangResource extends Resource { + setupRoutes(): void; + getAll(req: Request, res: Response): void; + getById(req: Request, res: Response): void; + create(req: Request, res: Response): void; + addAndRetrieve(req: Request, res: Response): void; +} diff --git a/lib/examples/customResource/resources/boomerang.d.ts b/lib/examples/customResource/resources/boomerang.d.ts new file mode 100644 index 0000000..1967526 --- /dev/null +++ b/lib/examples/customResource/resources/boomerang.d.ts @@ -0,0 +1,2 @@ +import BoomerangResource from '../resourceDefinitions/boomerangResource'; +export declare const boomerang: BoomerangResource; diff --git a/lib/examples/foods/app.d.ts b/lib/examples/foods/app.d.ts new file mode 100644 index 0000000..d8302b9 --- /dev/null +++ b/lib/examples/foods/app.d.ts @@ -0,0 +1,2 @@ +import * as express from 'express'; +export declare const app: express.Express; diff --git a/lib/examples/foods/resources/dish.d.ts b/lib/examples/foods/resources/dish.d.ts new file mode 100644 index 0000000..4810bac --- /dev/null +++ b/lib/examples/foods/resources/dish.d.ts @@ -0,0 +1,2 @@ +import { Resource } from '../../../src/resource'; +export declare const dish: Resource; diff --git a/lib/examples/foods/resources/food.d.ts b/lib/examples/foods/resources/food.d.ts new file mode 100644 index 0000000..b5ba64c --- /dev/null +++ b/lib/examples/foods/resources/food.d.ts @@ -0,0 +1,2 @@ +import resource = require('../../../src/resource'); +export declare const food: resource.Resource; diff --git a/lib/examples/foods/resources/list.d.ts b/lib/examples/foods/resources/list.d.ts new file mode 100644 index 0000000..e1bd9e4 --- /dev/null +++ b/lib/examples/foods/resources/list.d.ts @@ -0,0 +1,2 @@ +import resource = require('../../../src/resource'); +export declare const list: resource.Resource; diff --git a/lib/examples/subresource/app.d.ts b/lib/examples/subresource/app.d.ts new file mode 100644 index 0000000..d8302b9 --- /dev/null +++ b/lib/examples/subresource/app.d.ts @@ -0,0 +1,2 @@ +import * as express from 'express'; +export declare const app: express.Express; diff --git a/lib/examples/subresource/resources/parent.d.ts b/lib/examples/subresource/resources/parent.d.ts new file mode 100644 index 0000000..96d5979 --- /dev/null +++ b/lib/examples/subresource/resources/parent.d.ts @@ -0,0 +1,2 @@ +import { Resource } from '../../../src/resource'; +export declare const parentResource: Resource; diff --git a/lib/examples/subresource/resources/ref.d.ts b/lib/examples/subresource/resources/ref.d.ts new file mode 100644 index 0000000..179912d --- /dev/null +++ b/lib/examples/subresource/resources/ref.d.ts @@ -0,0 +1,2 @@ +import { Resource } from '../../../src/resource'; +export declare const ref: Resource; diff --git a/lib/examples/subresource/resources/sub.d.ts b/lib/examples/subresource/resources/sub.d.ts new file mode 100644 index 0000000..b38fb6a --- /dev/null +++ b/lib/examples/subresource/resources/sub.d.ts @@ -0,0 +1,2 @@ +import SubResource from '../../../src/subResource'; +export declare const sub: SubResource; diff --git a/lib/src/authentication.d.ts b/lib/src/authentication.d.ts new file mode 100644 index 0000000..73a4b40 --- /dev/null +++ b/lib/src/authentication.d.ts @@ -0,0 +1,6 @@ +export declare function encryptPassword(password: string): any; +export declare function createAuthToken(userId: string): any; +export declare function decryptAuthToken(authToken: string): { + id: any; + createdAt: Date; +}; diff --git a/lib/src/authorizedResource.d.ts b/lib/src/authorizedResource.d.ts new file mode 100644 index 0000000..c362dc9 --- /dev/null +++ b/lib/src/authorizedResource.d.ts @@ -0,0 +1,37 @@ +import { Resource } from './resource'; +import { Request, Response } from 'express'; +import * as mongoose from 'mongoose'; +export declare const ROLES: { + USER: string; + SUPER_USER: string; + MODERATOR: string; + ADMIN: string; +}; +export default class AuthorizedResource extends Resource { + methodAccess: IMethodAccess; + maxDays: number; + permissions: IMethodAccess; + isTokenExpired(createdAt: Date): boolean; + getRoles(id: string): mongoose.Promise; + hasAuthorizedRole(roles: Array, authorizedRoles: Array): boolean; + hasAccessRightsDefined(req: Request, authorizedRoles: Array): mongoose.Promise<{}>; + isAuthorized(req: Request, authorizedRoles: Array): mongoose.Promise<{}>; + sendUnauthorized(error: Error, res: Response): void; + baseGetAll: (req: Request, res: Response) => void; + baseGetById: (req: Request, res: Response) => void; + baseCreate: (req: Request, res: Response) => void; + baseUpdate: (req: Request, res: Response) => void; + baseDel: (req: Request, res: Response) => void; + getAll(req: Request, res: Response): void; + getById(req: Request, res: Response): void; + create(req: Request, res: Response): void; + update(req: Request, res: Response): void; + del(req: Request, res: Response): void; +} +export interface IMethodAccess { + getAll: Array; + getById: Array; + create: Array; + update: Array; + del: Array; +} diff --git a/lib/src/authorizedSubResource.d.ts b/lib/src/authorizedSubResource.d.ts new file mode 100644 index 0000000..b6cf745 --- /dev/null +++ b/lib/src/authorizedSubResource.d.ts @@ -0,0 +1,23 @@ +import AuthorizedResource from './authorizedResource'; +import { Resource, IResource } from './resource'; +import { Request, Response } from 'express'; +import { Model, Document } from 'mongoose'; +export default class AuthorizedSubResource extends AuthorizedResource { + constructor(subResDef: ISubResource); + createModel(resDef: IResource): Model; + getAll(req: Request, res: Response): void; + getById(req: Request, res: Response): void; + create(req: Request, res: Response): void; + update(req: Request, res: Response): void; + del(req: Request, res: Response): void; + createProjectionQuery(req: Request): any; + createPullQuery(req: Request): any; + createFindQuery(req: Request): any; + createSubUpdateQuery(req: Request): any; +} +export interface ISubResource { + name: string; + plural?: string; + parentResource: Resource; + populate?: string; +} diff --git a/lib/src/index.d.ts b/lib/src/index.d.ts new file mode 100644 index 0000000..f0fdb96 --- /dev/null +++ b/lib/src/index.d.ts @@ -0,0 +1,20 @@ +import { Mongoose } from 'mongoose'; +import * as express from 'express'; +import * as resource from './resource'; +import UserResource from './userResource'; +import * as authorizedResource from './authorizedResource'; +import SubResource from './subResource'; +import AuthorizedSubResource from './authorizedSubResource'; +export default class RestIO { + static authorizedResource: typeof authorizedResource; + static UserResource: typeof UserResource; + static AuthorizedResource: typeof authorizedResource.AuthorizedResource; + static SubResource: typeof SubResource; + static AuthorizedSubResource: typeof AuthorizedSubResource; + static Resource: typeof resource.Resource; + constructor(app: express.Application, config?: IRestIOConfig); +} +export interface IRestIOConfig { + resources: string; + db?: Mongoose; +} diff --git a/lib/src/resource.d.ts b/lib/src/resource.d.ts new file mode 100644 index 0000000..76e544a --- /dev/null +++ b/lib/src/resource.d.ts @@ -0,0 +1,43 @@ +import { Request, Router, Application, Response } from 'express'; +import * as mongoose from 'mongoose'; +import { Mongoose, Model, Document } from 'mongoose'; +export declare class Resource { + static BASE_URL: string; + baseUrl: string; + url: string; + parameterizedUrl: string; + model: Model; + resDef: IResource; + parentResource: Resource; + router: Router; + app: Application; + db: Mongoose; + paramId: string; + parentRef: string; + populate: string; + constructor(resDef: IResource); + createModel(resDef: IResource): mongoose.Model; + toClassName(name: string): string; + setupRoutes(): void; + setupRecursiveRoutes(): void; + getAll(req: Request, res: Response): void; + buildPopulateQuery(req: Request): any; + buildSearchQuery(req: Request): {}; + createQuery(query: string): any; + createRegex(query: string): RegExp; + buildParentSearch(req: Request, query: any): any; + getById(req: Request, res: Response): void; + create(req: Request, res: Response): void; + update(req: Request, res: Response): void; + del(req: Request, res: Response): void; + errorHandler(err: Error, res: Response): void; +} +export interface IResource { + name: string; + model: any; + parentRef?: string; + populate?: string; + plural?: string; + parentResource?: Resource; +} +export declare function registerApp(registerApp: any, connection: Mongoose): void; diff --git a/lib/src/subResource.d.ts b/lib/src/subResource.d.ts new file mode 100644 index 0000000..29e2ab4 --- /dev/null +++ b/lib/src/subResource.d.ts @@ -0,0 +1,24 @@ +import { Resource, IResource } from './resource'; +import { Request, Response } from 'express'; +import { Document, Model } from 'mongoose'; +export default class SubResource extends Resource { + constructor(subResDef: ISubResource); + createModel(resDef: IResource): Model; + getAll(req: Request, res: Response): void; + getById(req: Request, res: Response): void; + createProjectionQuery(req: Request): {}; + create(req: Request, res: Response): void; + del(req: Request, res: Response): void; + createPullQuery(req: Request): {}; + update(req: Request, res: Response): void; + createFindQuery(req: Request): { + _id: any; + }; + createSubUpdateQuery(req: Request): {}; +} +export interface ISubResource { + name: string; + plural?: string; + parentResource: Resource; + populate?: string; +} diff --git a/lib/src/userResource.d.ts b/lib/src/userResource.d.ts new file mode 100644 index 0000000..9543ef5 --- /dev/null +++ b/lib/src/userResource.d.ts @@ -0,0 +1,17 @@ +import AuthorizedResource from './authorizedResource'; +import { IMethodAccess } from './authorizedResource'; +import { IResource } from './resource'; +import { Request, Response } from 'express'; +import { Model, Document } from 'mongoose'; +export default class UserResource extends AuthorizedResource { + permissions: IMethodAccess; + createModel(resDef: IResource): Model; + ensureBaseUserModel(model: any): void; + createRoleModel(): void; + setupRoutes(): void; + isSelf(req: Request): boolean; + create(req: Request, res: Response): void; + update(req: Request, res: Response): void; + del(req: Request, res: Response): void; + login(req: Request, res: Response): void; +} diff --git a/lib/test/authentication/authentication.spec.d.ts b/lib/test/authentication/authentication.spec.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/lib/test/authentication/definitions/authentication.steps.d.ts b/lib/test/authentication/definitions/authentication.steps.d.ts new file mode 100644 index 0000000..3ad1278 --- /dev/null +++ b/lib/test/authentication/definitions/authentication.steps.d.ts @@ -0,0 +1,2 @@ +declare var library: any; +export = library; diff --git a/lib/test/customResource/customResource.spec.d.ts b/lib/test/customResource/customResource.spec.d.ts new file mode 100644 index 0000000..47f5738 --- /dev/null +++ b/lib/test/customResource/customResource.spec.d.ts @@ -0,0 +1,3 @@ +declare var Yadda: any; +declare var mongoose: any; +declare var library: any; diff --git a/lib/test/customResource/definitions/customResource.steps.d.ts b/lib/test/customResource/definitions/customResource.steps.d.ts new file mode 100644 index 0000000..3ad1278 --- /dev/null +++ b/lib/test/customResource/definitions/customResource.steps.d.ts @@ -0,0 +1,2 @@ +declare var library: any; +export = library; diff --git a/lib/test/foods/definitions/foods.steps.d.ts b/lib/test/foods/definitions/foods.steps.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/lib/test/foods/foods.spec.d.ts b/lib/test/foods/foods.spec.d.ts new file mode 100644 index 0000000..47f5738 --- /dev/null +++ b/lib/test/foods/foods.spec.d.ts @@ -0,0 +1,3 @@ +declare var Yadda: any; +declare var mongoose: any; +declare var library: any; diff --git a/lib/test/subresource/definitions/sub.steps.d.ts b/lib/test/subresource/definitions/sub.steps.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/lib/test/subresource/subresource.spec.d.ts b/lib/test/subresource/subresource.spec.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/package.json b/package.json index fed5e80..3a3633c 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,10 @@ { "name": "rest-io", - "version": "4.0.0", + "version": "4.1.0", "description": "REST resource generator", "main": "lib/src/index.js", - "typescript": { - "definitions": "./definitions/rest-io.d.ts" - }, + "typings": "lib/src/index.d.ts", "files": [ - "definitions/", "lib/src" ], "directories": { @@ -17,11 +14,8 @@ }, "scripts": { "clean": "rimraf lib dist build", - "ts": "tsc --module commonjs -t ES5 --outDir lib", - "ts-watch": "tsc --module commonjs -t ES5 --outDir lib -p . -w", - "test": "mocha lib/test/**/*.spec.js -R mocha-better-spec-reporter", - "test-watch": "watch \"npm run test\" lib/", - "watch": "parallelshell \"npm run ts-watch\" \"npm run test-watch\"" + "ts": "tsc --module commonjs -t ES5 --outDir lib -d", + "test": "mocha --require ts-node/register test/**/*.spec.ts -R mocha-better-spec-reporter" }, "repository": { "type": "git", @@ -65,7 +59,8 @@ "sinon": "^1.14.1", "sinon-chai": "^2.7.0", "supertest": "^1.0.1", - "typescript": "^1.5.0-beta", + "ts-node": "^0.7.2", + "typescript": "^1.8.10", "watch": "^0.16.0", "yadda": "^0.11.5" }, diff --git a/wercker.yml b/wercker.yml index f660fd4..d990a92 100644 --- a/wercker.yml +++ b/wercker.yml @@ -28,9 +28,12 @@ build: # Read more about steps on our dev center: # http://devcenter.wercker.com/docs/steps/index.html steps: - # A step that executes `npm install` command - npm-install - # A step that executes `npm test` command + - script: + name: build the package + code: | + npm run clean + npm run ts - npm-test # A custom script step, name value is used in the UI From 29431eda7295d979a434b19b608c7a5e93ae3cc5 Mon Sep 17 00:00:00 2001 From: Andy Tang Date: Thu, 5 May 2016 08:58:44 +0200 Subject: [PATCH 13/13] updated all packages --- README.md | 1 + package.json | 10 ++++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 69a6953..84cf5a8 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ $ npm install rest-io --save ## New in v4.1.0 - Updated to Typescript 1.8 - Updated to Typings from TSD +- Typescript definitions are now automatically loaded ## Features - Custom Resource declarations diff --git a/package.json b/package.json index 3a3633c..00602a3 100644 --- a/package.json +++ b/package.json @@ -54,15 +54,13 @@ "mocha": "^2.2.5", "mocha-better-spec-reporter": "^2.0.1", "mongoose": "^4.4.14", - "parallelshell": "^1.1.1", "rimraf": "^2.3.4", - "sinon": "^1.14.1", - "sinon-chai": "^2.7.0", - "supertest": "^1.0.1", + "sinon": "^1.17.4", + "sinon-chai": "^2.8.0", + "supertest": "^1.2.0", "ts-node": "^0.7.2", "typescript": "^1.8.10", - "watch": "^0.16.0", - "yadda": "^0.11.5" + "yadda": "^0.11.7" }, "dependencies": { "crypto-js": "^3.1.5",