From c69db70217e535f1b27f40971729402d39e09351 Mon Sep 17 00:00:00 2001 From: troy_paypac Date: Wed, 26 Mar 2014 14:58:30 +0800 Subject: [PATCH 01/13] internal module defns for node and express --- express/express.d.ts | 99 +++++++++++++++--------------- node/node.d.ts | 140 +++++++++++++++++++++---------------------- 2 files changed, 118 insertions(+), 121 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 243aa41d4..e18b7bc7d 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -12,14 +12,11 @@ /// -declare module "express" { - import http = require('http'); +declare module "express" { export = ExpressStatic; } +declare function ExpressStatic(): ExpressStatic.Express +declare module ExpressStatic { - // Merged declaration, e is both a callable function and a namespace - function e(): e.Express; - - module e { - interface IRoute { + export interface IRoute { path: string; method: string; @@ -35,7 +32,7 @@ declare module "express" { match(path: string): boolean; } - class Route implements IRoute { + export class Route implements IRoute { path: string; method: string; @@ -62,7 +59,7 @@ declare module "express" { new (method: string, path: string, callbacks: Function[], options: any): Route; } - interface IRouter { + export interface IRouter { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -107,6 +104,8 @@ declare module "express" { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): T; get(name: RegExp, ...handlers: RequestFunction[]): T; @@ -141,6 +140,8 @@ declare module "express" { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): Router; get(name: RegExp, ...handlers: RequestFunction[]): Router; @@ -162,11 +163,11 @@ declare module "express" { patch(name: RegExp, ...handlers: RequestFunction[]): Router; } - interface Handler { + export interface Handler { (req: Request, res: Response, next?: Function): void; } - interface CookieOptions { + export interface CookieOptions { maxAge?: number; signed?: boolean; expires?: Date; @@ -176,9 +177,9 @@ declare module "express" { secure?: boolean; } - interface Errback { (err: Error): void; } + export interface Errback { (err: Error): void; } - interface Session { + export interface Session { /** * Update reset `.cookie.maxAge` to prevent * the cookie from expiring when the @@ -229,7 +230,7 @@ declare module "express" { count: number; } - interface Request { + export interface Request { session: Session; @@ -533,19 +534,19 @@ declare module "express" { url: string; } - interface MediaType { + export interface MediaType { value: string; quality: number; type: string; subtype: string; } - interface Send { + export interface Send { (status: number, body?: any): Response; (body: any): Response; } - interface Response extends http.ServerResponse { + export interface Response extends NodeHttp.ServerResponse { /** * Set status `code`. * @@ -889,11 +890,11 @@ declare module "express" { charset: string; } - interface RequestFunction { + export interface RequestFunction { (req: Request, res: Response, next: Function): any; } - interface Application extends IRouter { + export interface Application extends IRouter { /** * Initialize the server. * @@ -1145,7 +1146,7 @@ declare module "express" { routes: any; } - interface Express extends Application { + export interface Express extends Application { /** * Framework version. */ @@ -1199,7 +1200,7 @@ declare module "express" { * * @param options */ - function bodyParser(options?: any): Handler; + export function bodyParser(options?: any): Handler; /** * Error handler: @@ -1222,7 +1223,7 @@ declare module "express" { * * When accepted connect will output a nice html stack trace. */ - function errorHandler(opts?: any): Handler; + export function errorHandler(opts?: any): Handler; /** * Method Override: @@ -1235,7 +1236,7 @@ declare module "express" { * * @param key */ - function methodOverride(key?: string): Handler; + export function methodOverride(key?: string): Handler; /** * Cookie parser: @@ -1256,7 +1257,7 @@ declare module "express" { * * @param secret */ - function cookieParser(secret?: string): Handler; + export function cookieParser(secret?: string): Handler; /** * Session: @@ -1393,7 +1394,7 @@ declare module "express" { * * @param options */ - function session(options?: any): Handler; + export function session(options?: any): Handler; /** * Hash the given `sess` object omitting changes @@ -1401,7 +1402,7 @@ declare module "express" { * * @param sess */ - function hash(sess: string): string; + export function hash(sess: string): string; /** * Static: @@ -1427,7 +1428,7 @@ declare module "express" { * @param root * @param options */ - function static(root: string, options?: any): Handler; + export function static(root: string, options?: any): Handler; /** * Basic Auth: @@ -1492,7 +1493,7 @@ declare module "express" { * * @param options */ - function compress(options?: any): Handler; + export function compress(options?: any): Handler; /** * Cookie Session: @@ -1519,7 +1520,7 @@ declare module "express" { * * @param options */ - function cookieSession(options?: any): Handler; + export function cookieSession(options?: any): Handler; /** * Anti CSRF: @@ -1560,7 +1561,7 @@ declare module "express" { * @param root * @param options */ - function directory(root: string, options?: any): Handler; + export function directory(root: string, options?: any): Handler; /** * Favicon: @@ -1609,7 +1610,7 @@ declare module "express" { * * @param options */ - function json(options?: any): Handler; + export function json(options?: any): Handler; /** * Limit: @@ -1623,9 +1624,9 @@ declare module "express" { * .use(connect.limit('5.5mb')) * .use(handleImageUpload) */ - function limit(bytes: number): Handler; + export function limit(bytes: number): Handler; - function limit(bytes: string): Handler; + export function limit(bytes: string): Handler; /** * Logger: @@ -1686,18 +1687,18 @@ declare module "express" { * * connect.logger.format('name', 'string or function') */ - function logger(options: string): Handler; + export function logger(options: string): Handler; - function logger(options: Function): Handler; + export function logger(options: Function): Handler; - function logger(options?: any): Handler; + export function logger(options?: any): Handler; /** * Compile `fmt` into a function. * * @param fmt */ - function compile(fmt: string): Handler; + export function compile(fmt: string): Handler; /** * Define a token function with the given `name`, @@ -1706,14 +1707,14 @@ declare module "express" { * @param name * @param fn */ - function token(name: string, fn: Function): any; + export function token(name: string, fn: Function): any; /** * Define a `fmt` with the given `name`. */ - function format(name: string, str: string): any; + export function format(name: string, str: string): any; - function format(name: string, str: Function): any; + export function format(name: string, str: Function): any; /** * Query: @@ -1731,7 +1732,7 @@ declare module "express" { * * The `options` passed are provided to qs.parse function. */ - function query(options: any): Handler; + export function query(options: any): Handler; /** * Reponse time: @@ -1739,7 +1740,7 @@ declare module "express" { * Adds the `X-Response-Time` header displaying the response * duration in milliseconds. */ - function responseTime(): Handler; + export function responseTime(): Handler; /** * Static cache: @@ -1771,7 +1772,7 @@ declare module "express" { * - `maxObjects` max cache objects [128] * - `maxLength` max cache object length 256kb */ - function staticCache(options: any): Handler; + export function staticCache(options: any): Handler; /** * Timeout: @@ -1784,7 +1785,7 @@ declare module "express" { * the response behaviour. This error has the `.timeout` property as * well as `.status == 408`. */ - function timeout(ms: number): Handler; + export function timeout(ms: number): Handler; /** * Vhost: @@ -1802,14 +1803,10 @@ declare module "express" { * @param hostname * @param server */ - function vhost(hostname: string, server: any): Handler; + export function vhost(hostname: string, server: any): Handler; - function urlencoded(): any; + export function urlencoded(): any; - function multipart(): any; - - } - - export = e; + export function multipart(): any; } diff --git a/node/node.d.ts b/node/node.d.ts index 4fafb883e..ddfb5b94a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -224,14 +224,16 @@ interface NodeTimer { * MODULES * * * ************************************************/ -declare module "querystring" { +declare module "querystring" { export = NodeQueryString; } +declare module NodeQueryString { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; export function escape(): any; export function unescape(): any; } -declare module "events" { +declare module "events" { export = NodeEvents; } +declare module NodeEvents { export class EventEmitter implements NodeEventEmitter { static listenerCount(emitter: EventEmitter, event: string): number; @@ -246,10 +248,8 @@ declare module "events" { } } -declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); +declare module "http" { export = NodeHttp; } +declare module NodeHttp { export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; @@ -267,7 +267,7 @@ declare module "http" { setEncoding(encoding?: string): void; pause(): void; resume(): void; - connection: net.Socket; + connection: NodeNet.Socket; } export interface ServerResponse extends NodeEventEmitter, WritableStream { // Extended base methods @@ -335,9 +335,8 @@ declare module "http" { export var globalAgent: Agent; } -declare module "cluster" { - import child = require("child_process"); - import events = require("events"); +declare module "cluster" { export = NodeCluster; } +declare module NodeCluster { export interface ClusterSettings { exec?: string; @@ -345,9 +344,9 @@ declare module "cluster" { silent?: boolean; } - export class Worker extends events.EventEmitter { + export class Worker extends NodeEvents.EventEmitter { id: string; - process: child.ChildProcess; + process: NodeChildProcess.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any): void; kill(signal?: string): void; @@ -375,8 +374,9 @@ declare module "cluster" { export function emit(event: string, ...args: any[]): boolean; } -declare module "zlib" { - import stream = require("stream"); +declare module "zlib" { export = NodeZlib; } +declare module NodeZlib { + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends ReadWriteStream { } @@ -437,7 +437,8 @@ declare module "zlib" { export var Z_NULL: number; } -declare module "os" { +declare module "os" { export = NodeOs; } +declare module NodeOs { export function tmpDir(): string; export function hostname(): string; export function type(): string; @@ -453,10 +454,8 @@ declare module "os" { export var EOL: string; } -declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); +declare module "https" { export = NodeHttps; } +declare module NodeHttps { export interface ServerOptions { pfx?: any; @@ -499,14 +498,15 @@ declare module "https" { export var Agent: { new (options?: RequestOptions): Agent; }; - export interface Server extends tls.Server { } + export interface Server extends NodeTls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; + export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; export var globalAgent: Agent; } -declare module "punycode" { +declare module "punycode" { export = NodePunyCode; } +declare module NodePunyCode { export function decode(string: string): string; export function encode(string: string): string; export function toUnicode(domain: string): string; @@ -519,9 +519,8 @@ declare module "punycode" { export var version: any; } -declare module "repl" { - import stream = require("stream"); - import events = require("events"); +declare module "repl" { export = NodeRepl; } +declare module NodeRepl { export interface ReplOptions { prompt?: string; @@ -537,9 +536,8 @@ declare module "repl" { export function start(options: ReplOptions): NodeEventEmitter; } -declare module "readline" { - import events = require("events"); - import stream = require("stream"); +declare module "readline" { export = NodeReadLine; } +declare module NodeReadLine { export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; @@ -559,7 +557,8 @@ declare module "readline" { export function createInterface(options: ReadLineOptions): ReadLine; } -declare module "vm" { +declare module "vm" { export = NodeVm; } +declare module NodeVm { export interface Context { } export interface Script { runInThisContext(): void; @@ -572,9 +571,8 @@ declare module "vm" { export function createScript(code: string, filename?: string): Script; } -declare module "child_process" { - import events = require("events"); - import stream = require("stream"); +declare module "child_process" { export = NodeChildProcess; } +declare module NodeChildProcess { export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; @@ -621,7 +619,8 @@ declare module "child_process" { }): ChildProcess; } -declare module "url" { +declare module "url" { export = NodeUrl; } +declare module NodeUrl { export interface Url { href: string; protocol: string; @@ -651,7 +650,8 @@ declare module "url" { export function resolve(from: string, to: string): string; } -declare module "dns" { +declare module "dns" { export = NodeDns; } +declare module NodeDns { 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[]; @@ -666,8 +666,8 @@ declare module "dns" { export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } -declare module "net" { - import stream = require("stream"); +declare module "net" { export = NodeNet; } +declare module NodeNet { export interface Socket extends ReadWriteStream { // Extended base methods @@ -728,8 +728,8 @@ declare module "net" { export function isIPv6(input: string): boolean; } -declare module "dgram" { - import events = require("events"); +declare module "dgram" { export = NodeDgram; } +declare module NodeDgram { export function createSocket(type: string, callback?: Function): Socket; @@ -746,8 +746,8 @@ declare module "dgram" { } } -declare module "fs" { - import stream = require("stream"); +declare module "fs" { export = NodeFs; } +declare module NodeFs { interface Stats { isFile(): boolean; @@ -893,7 +893,8 @@ declare module "fs" { }): WriteStream; } -declare module "path" { +declare module "path" { export = NodePath; } +declare module NodePath { export function normalize(p: string): string; export function join(...paths: any[]): string; export function resolve(...pathSegments: any[]): string; @@ -904,7 +905,8 @@ declare module "path" { export var sep: string; } -declare module "string_decoder" { +declare module "string_decoder" { export = NodeStringDecoder; } +declare module NodeStringDecoder { export interface NodeStringDecoder { write(buffer: NodeBuffer): string; detectIncompleteChar(buffer: NodeBuffer): number; @@ -914,10 +916,8 @@ declare module "string_decoder" { }; } -declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); +declare module "tls" { export = NodeTls; } +declare module NodeTls { var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; @@ -940,7 +940,7 @@ declare module "tls" { export interface ConnectionOptions { host?: string; port?: number; - socket?: net.Socket; + socket?: NodeNet.Socket; pfx?: any; //string | Buffer key?: any; //string | Buffer passphrase?: string; @@ -951,7 +951,7 @@ declare module "tls" { servername?: string; } - export interface Server extends net.Server { + export interface Server extends NodeNet.Server { // Extended base methods listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; listen(path: string, listeningListener?: Function): void; @@ -995,10 +995,11 @@ declare module "tls" { 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 createSecurePair(credentials?: NodeCrypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; } -declare module "crypto" { +declare module "crypto" { export = NodeCrypto; } +declare module NodeCrypto { export interface CredentialDetails { pfx: string; key: string; @@ -1064,8 +1065,8 @@ declare module "crypto" { export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; } -declare module "stream" { - import events = require("events"); +declare module "stream" { export = NodeStream; } +declare module NodeStream { export interface ReadableOptions { highWaterMark?: number; @@ -1073,7 +1074,7 @@ declare module "stream" { objectMode?: boolean; } - export class Readable extends events.EventEmitter implements ReadableStream { + export class Readable extends NodeEvents.EventEmitter implements ReadableStream { readable: boolean; constructor(opts?: ReadableOptions); _read(size: number): void; @@ -1094,7 +1095,7 @@ declare module "stream" { decodeStrings?: boolean; } - export class Writable extends events.EventEmitter implements WritableStream { + export class Writable extends NodeEvents.EventEmitter implements WritableStream { writable: boolean; constructor(opts?: WritableOptions); _write(data: NodeBuffer, encoding: string, callback: Function): void; @@ -1130,7 +1131,7 @@ declare module "stream" { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements ReadWriteStream { + export class Transform extends NodeEvents.EventEmitter implements ReadWriteStream { readable: boolean; writable: boolean; constructor(opts?: TransformOptions); @@ -1159,7 +1160,8 @@ declare module "stream" { export class PassThrough extends Transform {} } -declare module "util" { +declare module "util" { export = NodeUtil; } +declare module NodeUtil { export interface InspectOptions { showHidden?: boolean; depth?: number; @@ -1182,9 +1184,10 @@ declare module "util" { export function inherits(constructor: any, superConstructor: any): void; } -declare module "assert" { - function internal (value: any, message?: string): void; - module internal { +declare module "assert" { export = NodeAssert; } +declare function NodeAssert(value: any, message?: string): void; +declare module NodeAssert { + export class AssertionError implements Error { name: string; message: string; @@ -1220,29 +1223,26 @@ declare module "assert" { } export function ifError(value: any): void; - } - - export = internal; } -declare module "tty" { - import net = require("net"); +declare module "tty" { export = NodeTty; } +declare module NodeTty { export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export interface ReadStream extends NodeNet.Socket { isRaw: boolean; setRawMode(mode: boolean): void; } - export interface WriteStream extends net.Socket { + export interface WriteStream extends NodeNet.Socket { columns: number; rows: number; } } -declare module "domain" { - import events = require("events"); +declare module "domain" { export = NodeDomain; } +declare module NodeDomain { - export class Domain extends events.EventEmitter { + export class Domain extends NodeEvents.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; remove(emitter: NodeEventEmitter): void; From 1fd18add08705c7d0a6196dc372d52b465176332 Mon Sep 17 00:00:00 2001 From: troy_paypac Date: Wed, 26 Mar 2014 14:58:30 +0800 Subject: [PATCH 02/13] internal module defns for node and express --- express/express.d.ts | 99 +++++++++++++++--------------- node/node.d.ts | 140 +++++++++++++++++++++---------------------- 2 files changed, 118 insertions(+), 121 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 243aa41d4..e18b7bc7d 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -12,14 +12,11 @@ /// -declare module "express" { - import http = require('http'); +declare module "express" { export = ExpressStatic; } +declare function ExpressStatic(): ExpressStatic.Express +declare module ExpressStatic { - // Merged declaration, e is both a callable function and a namespace - function e(): e.Express; - - module e { - interface IRoute { + export interface IRoute { path: string; method: string; @@ -35,7 +32,7 @@ declare module "express" { match(path: string): boolean; } - class Route implements IRoute { + export class Route implements IRoute { path: string; method: string; @@ -62,7 +59,7 @@ declare module "express" { new (method: string, path: string, callbacks: Function[], options: any): Route; } - interface IRouter { + export interface IRouter { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -107,6 +104,8 @@ declare module "express" { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): T; get(name: RegExp, ...handlers: RequestFunction[]): T; @@ -141,6 +140,8 @@ declare module "express" { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): Router; get(name: RegExp, ...handlers: RequestFunction[]): Router; @@ -162,11 +163,11 @@ declare module "express" { patch(name: RegExp, ...handlers: RequestFunction[]): Router; } - interface Handler { + export interface Handler { (req: Request, res: Response, next?: Function): void; } - interface CookieOptions { + export interface CookieOptions { maxAge?: number; signed?: boolean; expires?: Date; @@ -176,9 +177,9 @@ declare module "express" { secure?: boolean; } - interface Errback { (err: Error): void; } + export interface Errback { (err: Error): void; } - interface Session { + export interface Session { /** * Update reset `.cookie.maxAge` to prevent * the cookie from expiring when the @@ -229,7 +230,7 @@ declare module "express" { count: number; } - interface Request { + export interface Request { session: Session; @@ -533,19 +534,19 @@ declare module "express" { url: string; } - interface MediaType { + export interface MediaType { value: string; quality: number; type: string; subtype: string; } - interface Send { + export interface Send { (status: number, body?: any): Response; (body: any): Response; } - interface Response extends http.ServerResponse { + export interface Response extends NodeHttp.ServerResponse { /** * Set status `code`. * @@ -889,11 +890,11 @@ declare module "express" { charset: string; } - interface RequestFunction { + export interface RequestFunction { (req: Request, res: Response, next: Function): any; } - interface Application extends IRouter { + export interface Application extends IRouter { /** * Initialize the server. * @@ -1145,7 +1146,7 @@ declare module "express" { routes: any; } - interface Express extends Application { + export interface Express extends Application { /** * Framework version. */ @@ -1199,7 +1200,7 @@ declare module "express" { * * @param options */ - function bodyParser(options?: any): Handler; + export function bodyParser(options?: any): Handler; /** * Error handler: @@ -1222,7 +1223,7 @@ declare module "express" { * * When accepted connect will output a nice html stack trace. */ - function errorHandler(opts?: any): Handler; + export function errorHandler(opts?: any): Handler; /** * Method Override: @@ -1235,7 +1236,7 @@ declare module "express" { * * @param key */ - function methodOverride(key?: string): Handler; + export function methodOverride(key?: string): Handler; /** * Cookie parser: @@ -1256,7 +1257,7 @@ declare module "express" { * * @param secret */ - function cookieParser(secret?: string): Handler; + export function cookieParser(secret?: string): Handler; /** * Session: @@ -1393,7 +1394,7 @@ declare module "express" { * * @param options */ - function session(options?: any): Handler; + export function session(options?: any): Handler; /** * Hash the given `sess` object omitting changes @@ -1401,7 +1402,7 @@ declare module "express" { * * @param sess */ - function hash(sess: string): string; + export function hash(sess: string): string; /** * Static: @@ -1427,7 +1428,7 @@ declare module "express" { * @param root * @param options */ - function static(root: string, options?: any): Handler; + export function static(root: string, options?: any): Handler; /** * Basic Auth: @@ -1492,7 +1493,7 @@ declare module "express" { * * @param options */ - function compress(options?: any): Handler; + export function compress(options?: any): Handler; /** * Cookie Session: @@ -1519,7 +1520,7 @@ declare module "express" { * * @param options */ - function cookieSession(options?: any): Handler; + export function cookieSession(options?: any): Handler; /** * Anti CSRF: @@ -1560,7 +1561,7 @@ declare module "express" { * @param root * @param options */ - function directory(root: string, options?: any): Handler; + export function directory(root: string, options?: any): Handler; /** * Favicon: @@ -1609,7 +1610,7 @@ declare module "express" { * * @param options */ - function json(options?: any): Handler; + export function json(options?: any): Handler; /** * Limit: @@ -1623,9 +1624,9 @@ declare module "express" { * .use(connect.limit('5.5mb')) * .use(handleImageUpload) */ - function limit(bytes: number): Handler; + export function limit(bytes: number): Handler; - function limit(bytes: string): Handler; + export function limit(bytes: string): Handler; /** * Logger: @@ -1686,18 +1687,18 @@ declare module "express" { * * connect.logger.format('name', 'string or function') */ - function logger(options: string): Handler; + export function logger(options: string): Handler; - function logger(options: Function): Handler; + export function logger(options: Function): Handler; - function logger(options?: any): Handler; + export function logger(options?: any): Handler; /** * Compile `fmt` into a function. * * @param fmt */ - function compile(fmt: string): Handler; + export function compile(fmt: string): Handler; /** * Define a token function with the given `name`, @@ -1706,14 +1707,14 @@ declare module "express" { * @param name * @param fn */ - function token(name: string, fn: Function): any; + export function token(name: string, fn: Function): any; /** * Define a `fmt` with the given `name`. */ - function format(name: string, str: string): any; + export function format(name: string, str: string): any; - function format(name: string, str: Function): any; + export function format(name: string, str: Function): any; /** * Query: @@ -1731,7 +1732,7 @@ declare module "express" { * * The `options` passed are provided to qs.parse function. */ - function query(options: any): Handler; + export function query(options: any): Handler; /** * Reponse time: @@ -1739,7 +1740,7 @@ declare module "express" { * Adds the `X-Response-Time` header displaying the response * duration in milliseconds. */ - function responseTime(): Handler; + export function responseTime(): Handler; /** * Static cache: @@ -1771,7 +1772,7 @@ declare module "express" { * - `maxObjects` max cache objects [128] * - `maxLength` max cache object length 256kb */ - function staticCache(options: any): Handler; + export function staticCache(options: any): Handler; /** * Timeout: @@ -1784,7 +1785,7 @@ declare module "express" { * the response behaviour. This error has the `.timeout` property as * well as `.status == 408`. */ - function timeout(ms: number): Handler; + export function timeout(ms: number): Handler; /** * Vhost: @@ -1802,14 +1803,10 @@ declare module "express" { * @param hostname * @param server */ - function vhost(hostname: string, server: any): Handler; + export function vhost(hostname: string, server: any): Handler; - function urlencoded(): any; + export function urlencoded(): any; - function multipart(): any; - - } - - export = e; + export function multipart(): any; } diff --git a/node/node.d.ts b/node/node.d.ts index 4fafb883e..ddfb5b94a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -224,14 +224,16 @@ interface NodeTimer { * MODULES * * * ************************************************/ -declare module "querystring" { +declare module "querystring" { export = NodeQueryString; } +declare module NodeQueryString { export function stringify(obj: any, sep?: string, eq?: string): string; export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; export function escape(): any; export function unescape(): any; } -declare module "events" { +declare module "events" { export = NodeEvents; } +declare module NodeEvents { export class EventEmitter implements NodeEventEmitter { static listenerCount(emitter: EventEmitter, event: string): number; @@ -246,10 +248,8 @@ declare module "events" { } } -declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); +declare module "http" { export = NodeHttp; } +declare module NodeHttp { export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; @@ -267,7 +267,7 @@ declare module "http" { setEncoding(encoding?: string): void; pause(): void; resume(): void; - connection: net.Socket; + connection: NodeNet.Socket; } export interface ServerResponse extends NodeEventEmitter, WritableStream { // Extended base methods @@ -335,9 +335,8 @@ declare module "http" { export var globalAgent: Agent; } -declare module "cluster" { - import child = require("child_process"); - import events = require("events"); +declare module "cluster" { export = NodeCluster; } +declare module NodeCluster { export interface ClusterSettings { exec?: string; @@ -345,9 +344,9 @@ declare module "cluster" { silent?: boolean; } - export class Worker extends events.EventEmitter { + export class Worker extends NodeEvents.EventEmitter { id: string; - process: child.ChildProcess; + process: NodeChildProcess.ChildProcess; suicide: boolean; send(message: any, sendHandle?: any): void; kill(signal?: string): void; @@ -375,8 +374,9 @@ declare module "cluster" { export function emit(event: string, ...args: any[]): boolean; } -declare module "zlib" { - import stream = require("stream"); +declare module "zlib" { export = NodeZlib; } +declare module NodeZlib { + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends ReadWriteStream { } @@ -437,7 +437,8 @@ declare module "zlib" { export var Z_NULL: number; } -declare module "os" { +declare module "os" { export = NodeOs; } +declare module NodeOs { export function tmpDir(): string; export function hostname(): string; export function type(): string; @@ -453,10 +454,8 @@ declare module "os" { export var EOL: string; } -declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); +declare module "https" { export = NodeHttps; } +declare module NodeHttps { export interface ServerOptions { pfx?: any; @@ -499,14 +498,15 @@ declare module "https" { export var Agent: { new (options?: RequestOptions): Agent; }; - export interface Server extends tls.Server { } + export interface Server extends NodeTls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; + export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; export var globalAgent: Agent; } -declare module "punycode" { +declare module "punycode" { export = NodePunyCode; } +declare module NodePunyCode { export function decode(string: string): string; export function encode(string: string): string; export function toUnicode(domain: string): string; @@ -519,9 +519,8 @@ declare module "punycode" { export var version: any; } -declare module "repl" { - import stream = require("stream"); - import events = require("events"); +declare module "repl" { export = NodeRepl; } +declare module NodeRepl { export interface ReplOptions { prompt?: string; @@ -537,9 +536,8 @@ declare module "repl" { export function start(options: ReplOptions): NodeEventEmitter; } -declare module "readline" { - import events = require("events"); - import stream = require("stream"); +declare module "readline" { export = NodeReadLine; } +declare module NodeReadLine { export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; @@ -559,7 +557,8 @@ declare module "readline" { export function createInterface(options: ReadLineOptions): ReadLine; } -declare module "vm" { +declare module "vm" { export = NodeVm; } +declare module NodeVm { export interface Context { } export interface Script { runInThisContext(): void; @@ -572,9 +571,8 @@ declare module "vm" { export function createScript(code: string, filename?: string): Script; } -declare module "child_process" { - import events = require("events"); - import stream = require("stream"); +declare module "child_process" { export = NodeChildProcess; } +declare module NodeChildProcess { export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; @@ -621,7 +619,8 @@ declare module "child_process" { }): ChildProcess; } -declare module "url" { +declare module "url" { export = NodeUrl; } +declare module NodeUrl { export interface Url { href: string; protocol: string; @@ -651,7 +650,8 @@ declare module "url" { export function resolve(from: string, to: string): string; } -declare module "dns" { +declare module "dns" { export = NodeDns; } +declare module NodeDns { 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[]; @@ -666,8 +666,8 @@ declare module "dns" { export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } -declare module "net" { - import stream = require("stream"); +declare module "net" { export = NodeNet; } +declare module NodeNet { export interface Socket extends ReadWriteStream { // Extended base methods @@ -728,8 +728,8 @@ declare module "net" { export function isIPv6(input: string): boolean; } -declare module "dgram" { - import events = require("events"); +declare module "dgram" { export = NodeDgram; } +declare module NodeDgram { export function createSocket(type: string, callback?: Function): Socket; @@ -746,8 +746,8 @@ declare module "dgram" { } } -declare module "fs" { - import stream = require("stream"); +declare module "fs" { export = NodeFs; } +declare module NodeFs { interface Stats { isFile(): boolean; @@ -893,7 +893,8 @@ declare module "fs" { }): WriteStream; } -declare module "path" { +declare module "path" { export = NodePath; } +declare module NodePath { export function normalize(p: string): string; export function join(...paths: any[]): string; export function resolve(...pathSegments: any[]): string; @@ -904,7 +905,8 @@ declare module "path" { export var sep: string; } -declare module "string_decoder" { +declare module "string_decoder" { export = NodeStringDecoder; } +declare module NodeStringDecoder { export interface NodeStringDecoder { write(buffer: NodeBuffer): string; detectIncompleteChar(buffer: NodeBuffer): number; @@ -914,10 +916,8 @@ declare module "string_decoder" { }; } -declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); +declare module "tls" { export = NodeTls; } +declare module NodeTls { var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; @@ -940,7 +940,7 @@ declare module "tls" { export interface ConnectionOptions { host?: string; port?: number; - socket?: net.Socket; + socket?: NodeNet.Socket; pfx?: any; //string | Buffer key?: any; //string | Buffer passphrase?: string; @@ -951,7 +951,7 @@ declare module "tls" { servername?: string; } - export interface Server extends net.Server { + export interface Server extends NodeNet.Server { // Extended base methods listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; listen(path: string, listeningListener?: Function): void; @@ -995,10 +995,11 @@ declare module "tls" { 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 createSecurePair(credentials?: NodeCrypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; } -declare module "crypto" { +declare module "crypto" { export = NodeCrypto; } +declare module NodeCrypto { export interface CredentialDetails { pfx: string; key: string; @@ -1064,8 +1065,8 @@ declare module "crypto" { export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; } -declare module "stream" { - import events = require("events"); +declare module "stream" { export = NodeStream; } +declare module NodeStream { export interface ReadableOptions { highWaterMark?: number; @@ -1073,7 +1074,7 @@ declare module "stream" { objectMode?: boolean; } - export class Readable extends events.EventEmitter implements ReadableStream { + export class Readable extends NodeEvents.EventEmitter implements ReadableStream { readable: boolean; constructor(opts?: ReadableOptions); _read(size: number): void; @@ -1094,7 +1095,7 @@ declare module "stream" { decodeStrings?: boolean; } - export class Writable extends events.EventEmitter implements WritableStream { + export class Writable extends NodeEvents.EventEmitter implements WritableStream { writable: boolean; constructor(opts?: WritableOptions); _write(data: NodeBuffer, encoding: string, callback: Function): void; @@ -1130,7 +1131,7 @@ declare module "stream" { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements ReadWriteStream { + export class Transform extends NodeEvents.EventEmitter implements ReadWriteStream { readable: boolean; writable: boolean; constructor(opts?: TransformOptions); @@ -1159,7 +1160,8 @@ declare module "stream" { export class PassThrough extends Transform {} } -declare module "util" { +declare module "util" { export = NodeUtil; } +declare module NodeUtil { export interface InspectOptions { showHidden?: boolean; depth?: number; @@ -1182,9 +1184,10 @@ declare module "util" { export function inherits(constructor: any, superConstructor: any): void; } -declare module "assert" { - function internal (value: any, message?: string): void; - module internal { +declare module "assert" { export = NodeAssert; } +declare function NodeAssert(value: any, message?: string): void; +declare module NodeAssert { + export class AssertionError implements Error { name: string; message: string; @@ -1220,29 +1223,26 @@ declare module "assert" { } export function ifError(value: any): void; - } - - export = internal; } -declare module "tty" { - import net = require("net"); +declare module "tty" { export = NodeTty; } +declare module NodeTty { export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export interface ReadStream extends NodeNet.Socket { isRaw: boolean; setRawMode(mode: boolean): void; } - export interface WriteStream extends net.Socket { + export interface WriteStream extends NodeNet.Socket { columns: number; rows: number; } } -declare module "domain" { - import events = require("events"); +declare module "domain" { export = NodeDomain; } +declare module NodeDomain { - export class Domain extends events.EventEmitter { + export class Domain extends NodeEvents.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; remove(emitter: NodeEventEmitter): void; From 08e8430ce59073aaf47b9b9332c989c6bff04cf0 Mon Sep 17 00:00:00 2001 From: maanasa Date: Mon, 24 Mar 2014 15:29:49 +0530 Subject: [PATCH 03/13] Update typeahead.d.ts added support for call typeahead(options, dataset) where options include hint, highlight and minLength all of which are optional. --- typeahead/typeahead.d.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index 9ee948392..f6f387986 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -50,6 +50,16 @@ interface JQuery { * @param query The query to be set in case method 'setQuery' is used. */ typeahead(methodName: string, query: string): JQuery; + + /** + * Accomodates specifying options such as hint and highlight. + * This is in correspondence to the examples mentioned in http://twitter.github.io/typeahead.js/examples/ + * + * @constructor + * @param options ('hint' or 'highlight' or 'minLength' all of which are optional) + * @param dataset Array of datasets + */ + typeahead(options: Twitter.Typeahead.Options, dataset: Twitter.Typeahead.Dataset): JQuery; } declare module Twitter.Typeahead { @@ -243,4 +253,26 @@ declare module Twitter.Typeahead { */ tokens: string[]; } + + /** + * When initializing a typeahead, there are a number of options you can configure. + */ + interface Options { + /** + * highlight: If true, when suggestions are rendered, + * pattern matches for the current query in text nodes will be wrapped in a strong element. + * Defaults to false. + */ + highlight?: boolean; + + /** + * If false, the typeahead will not show a hint. Defaults to true. + */ + hint?: boolean; + + /** + * The minimum character length needed before suggestions start getting rendered. Defaults to 1. + */ + minLength?: number; + } } From 63199e8ecc6829b2097829aecd8ac726770aac2c Mon Sep 17 00:00:00 2001 From: maanasa Date: Wed, 26 Mar 2014 17:04:20 +0530 Subject: [PATCH 04/13] Update typeahead-tests.ts --- typeahead/typeahead-tests.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index f93049a44..3a24fb152 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -71,3 +71,16 @@ $('.example-films .typeahead').typeahead([ engine: Hogan } ]); + +//Basic substring search +//Specifies options along with datasets. In this case the dataset uses a custom substring matcher function as its source +$('#the-basics .typeahead').typeahead({ + hint: true, + highlight: true, + minLength: 1 +}, +{ + name: 'states', + displayKey: 'value', + source: substringMatcher(states) +}); From b47ce62205575b22a07ccb7ec614fdb3cbf034b5 Mon Sep 17 00:00:00 2001 From: maanasa Date: Wed, 26 Mar 2014 17:45:30 +0530 Subject: [PATCH 05/13] Update typeahead-tests.ts Adding tests for including options --- typeahead/typeahead-tests.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/typeahead/typeahead-tests.ts b/typeahead/typeahead-tests.ts index 3a24fb152..67fc8d31a 100644 --- a/typeahead/typeahead-tests.ts +++ b/typeahead/typeahead-tests.ts @@ -72,15 +72,16 @@ $('.example-films .typeahead').typeahead([ } ]); -//Basic substring search -//Specifies options along with datasets. In this case the dataset uses a custom substring matcher function as its source -$('#the-basics .typeahead').typeahead({ +// Countries - Modified the first test here to add options +// Specifies options to display hint with a highlight and adds a minimum length restriction for search +// Prefetches data, stores it in localStorage, and searches it on the client +$('.example-countries .typeahead').typeahead({ hint: true, highlight: true, - minLength: 1 + minLength: 2 }, { - name: 'states', - displayKey: 'value', - source: substringMatcher(states) + name: 'countries', + prefetch: '../data/countries.json', + limit: 10 }); From a7829a1fd977e3e51bd2a5921b78f75ef036a333 Mon Sep 17 00:00:00 2001 From: Troy Gerwien Date: Fri, 28 Mar 2014 22:32:20 +0800 Subject: [PATCH 06/13] referenceable types throughout node and express All node modules and classes can be referenced by type name. External module support remains unchanged, but now static type information is available for all node modules and types without needing to go through the external module definitions. Similar for express. --- express/express.d.ts | 8 +- node/node.d.ts | 2017 ++++++++++++++++++++++-------------------- 2 files changed, 1053 insertions(+), 972 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index e18b7bc7d..b7331a43d 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -12,8 +12,10 @@ /// -declare module "express" { export = ExpressStatic; } -declare function ExpressStatic(): ExpressStatic.Express +declare module "express" { var _: ExpressStatic; export = _; } +interface ExpressStatic{ + (): ExpressStatic.Express +} declare module ExpressStatic { export interface IRoute { @@ -546,7 +548,7 @@ declare module ExpressStatic { (body: any): Response; } - export interface Response extends NodeHttp.ServerResponse { + export interface Response extends NodeJs.Http.ServerResponse { /** * Set status `code`. * diff --git a/node/node.d.ts b/node/node.d.ts index ddfb5b94a..f82ffe202 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -221,1041 +221,1120 @@ interface NodeTimer { /************************************************ * * -* MODULES * +* MODULES - EXTERNAL * * * ************************************************/ -declare module "querystring" { export = NodeQueryString; } -declare module NodeQueryString { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; -} -declare module "events" { export = NodeEvents; } -declare module NodeEvents { - export class EventEmitter implements NodeEventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; +declare module "querystring" { var _: NodeJs.QueryString; export = _; } +declare module "events" { var _: NodeJs.Events; export = _; } +declare module "http" { var _: NodeJs.Http; export = _; } +declare module "cluster" { var _: NodeJs.Cluster; export = _; } +declare module "zlib" { var _: NodeJs.Zlib; export = _; } +declare module "os" { var _: NodeJs.Os; export = _; } +declare module "https" { var _: NodeJs.Https; export = _; } +declare module "punycode" { var _: NodeJs.PunyCode; export = _; } +declare module "repl" { var _: NodeJs.Repl; export = _; } +declare module "readline" { var _: NodeJs.ReadLine; export = _; } +declare module "vm" { var _: NodeJs.Vm; export = _; } +declare module "child_process" { var _: NodeJs.ChildProcess; export = _; } +declare module "url" { var _: NodeJs.Url; export = _; } +declare module "dns" { var _: NodeJs.Dns; export = _; } +declare module "net" { var _: NodeJs.Net; export = _; } +declare module "dgram" { var _: NodeJs.Dgram; export = _; } +declare module "fs" { var _: NodeJs.Fs; export = _; } +declare module "path" { var _: NodeJs.Path; export = _; } +declare module "string_decoder" { var _: NodeJs.StringDecoder; export = _; } +declare module "tls" { var _: NodeJs.Tls; export = _; } +declare module "crypto" { var _: NodeJs.Crypto; export = _; } +declare module "stream" { var _: NodeJs.Stream; export = _; } +declare module "util" { var _: NodeJs.Util; export = _; } +declare module "assert" { var _: NodeJs.Assert; export = _; } +declare module "tty" { var _: NodeJs.Tty; export = _; } +declare module "domain" { var _: NodeJs.Domain; export = _; } - 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; +/************************************************ +* * +* MODULES - INTERNAL * +* * +************************************************/ + +declare module NodeJs { + + // "querystring" module + export interface QueryString { + stringify(obj: any, sep?: string, eq?: string): string; + parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + escape(): any; + unescape(): any; + } + + // "events" module + export interface Events { + EventEmitter: Events.EventEmitterStatic; + } + export module Events { + export interface EventEmitterStatic { + listenerCount(emitter: EventEmitter, event: string): number; + } + + export interface EventEmitter extends NodeEventEmitter { + 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; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + } + + // "http" module + export interface Http { + STATUS_CODES: any; + createServer(requestListener?: (request: Http.ServerRequest, response: Http.ServerResponse) =>void ): Http.Server; + createClient(port?: number, host?: string): any; + request(options: any, callback?: Function): Http.ClientRequest; + get(options: any, callback?: Function): Http.ClientRequest; + globalAgent: Http.Agent; + } + export module Http { + + export interface Server extends NodeEventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; + listen(path: string, callback?: Function): void; + listen(handle: any, listeningListener?: Function): void; + close(cb?: any): void; + maxHeadersCount: number; + } + export interface ServerRequest extends NodeEventEmitter, ReadableStream { + method: string; + url: string; + headers: any; + trailers: string; + httpVersion: string; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; + connection: Net.Socket; + } + export interface ServerResponse extends NodeEventEmitter, WritableStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, 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; + setHeader(name: string, value: 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: NodeBuffer, 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 NodeEventEmitter, WritableStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, 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?: Function): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + // Extended base methods + end(): void; + end(buffer: NodeBuffer, 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 ClientResponse extends NodeEventEmitter, ReadableStream { + statusCode: number; + httpVersion: string; + headers: any; + trailers: any; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; + } + export interface Agent { maxSockets: number; sockets: any; requests: any; } + } + + // "cluster" module + export interface Cluster { + settings: Cluster.ClusterSettings; + isMaster: boolean; + isWorker: boolean; + setupMaster(settings?: Cluster.ClusterSettings): void; + fork(env?: any): Worker; + disconnect(callback?: Function): void; + worker: Worker; + workers: Worker[]; + + // Event emitter + addListener(event: string, listener: Function): void; + on(event: string, listener: Function): any; + once(event: string, listener: Function): void; + removeListener(event: string, listener: Function): void; + removeAllListeners(event?: string): void; setMaxListeners(n: number): void; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; - } -} - -declare module "http" { export = NodeHttp; } -declare module NodeHttp { - - export interface Server extends NodeEventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; - listen(path: string, callback?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(cb?: any): void; - maxHeadersCount: number; } - export interface ServerRequest extends NodeEventEmitter, ReadableStream { - method: string; - url: string; - headers: any; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - connection: NodeNet.Socket; - } - export interface ServerResponse extends NodeEventEmitter, WritableStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; + export module Cluster { - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - setHeader(name: string, value: string): void; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } - // Extended base methods - end(): void; - end(buffer: NodeBuffer, 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 NodeEventEmitter, WritableStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, 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?: Function): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - // Extended base methods - end(): void; - end(buffer: NodeBuffer, 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 ClientResponse extends NodeEventEmitter, ReadableStream { - statusCode: number; - httpVersion: string; - headers: any; - trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; - } - export interface Agent { maxSockets: number; sockets: any; requests: any; } - - export var STATUS_CODES: any; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; - export var globalAgent: Agent; -} - -declare module "cluster" { export = NodeCluster; } -declare module NodeCluster { - - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; + export interface Worker extends Events.EventEmitter { + id: string; + process: ChildProcess.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } } - export class Worker extends NodeEvents.EventEmitter { - id: string; - process: NodeChildProcess.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): void; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; + // "zlib" module + export interface Zlib { + createGzip(options?: Zlib.ZlibOptions): Zlib.Gzip; + createGunzip(options?: Zlib.ZlibOptions): Zlib.Gunzip; + createDeflate(options?: Zlib.ZlibOptions): Zlib.Deflate; + createInflate(options?: Zlib.ZlibOptions): Zlib.Inflate; + createDeflateRaw(options?: Zlib.ZlibOptions): Zlib.DeflateRaw; + createInflateRaw(options?: Zlib.ZlibOptions): Zlib.InflateRaw; + createUnzip(options?: Zlib.ZlibOptions): Zlib.Unzip; + + deflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + deflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + gzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + gunzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + inflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + inflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + unzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; + + // Constants + Z_NO_FLUSH: number; + Z_PARTIAL_FLUSH: number; + Z_SYNC_FLUSH: number; + Z_FULL_FLUSH: number; + Z_FINISH: number; + Z_BLOCK: number; + Z_TREES: number; + Z_OK: number; + Z_STREAM_END: number; + Z_NEED_DICT: number; + Z_ERRNO: number; + Z_STREAM_ERROR: number; + Z_DATA_ERROR: number; + Z_MEM_ERROR: number; + Z_BUF_ERROR: number; + Z_VERSION_ERROR: number; + Z_NO_COMPRESSION: number; + Z_BEST_SPEED: number; + Z_BEST_COMPRESSION: number; + Z_DEFAULT_COMPRESSION: number; + Z_FILTERED: number; + Z_HUFFMAN_ONLY: number; + Z_RLE: number; + Z_FIXED: number; + Z_DEFAULT_STRATEGY: number; + Z_BINARY: number; + Z_TEXT: number; + Z_ASCII: number; + Z_UNKNOWN: number; + Z_DEFLATED: number; + Z_NULL: number; + } + export module Zlib { + + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends ReadWriteStream { } + export interface Gunzip extends ReadWriteStream { } + export interface Deflate extends ReadWriteStream { } + export interface Inflate extends ReadWriteStream { } + export interface DeflateRaw extends ReadWriteStream { } + export interface InflateRaw extends ReadWriteStream { } + export interface Unzip extends ReadWriteStream { } } - 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: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): 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" { export = NodeZlib; } -declare module NodeZlib { - - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - - export interface Gzip extends ReadWriteStream { } - export interface Gunzip extends ReadWriteStream { } - export interface Deflate extends ReadWriteStream { } - export interface Inflate extends ReadWriteStream { } - export interface DeflateRaw extends ReadWriteStream { } - export interface InflateRaw extends ReadWriteStream { } - export interface Unzip extends ReadWriteStream { } - - 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: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function gunzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflate(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRaw(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - export function unzip(buf: NodeBuffer, callback: (error: Error, result: any) =>void ): void; - - // 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 = NodeOs; } -declare module NodeOs { - export function tmpDir(): 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(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; - export var EOL: string; -} - -declare module "https" { export = NodeHttps; } -declare module NodeHttps { - - 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; + // "os" module + export interface Os { + tmpDir(): string; + hostname(): string; + type(): string; + platform(): string; + arch(): string; + release(): string; + uptime(): number; + loadavg(): number[]; + totalmem(): number; + freemem(): number; + cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + networkInterfaces(): any; + EOL: string; } - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; + // "https" module + export interface Https { + Agent: new(options?: Https.RequestOptions) => Https.Agent; + + createServer(options: Https.ServerOptions, requestListener?: Function): Https.Server; + request(options: Https.RequestOptions, callback?: (res: NodeEventEmitter) => void): Http.ClientRequest; + get(options: Https.RequestOptions, callback?: (res: NodeEventEmitter) => void): Http.ClientRequest; + globalAgent: Https.Agent; + } + export module Https { + + 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 { + host?: string; + hostname?: string; + port?: number; + path?: string; + method?: string; + headers?: any; + auth?: string; + agent?: any; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + export interface Server extends Tls.Server { } } - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; - } - export var Agent: { - new (options?: RequestOptions): Agent; - }; - export interface Server extends NodeTls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; - export function get(options: RequestOptions, callback?: (res: NodeEventEmitter) => void): NodeHttp.ClientRequest; - export var globalAgent: Agent; -} - -declare module "punycode" { export = NodePunyCode; } -declare module NodePunyCode { - 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 { + // "punycode" module + export interface PunyCode { decode(string: string): string; - encode(codePoints: number[]): string; - } - export var version: any; -} - -declare module "repl" { export = NodeRepl; } -declare module NodeRepl { - - export interface ReplOptions { - prompt?: string; - input?: ReadableStream; - output?: WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - } - export function start(options: ReplOptions): NodeEventEmitter; -} - -declare module "readline" { export = NodeReadLine; } -declare module NodeReadLine { - - export interface ReadLine extends NodeEventEmitter { - setPrompt(prompt: string, length: number): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; - close(): void; - write(data: any, key?: any): void; - } - export interface ReadLineOptions { - input: ReadableStream; - output: WritableStream; - completer?: Function; - terminal?: boolean; - } - export function createInterface(options: ReadLineOptions): ReadLine; -} - -declare module "vm" { export = NodeVm; } -declare module NodeVm { - 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; -} - -declare module "child_process" { export = NodeChildProcess; } -declare module NodeChildProcess { - - export interface ChildProcess extends NodeEventEmitter { - stdin: WritableStream; - stdout: ReadableStream; - stderr: ReadableStream; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle: any): void; - disconnect(): void; + encode(string: string): string; + toUnicode(domain: string): string; + toASCII(domain: string): string; + ucs2: { + decode(string: string): string; + encode(codePoints: number[]): string; + } + version: any; } - export function spawn(command: string, args?: string[], options?: { - cwd?: string; - stdio?: any; - custom?: any; - env?: any; - detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function execFile(file: string, args: string[], options: { - cwd?: string; - stdio?: any; - customFds?: any; - env?: any; - encoding?: string; - timeout?: number; - maxBuffer?: string; - killSignal?: string; - }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { - cwd?: string; - env?: any; - encoding?: string; - }): ChildProcess; -} + // "repl" module + export interface Repl { + start(options: Repl.ReplOptions): NodeEventEmitter; + } + export module Repl { -declare module "url" { export = NodeUrl; } -declare module NodeUrl { + export interface ReplOptions { + prompt?: string; + input?: ReadableStream; + output?: WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + } + + // "readline" module + export interface ReadLine { + createInterface(options: ReadLine.ReadLineOptions): ReadLine.ReadLine; + } + export module ReadLine { + + export interface ReadLine extends NodeEventEmitter { + setPrompt(prompt: string, length: number): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; + close(): void; + write(data: any, key?: any): void; + } + export interface ReadLineOptions { + input: ReadableStream; + output: WritableStream; + completer?: Function; + terminal?: boolean; + } + } + + // "vm" module + export interface Vm { + runInThisContext(code: string, filename?: string): void; + runInNewContext(code: string, sandbox?: Vm.Context, filename?: string): void; + runInContext(code: string, context: Vm.Context, filename?: string): void; + createContext(initSandbox?: Vm.Context): Vm.Context; + createScript(code: string, filename?: string): Vm.Script; + } + export module Vm { + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + } + + // "child_process" module + export interface ChildProcess { + spawn(command: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; + }): ChildProcess.ChildProcess; + exec(command: string, options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess.ChildProcess; + exec(command: string, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess.ChildProcess; + execFile(file: string, args: string[], options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: string; + killSignal?: string; + }, callback: (error: Error, stdout: NodeBuffer, stderr: NodeBuffer) =>void ): ChildProcess.ChildProcess; + fork(modulePath: string, args?: string[], options?: { + cwd?: string; + env?: any; + encoding?: string; + }): ChildProcess.ChildProcess; + } + export module ChildProcess { + + export interface ChildProcess extends NodeEventEmitter { + stdin: WritableStream; + stdout: ReadableStream; + stderr: ReadableStream; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle: any): void; + disconnect(): void; + } + } + + // "url" module export interface Url { - href: string; - protocol: string; - auth: string; - hostname: string; - port: string; - host: string; - pathname: string; - search: string; - query: string; - slashes: boolean; + parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url.Url; + format(url: Url.UrlOptions): string; + resolve(from: string, to: string): string; + } + export module Url { + export interface Url { + href: string; + protocol: string; + auth: string; + hostname: string; + port: string; + host: string; + pathname: string; + search: string; + query: string; + slashes: boolean; + } + + export interface UrlOptions { + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: any; + } } - export interface UrlOptions { - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: any; + // "dns" module + export interface Dns { + lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: UrlOptions): string; - export function resolve(from: string, to: string): string; -} + // "net" module + export interface Net { + Socket: new(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }) => Net.Socket; -declare module "dns" { export = NodeDns; } -declare module NodeDns { - 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[]; -} + createServer(connectionListener?: (socket: Net.Socket) =>void ): Net.Server; + createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Net.Socket) =>void ): Net.Server; + connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Net.Socket; + connect(port: number, host?: string, connectionListener?: Function): Net.Socket; + connect(path: string, connectionListener?: Function): Net.Socket; + createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Net.Socket; + createConnection(port: number, host?: string, connectionListener?: Function): Net.Socket; + createConnection(path: string, connectionListener?: Function): Net.Socket; + isIP(input: string): number; + isIPv4(input: string): boolean; + isIPv6(input: string): boolean; + } + export module Net { -declare module "net" { export = NodeNet; } -declare module NodeNet { + export interface Socket extends ReadWriteStream { + // Extended base methods + write(buffer: NodeBuffer): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - export interface Socket extends ReadWriteStream { - // Extended base methods - write(buffer: NodeBuffer): boolean; - write(buffer: NodeBuffer, 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; }; + remoteAddress: string; + remotePort: number; + bytesRead: number; + bytesWritten: number; - 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; }; - remoteAddress: string; - remotePort: number; - bytesRead: number; - bytesWritten: number; + // Extended base methods + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } - // Extended base methods - end(): void; - end(buffer: NodeBuffer, 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 Server extends Socket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; + listen(path: string, listeningListener?: Function): void; + listen(handle: any, listeningListener?: Function): void; + close(callback?: Function): void; + address(): { port: number; family: string; address: string; }; + maxConnections: number; + connections: number; + } } - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface Server extends Socket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; - close(callback?: Function): void; - address(): { port: number; family: string; address: string; }; - maxConnections: number; - connections: number; + // "dgram" module + export interface Dgram { + createSocket(type: string, callback?: Function): Dgram.Socket; } - 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(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(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; -} + export module Dgram { -declare module "dgram" { export = NodeDgram; } -declare module NodeDgram { - - export function createSocket(type: string, callback?: Function): Socket; - - interface Socket extends NodeEventEmitter { - send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; - bind(port: number, address?: string): void; - close(): void; - address: { address: string; family: string; port: number; }; - 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" { export = NodeFs; } -declare module NodeFs { - - 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; + interface Socket extends NodeEventEmitter { + send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; + bind(port: number, address?: string): void; + close(): void; + address: { address: string; family: string; port: number; }; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } } - interface FSWatcher extends NodeEventEmitter { - close(): void; + // "fs" module + export interface Fs { + rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; + renameSync(oldPath: string, newPath: string): void; + truncate(path: string, callback?: (err?: ErrnoException) => void): void; + truncate(path: string, len: number, callback?: (err?: ErrnoException) => void): void; + truncateSync(path: string, len?: number): void; + ftruncate(fd: number, callback?: (err?: ErrnoException) => void): void; + ftruncate(fd: number, len: number, callback?: (err?: ErrnoException) => void): void; + ftruncateSync(fd: number, len?: number): void; + chown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + chownSync(path: string, uid: number, gid: number): void; + fchown(fd: number, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + fchownSync(fd: number, uid: number, gid: number): void; + lchown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; + lchownSync(path: string, uid: number, gid: number): void; + chmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + chmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + chmodSync(path: string, mode: number): void; + chmodSync(path: string, mode: string): void; + fchmod(fd: number, mode: number, callback?: (err?: ErrnoException) => void): void; + fchmod(fd: number, mode: string, callback?: (err?: ErrnoException) => void): void; + fchmodSync(fd: number, mode: number): void; + fchmodSync(fd: number, mode: string): void; + lchmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + lchmod(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + lchmodSync(path: string, mode: number): void; + lchmodSync(path: string, mode: string): void; + stat(path: string, callback?: (err: ErrnoException, stats: Fs.Stats) => any): void; + lstat(path: string, callback?: (err: ErrnoException, stats: Fs.Stats) => any): void; + fstat(fd: number, callback?: (err: ErrnoException, stats: Fs.Stats) => any): void; + statSync(path: string): Fs.Stats; + lstatSync(path: string): Fs.Stats; + fstatSync(fd: number): Fs.Stats; + link(srcpath: string, dstpath: string, callback?: (err?: ErrnoException) => void): void; + linkSync(srcpath: string, dstpath: string): void; + symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: ErrnoException) => void): void; + symlinkSync(srcpath: string, dstpath: string, type?: string): void; + readlink(path: string, callback?: (err: ErrnoException, linkString: string) => any): void; + readlinkSync(path: string): string; + realpath(path: string, callback?: (err: ErrnoException, resolvedPath: string) => any): void; + realpath(path: string, cache: {[path: string]: string}, callback: (err: ErrnoException, resolvedPath: string) =>any): void; + realpathSync(path: string, cache?: {[path: string]: string}): void; + unlink(path: string, callback?: (err?: ErrnoException) => void): void; + unlinkSync(path: string): void; + rmdir(path: string, callback?: (err?: ErrnoException) => void): void; + rmdirSync(path: string): void; + mkdir(path: string, callback?: (err?: ErrnoException) => void): void; + mkdir(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; + mkdir(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; + mkdirSync(path: string, mode?: number): void; + mkdirSync(path: string, mode?: string): void; + readdir(path: string, callback?: (err: ErrnoException, files: string[]) => void): void; + readdirSync(path: string): string[]; + close(fd: number, callback?: (err?: ErrnoException) => void): void; + closeSync(fd: number): void; + open(path: string, flags: string, callback?: (err: ErrnoException, fd: number) => any): void; + open(path: string, flags: string, mode: number, callback?: (err: ErrnoException, fd: number) => any): void; + open(path: string, flags: string, mode: string, callback?: (err: ErrnoException, fd: number) => any): void; + openSync(path: string, flags: string, mode?: number): number; + openSync(path: string, flags: string, mode?: string): number; + utimes(path: string, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + utimesSync(path: string, atime: number, mtime: number): void; + futimes(fd: number, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; + futimesSync(fd: number, atime: number, mtime: number): void; + fsync(fd: number, callback?: (err?: ErrnoException) => void): void; + fsyncSync(fd: number): void; + write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, written: number, buffer: NodeBuffer) => void): void; + writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; + read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; + readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; + readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void): void; + readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: ErrnoException, data: string) => void): void; + readFile(filename: string, options: { flag?: string; }, callback: (err: ErrnoException, data: NodeBuffer) => void): void; + readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; + readFileSync(filename: string, encoding: string): string; + readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; + writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; + writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; + writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; + writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; + appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; + appendFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; + appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + watchFile(filename: string, listener: (curr: Fs.Stats, prev: Fs.Stats) => void): void; + watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Fs.Stats, prev: Fs.Stats) => void): void; + unwatchFile(filename: string, listener?: (curr: Fs.Stats, prev: Fs.Stats) => void): void; + watch(filename: string, listener?: (event: string, filename: string) => any): Fs.FSWatcher; + watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): Fs.FSWatcher; + exists(path: string, callback?: (exists: boolean) => void): void; + existsSync(path: string): boolean; + createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: number; + bufferSize?: number; + }): Fs.ReadStream; + createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: string; + bufferSize?: number; + }): Fs.ReadStream; + createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + string?: string; + }): Fs.WriteStream; + } + export module Fs { + + export 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; + } + + export interface FSWatcher extends NodeEventEmitter { + close(): void; + } + + export interface ReadStream extends ReadableStream { } + export interface WriteStream extends WritableStream { } } - export interface ReadStream extends ReadableStream { } - export interface WriteStream extends WritableStream { } - - export function rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: 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?: ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: 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?: ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: 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: ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: 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?: ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: {[path: string]: string}): void; - export function unlink(path: string, callback?: (err?: ErrnoException) => void): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err?: ErrnoException) => void): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: number, callback?: (err?: ErrnoException) => void): void; - export function mkdir(path: string, mode: string, callback?: (err?: ErrnoException) => void): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; - export function close(fd: number, callback?: (err?: ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: 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?: ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function fsync(fd: number, callback?: (err?: ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, written: number, buffer: NodeBuffer) => void): void; - export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; - export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { flag?: string; }, callback: (err: ErrnoException, data: NodeBuffer) => void): void; - export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string, encoding: string): string; - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; - export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: 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: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: 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; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: number; - bufferSize?: number; - }): ReadStream; - export function createReadStream(path: string, options?: { - flags?: string; - encoding?: string; - fd?: string; - mode?: string; - bufferSize?: number; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - string?: string; - }): WriteStream; -} - -declare module "path" { export = NodePath; } -declare module NodePath { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - 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; -} - -declare module "string_decoder" { export = NodeStringDecoder; } -declare module NodeStringDecoder { - export interface NodeStringDecoder { - write(buffer: NodeBuffer): string; - detectIncompleteChar(buffer: NodeBuffer): number; - } - export var StringDecoder: { - new (encoding: string): NodeStringDecoder; - }; -} - -declare module "tls" { export = NodeTls; } -declare module NodeTls { - - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; - - export interface TlsOptions { - 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; + // "path" module + export interface Path { + normalize(p: string): string; + join(...paths: any[]): string; + resolve(...pathSegments: any[]): string; + relative(from: string, to: string): string; + dirname(p: string): string; + basename(p: string, ext?: string): string; + extname(p: string): string; + sep: string; } - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: NodeNet.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; + // "string_decoder" module + export interface StringDecoder { + StringDecoder: new(encoding: string) => StringDecoder.StringDecoder; + + } + export module StringDecoder { + export interface StringDecoder { + write(buffer: NodeBuffer): string; + detectIncompleteChar(buffer: NodeBuffer): number; + } } - export interface Server extends NodeNet.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; - listen(path: string, listeningListener?: Function): void; - listen(handle: any, listeningListener?: Function): void; + // "tls" module + export interface Tls { + CLIENT_RENEG_LIMIT: number; + CLIENT_RENEG_WINDOW: number; + createServer(options: Tls.TlsOptions, secureConnectionListener?: (cleartextStream: Tls.ClearTextStream) =>void ): Tls.Server; + connect(options: Tls.TlsOptions, secureConnectionListener?: () =>void ): Tls.ClearTextStream; + connect(port: number, host?: string, options?: Tls.ConnectionOptions, secureConnectListener?: () =>void ): Tls.ClearTextStream; + connect(port: number, options?: Tls.ConnectionOptions, secureConnectListener?: () =>void ): Tls.ClearTextStream; + createSecurePair(credentials?: Crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): Tls.SecurePair; + } + export module Tls { - listen(port: number, host?: string, callback?: Function): void; - close(): void; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { + export interface TlsOptions { + 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 { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; + listen(path: string, listeningListener?: Function): void; + listen(handle: any, listeningListener?: Function): void; + + listen(port: number, host?: string, callback?: Function): void; + close(): void; + 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 ReadWriteStream { + 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; + } + } + + // "crypto" module + export interface Crypto { + createCredentials(details: Crypto.CredentialDetails): Crypto.Credentials; + createHash(algorithm: string): Crypto.Hash; + createHmac(algorithm: string, key: string): Crypto.Hmac; + createCipher(algorithm: string, password: any): Crypto.Cipher; + createCipheriv(algorithm: string, key: any, iv: any): Crypto.Cipher; + createSign(algorithm: string): Crypto.Signer; + createVerify(algorith: string): Crypto.Verify; + createDiffieHellman(prime_length: number): Crypto.DiffieHellman; + createDiffieHellman(prime: number, encoding?: string): Crypto.DiffieHellman; + getDiffieHellman(group_name: string): Crypto.DiffieHellman; + pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; + randomBytes(size: number): NodeBuffer; + randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; + pseudoRandomBytes(size: number): NodeBuffer; + pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; + + } + export module Crypto { + export interface CredentialDetails { + pfx: string; key: string; + passphrase: string; cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding?: string): string; + } + export interface Hmac { + update(data: any): void; + digest(encoding?: string): void; + } + export interface Cipher { + update(data: any, input_encoding?: string, output_encoding?: string): string; + final(output_encoding?: string): string; + setAutoPadding(auto_padding: boolean): void; + createDecipher(algorithm: string, password: any): Decipher; + createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + } + export interface Decipher { + update(data: any, input_encoding?: string, output_encoding?: string): void; + final(output_encoding?: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export interface Signer { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export interface Verify { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + 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 interface ClearTextStream extends ReadWriteStream { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; + // "stream" module + export interface Stream { + Readable: new(opts?: Stream.ReadableOptions) => Stream.Readable; + Writable: new(opts?: Stream.WritableOptions) => Stream.Writable; + Duplex: new(opts?: Stream.DuplexOptions) => Stream.Duplex; + Transform: new(opts?: Stream.TransformOptions) => Stream.Transform; + } + export module Stream { + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export interface Readable extends Events.EventEmitter, ReadableStream { + readable: boolean; + _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: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + } + + export interface Writable extends Events.EventEmitter, WritableStream { + writable: boolean; + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export interface Duplex extends Readable, ReadWriteStream { + writable: boolean; + _write(data: NodeBuffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export interface Transform extends Events.EventEmitter, ReadWriteStream { + readable: boolean; + writable: boolean; + _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; + _transform(chunk: string, 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: string): void; + unshift(chunk: NodeBuffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(buffer: NodeBuffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: NodeBuffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface PassThrough extends Transform {} } - export interface SecurePair { - encrypted: any; - cleartext: any; + // "util" module + export interface Util { + format(format: any, ...param: any[]): string; + debug(string: string): void; + error(...param: any[]): void; + puts(...param: any[]): void; + print(...param: any[]): void; + log(string: string): void; + inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + inspect(object: any, options: Util.InspectOptions): string; + isArray(object: any): boolean; + isRegExp(object: any): boolean; + isDate(object: any): boolean; + isError(object: any): boolean; + inherits(constructor: any, superConstructor: any): void; + } + export module Util { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } } - 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?: NodeCrypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; -} + // "assert" module + export interface Assert { + (value: any, message?: string): void; + AssertionError: new(options?: Assert.AssertionErrorOptions) => Assert.AssertionError; -declare module "crypto" { export = NodeCrypto; } -declare module NodeCrypto { - 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; - interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding?: string): string; - } - interface Hmac { - update(data: any): void; - digest(encoding?: string): void; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - interface Cipher { - update(data: any, input_encoding?: string, output_encoding?: string): string; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - createDecipher(algorithm: string, password: any): Decipher; - createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - } - interface Decipher { - update(data: any, input_encoding?: string, output_encoding?: string): void; - final(output_encoding?: string): string; - setAutoPadding(auto_padding: boolean): void; - } - export function createSign(algorithm: string): Signer; - interface Signer { - update(data: any): void; - sign(private_key: string, output_format: string): string; - } - export function createVerify(algorith: string): Verify; - interface Verify { - 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 { - 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, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; - export function randomBytes(size: number): NodeBuffer; - export function randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; - export function pseudoRandomBytes(size: number): NodeBuffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; -} + fail(actual?: any, expected?: any, message?: string, operator?: string): void; + ok(value: any, message?: string): void; + equal(actual: any, expected: any, message?: string): void; + notEqual(actual: any, expected: any, message?: string): void; + deepEqual(actual: any, expected: any, message?: string): void; + notDeepEqual(acutal: any, expected: any, message?: string): void; + strictEqual(actual: any, expected: any, message?: string): void; + notStrictEqual(actual: any, expected: any, message?: string): void; + 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; + } -declare module "stream" { export = NodeStream; } -declare module NodeStream { + 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 interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; + ifError(value: any): void; } + export module Assert { - export class Readable extends NodeEvents.EventEmitter implements 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: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - push(chunk: any, encoding?: string): boolean; - } + export interface AssertionErrorOptions { + message?: string; + actual?: any; + expected?: any; + operator?: string; + stackStartFunction?: Function + } - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - } - - export class Writable extends NodeEvents.EventEmitter implements WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, 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 ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(data: NodeBuffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, 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 NodeEvents.EventEmitter implements ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; - _transform(chunk: string, 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: string): void; - unshift(chunk: NodeBuffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(buffer: NodeBuffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: NodeBuffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform {} -} - -declare module "util" { export = NodeUtil; } -declare module NodeUtil { - 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; -} - -declare module "assert" { export = NodeAssert; } -declare function NodeAssert(value: any, message?: string): void; -declare module NodeAssert { - - export class AssertionError implements Error { + export interface AssertionError extends 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 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; -} - -declare module "tty" { export = NodeTty; } -declare module NodeTty { - - export function isatty(fd: number): boolean; - export interface ReadStream extends NodeNet.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - } - export interface WriteStream extends NodeNet.Socket { - columns: number; - rows: number; - } -} - -declare module "domain" { export = NodeDomain; } -declare module NodeDomain { - - export class Domain extends NodeEvents.EventEmitter { - run(fn: Function): void; - add(emitter: NodeEventEmitter): void; - remove(emitter: NodeEventEmitter): 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; + // "tty" module + export interface Tty { + ReadStream: new() => Tty.ReadStream; + WriteStream: new() => Tty.WriteStream; + + isatty(fd: number): boolean; + } + export module Tty { + + export interface ReadStream extends Net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + } + export interface WriteStream extends Net.Socket { + columns: number; + rows: number; + } + } + + // "domain" module + export interface Domain { + Domain: new() => Domain.Domain; + + create(): Domain.Domain; + } + export module Domain { + + export interface Domain extends Events.EventEmitter { + run(fn: Function): void; + add(emitter: NodeEventEmitter): void; + remove(emitter: NodeEventEmitter): 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; + } + + } } From 368266b684bfa07c8d2ae1934e342add8be624aa Mon Sep 17 00:00:00 2001 From: Troy Gerwien Date: Sat, 29 Mar 2014 21:21:41 +0800 Subject: [PATCH 07/13] var-interface-module pattern now consistent Everything (in both node and express) now follows the pattern: ``` declare module "external-name" { import _ = InternalName.InnerName; export = _; } declare module InternalName { export var InnerName: InnerName; export interface InnerName { // functions and vars in here } export module InnerName { // Must be non-instantiated - so only interfaces and modules in here } } ``` --- express/express.d.ts | 130 ++++++++++----------------- node/node.d.ts | 207 +++++++++++++++++++++++-------------------- 2 files changed, 160 insertions(+), 177 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index b7331a43d..049871c35 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -12,13 +12,15 @@ /// -declare module "express" { var _: ExpressStatic; export = _; } -interface ExpressStatic{ - (): ExpressStatic.Express +declare module "express" { + import _ = Express.Static; + export = _; } -declare module ExpressStatic { +declare module Express { + export var Static: Static; + export module Static { - export interface IRoute { + export interface Route { path: string; method: string; @@ -32,17 +34,6 @@ declare module ExpressStatic { * populate `.params`. */ match(path: string): boolean; - } - - export class Route implements IRoute { - path: string; - - method: string; - - callbacks: Function[]; - - regexp: any; - match(path: string): boolean; /** * Initialize `Route` with the given HTTP `method`, `path`, @@ -129,40 +120,10 @@ declare module ExpressStatic { patch(name: RegExp, ...handlers: RequestFunction[]): T; } - export class Router implements IRouter { - new (options?: any): Router; + export interface Router extends IRouter { + new (options?: any): Router; - middleware (): any; - - param(name: string, fn: Function): Router; - - param(name: any[], fn: Function): Router; - - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - - all(path: string, ...callbacks: Function[]): void; - - get(name: string): string; - - get(name: string, ...handlers: RequestFunction[]): Router; - - get(name: RegExp, ...handlers: RequestFunction[]): Router; - - post(name: string, ...handlers: RequestFunction[]): Router; - - post(name: RegExp, ...handlers: RequestFunction[]): Router; - - put(name: string, ...handlers: RequestFunction[]): Router; - - put(name: RegExp, ...handlers: RequestFunction[]): Router; - - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; - - patch(name: string, ...handlers: RequestFunction[]): Router; - - patch(name: RegExp, ...handlers: RequestFunction[]): Router; + middleware (): any; } export interface Handler { @@ -1125,7 +1086,7 @@ declare module ExpressStatic { listen(handle: any, listeningListener?: Function): void; - route: IRoute; + route: Route; router: string; @@ -1174,6 +1135,9 @@ declare module ExpressStatic { response: Response; } + } + interface Static { + (): Express.Static.Express; /** * Body parser: @@ -1202,7 +1166,7 @@ declare module ExpressStatic { * * @param options */ - export function bodyParser(options?: any): Handler; + bodyParser(options?: any): Express.Static.Handler; /** * Error handler: @@ -1225,7 +1189,7 @@ declare module ExpressStatic { * * When accepted connect will output a nice html stack trace. */ - export function errorHandler(opts?: any): Handler; + errorHandler(opts?: any): Express.Static.Handler; /** * Method Override: @@ -1238,7 +1202,7 @@ declare module ExpressStatic { * * @param key */ - export function methodOverride(key?: string): Handler; + methodOverride(key?: string): Express.Static.Handler; /** * Cookie parser: @@ -1259,7 +1223,7 @@ declare module ExpressStatic { * * @param secret */ - export function cookieParser(secret?: string): Handler; + cookieParser(secret?: string): Express.Static.Handler; /** * Session: @@ -1396,7 +1360,7 @@ declare module ExpressStatic { * * @param options */ - export function session(options?: any): Handler; + session(options?: any): Express.Static.Handler; /** * Hash the given `sess` object omitting changes @@ -1404,7 +1368,7 @@ declare module ExpressStatic { * * @param sess */ - export function hash(sess: string): string; + hash(sess: string): string; /** * Static: @@ -1430,7 +1394,7 @@ declare module ExpressStatic { * @param root * @param options */ - export function static(root: string, options?: any): Handler; + static(root: string, options?: any): Express.Static.Handler; /** * Basic Auth: @@ -1462,11 +1426,11 @@ declare module ExpressStatic { * @param callback or username * @param realm */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; + basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Express.Static.Handler; - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; + basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Express.Static.Handler; - export function basicAuth(user: string, pass: string, realm?: string): Handler; + basicAuth(user: string, pass: string, realm?: string): Express.Static.Handler; /** * Compress: @@ -1495,7 +1459,7 @@ declare module ExpressStatic { * * @param options */ - export function compress(options?: any): Handler; + compress(options?: any): Express.Static.Handler; /** * Cookie Session: @@ -1522,7 +1486,7 @@ declare module ExpressStatic { * * @param options */ - export function cookieSession(options?: any): Handler; + cookieSession(options?: any): Express.Static.Handler; /** * Anti CSRF: @@ -1547,7 +1511,7 @@ declare module ExpressStatic { * * @param options */ - export function csrf(options?: {value?: Function}): Handler; + csrf(options?: {value?: Function}): Express.Static.Handler; /** * Directory: @@ -1563,7 +1527,7 @@ declare module ExpressStatic { * @param root * @param options */ - export function directory(root: string, options?: any): Handler; + directory(root: string, options?: any): Express.Static.Handler; /** * Favicon: @@ -1596,7 +1560,7 @@ declare module ExpressStatic { * @param path * @param options */ - export function favicon(path?: string, options?: any): Handler; + favicon(path?: string, options?: any): Express.Static.Handler; /** * JSON: @@ -1612,7 +1576,7 @@ declare module ExpressStatic { * * @param options */ - export function json(options?: any): Handler; + json(options?: any): Express.Static.Handler; /** * Limit: @@ -1626,9 +1590,9 @@ declare module ExpressStatic { * .use(connect.limit('5.5mb')) * .use(handleImageUpload) */ - export function limit(bytes: number): Handler; + limit(bytes: number): Express.Static.Handler; - export function limit(bytes: string): Handler; + limit(bytes: string): Express.Static.Handler; /** * Logger: @@ -1689,18 +1653,18 @@ declare module ExpressStatic { * * connect.logger.format('name', 'string or function') */ - export function logger(options: string): Handler; + logger(options: string): Express.Static.Handler; - export function logger(options: Function): Handler; + logger(options: Function): Express.Static.Handler; - export function logger(options?: any): Handler; + logger(options?: any): Express.Static.Handler; /** * Compile `fmt` into a function. * * @param fmt */ - export function compile(fmt: string): Handler; + compile(fmt: string): Express.Static.Handler; /** * Define a token function with the given `name`, @@ -1709,14 +1673,14 @@ declare module ExpressStatic { * @param name * @param fn */ - export function token(name: string, fn: Function): any; + token(name: string, fn: Function): any; /** * Define a `fmt` with the given `name`. */ - export function format(name: string, str: string): any; + format(name: string, str: string): any; - export function format(name: string, str: Function): any; + format(name: string, str: Function): any; /** * Query: @@ -1734,7 +1698,7 @@ declare module ExpressStatic { * * The `options` passed are provided to qs.parse function. */ - export function query(options: any): Handler; + query(options: any): Express.Static.Handler; /** * Reponse time: @@ -1742,7 +1706,7 @@ declare module ExpressStatic { * Adds the `X-Response-Time` header displaying the response * duration in milliseconds. */ - export function responseTime(): Handler; + responseTime(): Express.Static.Handler; /** * Static cache: @@ -1774,7 +1738,7 @@ declare module ExpressStatic { * - `maxObjects` max cache objects [128] * - `maxLength` max cache object length 256kb */ - export function staticCache(options: any): Handler; + staticCache(options: any): Express.Static.Handler; /** * Timeout: @@ -1787,7 +1751,7 @@ declare module ExpressStatic { * the response behaviour. This error has the `.timeout` property as * well as `.status == 408`. */ - export function timeout(ms: number): Handler; + timeout(ms: number): Express.Static.Handler; /** * Vhost: @@ -1805,10 +1769,10 @@ declare module ExpressStatic { * @param hostname * @param server */ - export function vhost(hostname: string, server: any): Handler; + vhost(hostname: string, server: any): Express.Static.Handler; - export function urlencoded(): any; + urlencoded(): any; - export function multipart(): any; + multipart(): any; + } } - diff --git a/node/node.d.ts b/node/node.d.ts index f82ffe202..f98400c46 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -225,32 +225,32 @@ interface NodeTimer { * * ************************************************/ -declare module "querystring" { var _: NodeJs.QueryString; export = _; } -declare module "events" { var _: NodeJs.Events; export = _; } -declare module "http" { var _: NodeJs.Http; export = _; } -declare module "cluster" { var _: NodeJs.Cluster; export = _; } -declare module "zlib" { var _: NodeJs.Zlib; export = _; } -declare module "os" { var _: NodeJs.Os; export = _; } -declare module "https" { var _: NodeJs.Https; export = _; } -declare module "punycode" { var _: NodeJs.PunyCode; export = _; } -declare module "repl" { var _: NodeJs.Repl; export = _; } -declare module "readline" { var _: NodeJs.ReadLine; export = _; } -declare module "vm" { var _: NodeJs.Vm; export = _; } -declare module "child_process" { var _: NodeJs.ChildProcess; export = _; } -declare module "url" { var _: NodeJs.Url; export = _; } -declare module "dns" { var _: NodeJs.Dns; export = _; } -declare module "net" { var _: NodeJs.Net; export = _; } -declare module "dgram" { var _: NodeJs.Dgram; export = _; } -declare module "fs" { var _: NodeJs.Fs; export = _; } -declare module "path" { var _: NodeJs.Path; export = _; } -declare module "string_decoder" { var _: NodeJs.StringDecoder; export = _; } -declare module "tls" { var _: NodeJs.Tls; export = _; } -declare module "crypto" { var _: NodeJs.Crypto; export = _; } -declare module "stream" { var _: NodeJs.Stream; export = _; } -declare module "util" { var _: NodeJs.Util; export = _; } -declare module "assert" { var _: NodeJs.Assert; export = _; } -declare module "tty" { var _: NodeJs.Tty; export = _; } -declare module "domain" { var _: NodeJs.Domain; export = _; } +declare module "querystring" { import _ = NodeJs.QueryString; export = _; } +declare module "events" { import _ = NodeJs.Events; export = _; } +declare module "http" { import _ = NodeJs.Http; export = _; } +declare module "cluster" { import _ = NodeJs.Cluster; export = _; } +declare module "zlib" { import _ = NodeJs.Zlib; export = _; } +declare module "os" { import _ = NodeJs.Os; export = _; } +declare module "https" { import _ = NodeJs.Https; export = _; } +declare module "punycode" { import _ = NodeJs.PunyCode; export = _; } +declare module "repl" { import _ = NodeJs.Repl; export = _; } +declare module "readline" { import _ = NodeJs.ReadLine; export = _; } +declare module "vm" { import _ = NodeJs.Vm; export = _; } +declare module "child_process" { import _ = NodeJs.ChildProcess; export = _; } +declare module "url" { import _ = NodeJs.Url; export = _; } +declare module "dns" { import _ = NodeJs.Dns; export = _; } +declare module "net" { import _ = NodeJs.Net; export = _; } +declare module "dgram" { import _ = NodeJs.Dgram; export = _; } +declare module "fs" { import _ = NodeJs.Fs; export = _; } +declare module "path" { import _ = NodeJs.Path; export = _; } +declare module "string_decoder" { import _ = NodeJs.StringDecoder; export = _; } +declare module "tls" { import _ = NodeJs.Tls; export = _; } +declare module "crypto" { import _ = NodeJs.Crypto; export = _; } +declare module "stream" { import _ = NodeJs.Stream; export = _; } +declare module "util" { import _ = NodeJs.Util; export = _; } +declare module "assert" { import _ = NodeJs.Assert; export = _; } +declare module "tty" { import _ = NodeJs.Tty; export = _; } +declare module "domain" { import _ = NodeJs.Domain; export = _; } /************************************************ * * @@ -260,15 +260,20 @@ declare module "domain" { var _: NodeJs.Domain; export = _; } declare module NodeJs { - // "querystring" module + + // ---------- "querystring" module ---------- + export var QueryString: QueryString; export interface QueryString { stringify(obj: any, sep?: string, eq?: string): string; parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; escape(): any; unescape(): any; } + export module QueryString { } - // "events" module + + // ---------- "events" module ---------- + export var Events: Events; export interface Events { EventEmitter: Events.EventEmitterStatic; } @@ -276,7 +281,6 @@ declare module NodeJs { export interface EventEmitterStatic { listenerCount(emitter: EventEmitter, event: string): number; } - export interface EventEmitter extends NodeEventEmitter { addListener(event: string, listener: Function): EventEmitter; on(event: string, listener: Function): EventEmitter; @@ -289,7 +293,9 @@ declare module NodeJs { } } - // "http" module + + // ---------- "http" module ---------- + export var Http: Http; export interface Http { STATUS_CODES: any; createServer(requestListener?: (request: Http.ServerRequest, response: Http.ServerResponse) =>void ): Http.Server; @@ -299,7 +305,6 @@ declare module NodeJs { globalAgent: Http.Agent; } export module Http { - export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; listen(path: string, callback?: Function): void; @@ -319,6 +324,7 @@ declare module NodeJs { connection: Net.Socket; } export interface ServerResponse extends NodeEventEmitter, WritableStream { + // Extended base methods write(buffer: NodeBuffer): boolean; write(buffer: NodeBuffer, cb?: Function): boolean; @@ -345,6 +351,7 @@ declare module NodeJs { end(data?: any, encoding?: string): void; } export interface ClientRequest extends NodeEventEmitter, WritableStream { + // Extended base methods write(buffer: NodeBuffer): boolean; write(buffer: NodeBuffer, cb?: Function): boolean; @@ -377,7 +384,9 @@ declare module NodeJs { export interface Agent { maxSockets: number; sockets: any; requests: any; } } - // "cluster" module + + // ---------- "cluster" module ---------- + export var Cluster: Cluster; export interface Cluster { settings: Cluster.ClusterSettings; isMaster: boolean; @@ -399,13 +408,11 @@ declare module NodeJs { emit(event: string, ...args: any[]): boolean; } export module Cluster { - export interface ClusterSettings { exec?: string; args?: string[]; silent?: boolean; } - export interface Worker extends Events.EventEmitter { id: string; process: ChildProcess.ChildProcess; @@ -417,7 +424,9 @@ declare module NodeJs { } } - // "zlib" module + + // ---------- "zlib" module ---------- + export var Zlib: Zlib; export interface Zlib { createGzip(options?: Zlib.ZlibOptions): Zlib.Gzip; createGunzip(options?: Zlib.ZlibOptions): Zlib.Gunzip; @@ -469,9 +478,7 @@ declare module NodeJs { Z_NULL: number; } export module Zlib { - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - export interface Gzip extends ReadWriteStream { } export interface Gunzip extends ReadWriteStream { } export interface Deflate extends ReadWriteStream { } @@ -481,7 +488,9 @@ declare module NodeJs { export interface Unzip extends ReadWriteStream { } } - // "os" module + + // ---------- "os" module ---------- + export var Os: Os; export interface Os { tmpDir(): string; hostname(): string; @@ -497,8 +506,11 @@ declare module NodeJs { networkInterfaces(): any; EOL: string; } + export module Os { } - // "https" module + + // ---------- "https" module ---------- + export var Https: Https; export interface Https { Agent: new(options?: Https.RequestOptions) => Https.Agent; @@ -508,7 +520,6 @@ declare module NodeJs { globalAgent: Https.Agent; } export module Https { - export interface ServerOptions { pfx?: any; key?: any; @@ -523,7 +534,6 @@ declare module NodeJs { NPNProtocols?: any; SNICallback?: (servername: string) => any; } - export interface RequestOptions { host?: string; hostname?: string; @@ -541,7 +551,6 @@ declare module NodeJs { ciphers?: string; rejectUnauthorized?: boolean; } - export interface Agent { maxSockets: number; sockets: any; @@ -550,7 +559,9 @@ declare module NodeJs { export interface Server extends Tls.Server { } } - // "punycode" module + + // ---------- "punycode" module ---------- + export var PunyCode: PunyCode; export interface PunyCode { decode(string: string): string; encode(string: string): string; @@ -562,13 +573,15 @@ declare module NodeJs { } version: any; } + export module PunyCode { } - // "repl" module + + // ---------- "repl" module ---------- + export var Repl: Repl; export interface Repl { start(options: Repl.ReplOptions): NodeEventEmitter; } export module Repl { - export interface ReplOptions { prompt?: string; input?: ReadableStream; @@ -582,12 +595,13 @@ declare module NodeJs { } } - // "readline" module + + // ---------- "readline" module ---------- + export var ReadLine: ReadLine; export interface ReadLine { createInterface(options: ReadLine.ReadLineOptions): ReadLine.ReadLine; } export module ReadLine { - export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; prompt(preserveCursor?: boolean): void; @@ -605,7 +619,9 @@ declare module NodeJs { } } - // "vm" module + + // ---------- "vm" module ---------- + export var Vm: Vm; export interface Vm { runInThisContext(code: string, filename?: string): void; runInNewContext(code: string, sandbox?: Vm.Context, filename?: string): void; @@ -621,7 +637,9 @@ declare module NodeJs { } } - // "child_process" module + + // ---------- "child_process" module ---------- + export var ChildProcess: ChildProcess; export interface ChildProcess { spawn(command: string, args?: string[], options?: { cwd?: string; @@ -658,7 +676,6 @@ declare module NodeJs { }): ChildProcess.ChildProcess; } export module ChildProcess { - export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; stdout: ReadableStream; @@ -670,7 +687,9 @@ declare module NodeJs { } } - // "url" module + + // ---------- "url" module ---------- + export var Url: Url; export interface Url { parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url.Url; format(url: Url.UrlOptions): string; @@ -689,7 +708,6 @@ declare module NodeJs { query: string; slashes: boolean; } - export interface UrlOptions { protocol?: string; auth?: string; @@ -702,7 +720,9 @@ declare module NodeJs { } } - // "dns" module + + // ---------- "dns" module ---------- + export var Dns: Dns; export interface Dns { lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; @@ -717,8 +737,11 @@ declare module NodeJs { resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } + export module Dns { } - // "net" module + + // ---------- "net" module ---------- + export var Net: Net; export interface Net { Socket: new(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }) => Net.Socket; @@ -735,8 +758,8 @@ declare module NodeJs { isIPv6(input: string): boolean; } export module Net { - export interface Socket extends ReadWriteStream { + // Extended base methods write(buffer: NodeBuffer): boolean; write(buffer: NodeBuffer, cb?: Function): boolean; @@ -768,7 +791,6 @@ declare module NodeJs { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface Server extends Socket { listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; listen(path: string, listeningListener?: Function): void; @@ -780,12 +802,13 @@ declare module NodeJs { } } - // "dgram" module + + // ---------- "dgram" module ---------- + export var Dgram: Dgram; export interface Dgram { createSocket(type: string, callback?: Function): Dgram.Socket; } export module Dgram { - interface Socket extends NodeEventEmitter { send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; bind(port: number, address?: string): void; @@ -799,7 +822,9 @@ declare module NodeJs { } } - // "fs" module + + // ---------- "fs" module ---------- + export var Fs: Fs; export interface Fs { rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; renameSync(oldPath: string, newPath: string): void; @@ -915,7 +940,6 @@ declare module NodeJs { }): Fs.WriteStream; } export module Fs { - export interface Stats { isFile(): boolean; isDirectory(): boolean; @@ -938,16 +962,16 @@ declare module NodeJs { mtime: Date; ctime: Date; } - export interface FSWatcher extends NodeEventEmitter { close(): void; } - export interface ReadStream extends ReadableStream { } export interface WriteStream extends WritableStream { } } - // "path" module + + // ---------- "path" module ---------- + export var Path: Path; export interface Path { normalize(p: string): string; join(...paths: any[]): string; @@ -958,11 +982,13 @@ declare module NodeJs { extname(p: string): string; sep: string; } + export module Path { } - // "string_decoder" module + + // ---------- "string_decoder" module ---------- + export var StringDecoder: StringDecoder; export interface StringDecoder { StringDecoder: new(encoding: string) => StringDecoder.StringDecoder; - } export module StringDecoder { export interface StringDecoder { @@ -971,7 +997,9 @@ declare module NodeJs { } } - // "tls" module + + // ---------- "tls" module ---------- + export var Tls: Tls; export interface Tls { CLIENT_RENEG_LIMIT: number; CLIENT_RENEG_WINDOW: number; @@ -982,7 +1010,6 @@ declare module NodeJs { createSecurePair(credentials?: Crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): Tls.SecurePair; } export module Tls { - export interface TlsOptions { pfx?: any; //string or buffer key?: any; //string or buffer @@ -997,7 +1024,6 @@ declare module NodeJs { NPNProtocols?: any; //array or Buffer; SNICallback?: (servername: string) => any; } - export interface ConnectionOptions { host?: string; port?: number; @@ -1011,7 +1037,6 @@ declare module NodeJs { NPNProtocols?: any; //Array of string | Buffer servername?: string; } - export interface Server extends Net.Server { // Extended base methods listen(port: number, host?: string, backlog?: number, listeningListener?: Function): void; @@ -1029,7 +1054,6 @@ declare module NodeJs { maxConnections: number; connections: number; } - export interface ClearTextStream extends ReadWriteStream { authorized: boolean; authorizationError: Error; @@ -1046,14 +1070,15 @@ declare module NodeJs { remoteAddress: string; remotePort: number; } - export interface SecurePair { encrypted: any; cleartext: any; } } - // "crypto" module + + // ---------- "crypto" module ---------- + export var Crypto: Crypto; export interface Crypto { createCredentials(details: Crypto.CredentialDetails): Crypto.Credentials; createHash(algorithm: string): Crypto.Hash; @@ -1070,7 +1095,6 @@ declare module NodeJs { randomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; pseudoRandomBytes(size: number): NodeBuffer; pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; - } export module Crypto { export interface CredentialDetails { @@ -1123,7 +1147,9 @@ declare module NodeJs { } } - // "stream" module + + // ---------- "stream" module ---------- + export var Stream: Stream; export interface Stream { Readable: new(opts?: Stream.ReadableOptions) => Stream.Readable; Writable: new(opts?: Stream.WritableOptions) => Stream.Writable; @@ -1131,13 +1157,11 @@ declare module NodeJs { Transform: new(opts?: Stream.TransformOptions) => Stream.Transform; } export module Stream { - export interface ReadableOptions { highWaterMark?: number; encoding?: string; objectMode?: boolean; } - export interface Readable extends Events.EventEmitter, ReadableStream { readable: boolean; _read(size: number): void; @@ -1152,12 +1176,10 @@ declare module NodeJs { wrap(oldStream: ReadableStream): ReadableStream; push(chunk: any, encoding?: string): boolean; } - export interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; } - export interface Writable extends Events.EventEmitter, WritableStream { writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; @@ -1170,7 +1192,6 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean; } @@ -1188,7 +1209,6 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. @@ -1216,11 +1236,12 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export interface PassThrough extends Transform {} } - // "util" module + + // ---------- "util" module ---------- + export var Util: Util; export interface Util { format(format: any, ...param: any[]): string; debug(string: string): void; @@ -1245,7 +1266,9 @@ declare module NodeJs { } } - // "assert" module + + // ---------- "assert" module ---------- + export var Assert: Assert; export interface Assert { (value: any, message?: string): void; AssertionError: new(options?: Assert.AssertionErrorOptions) => Assert.AssertionError; @@ -1264,18 +1287,15 @@ declare module NodeJs { (block: Function, error: RegExp, message?: string): void; (block: Function, error: (err: any) => boolean, message?: string): void; } - 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; } - ifError(value: any): void; } export module Assert { - export interface AssertionErrorOptions { message?: string; actual?: any; @@ -1283,8 +1303,8 @@ declare module NodeJs { operator?: string; stackStartFunction?: Function } - export interface AssertionError extends Error { + new(options?: AssertionErrorOptions): AssertionError; name: string; message: string; actual: any; @@ -1294,15 +1314,15 @@ declare module NodeJs { } } - // "tty" module + + // ---------- "tty" module ---------- + export var Tty: Tty; export interface Tty { ReadStream: new() => Tty.ReadStream; WriteStream: new() => Tty.WriteStream; - isatty(fd: number): boolean; } export module Tty { - export interface ReadStream extends Net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; @@ -1313,14 +1333,14 @@ declare module NodeJs { } } - // "domain" module + + // ---------- "domain" module ---------- + export var Domain: Domain; export interface Domain { Domain: new() => Domain.Domain; - create(): Domain.Domain; } export module Domain { - export interface Domain extends Events.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; @@ -1335,6 +1355,5 @@ declare module NodeJs { removeListener(event: string, listener: Function): Domain; removeAllListeners(event?: string): Domain; } - } } From 6f472b8f0920aa65960260a364c9e1577a862136 Mon Sep 17 00:00:00 2001 From: Troy Gerwien Date: Sun, 30 Mar 2014 10:05:57 +0800 Subject: [PATCH 08/13] WIP: all passing (bar assert) but needs more... Need to remove superfluous typings - eg NodeJs.QueryString.escape should not be valid --- express/express.d.ts | 157 +++++++++++++++++++++++++++++++------------ node/node.d.ts | 64 ++++++++++++------ 2 files changed, 159 insertions(+), 62 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 049871c35..f88df016b 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -17,10 +17,47 @@ declare module "express" { export = _; } declare module Express { - export var Static: Static; + export function Static(): Static.Express; + export interface Static { + (): Static.Express; + Route: new (method: string, path: string, callbacks: Function[], options: any) => Static.Route; + Router: new (options?: any) => Static.Router; + bodyParser(options?: any): Static.Handler; + errorHandler(opts?: any): Static.Handler; + methodOverride(key?: string): Static.Handler; + cookieParser(secret?: string): Static.Handler; + session(options?: any): Static.Handler; + hash(sess: string): string; + static(root: string, options?: any): Static.Handler; + basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Static.Handler; + basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Static.Handler; + basicAuth(user: string, pass: string, realm?: string): Static.Handler; + compress(options?: any): Static.Handler; + cookieSession(options?: any): Static.Handler; + csrf(options?: {value?: Function}): Static.Handler; + directory(root: string, options?: any): Static.Handler; + favicon(path?: string, options?: any): Static.Handler; + json(options?: any): Static.Handler; + limit(bytes: number): Static.Handler; + limit(bytes: string): Static.Handler; + logger(options: string): Static.Handler; + logger(options: Function): Static.Handler; + logger(options?: any): Static.Handler; + compile(fmt: string): Static.Handler; + token(name: string, fn: Function): any; + format(name: string, str: string): any; + format(name: string, str: Function): any; + query(options: any): Static.Handler; + responseTime(): Static.Handler; + staticCache(options: any): Static.Handler; + timeout(ms: number): Static.Handler; + vhost(hostname: string, server: any): Static.Handler; + urlencoded(): any; + multipart(): any; + } export module Static { - export interface Route { + interface IRoute { path: string; method: string; @@ -34,6 +71,17 @@ declare module Express { * populate `.params`. */ match(path: string): boolean; + } + + class Route implements IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + match(path: string): boolean; /** * Initialize `Route` with the given HTTP `method`, `path`, @@ -49,10 +97,10 @@ declare module Express { * @param callbacks * @param options */ - new (method: string, path: string, callbacks: Function[], options: any): Route; + constructor (method: string, path: string, callbacks: Function[], options: any); } - export interface IRouter { + interface IRouter { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -97,8 +145,6 @@ declare module Express { all(path: string, ...callbacks: Function[]): void; - get(name: string): string; - get(name: string, ...handlers: RequestFunction[]): T; get(name: RegExp, ...handlers: RequestFunction[]): T; @@ -120,10 +166,38 @@ declare module Express { patch(name: RegExp, ...handlers: RequestFunction[]): T; } - export interface Router extends IRouter { - new (options?: any): Router; + export class Router implements IRouter { + constructor (options?: any); middleware (): any; + + param(name: string, fn: Function): Router; + + param(name: any[], fn: Function): Router; + + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; + + all(path: string, ...callbacks: Function[]): void; + + get(name: string, ...handlers: RequestFunction[]): Router; + + get(name: RegExp, ...handlers: RequestFunction[]): Router; + + post(name: string, ...handlers: RequestFunction[]): Router; + + post(name: RegExp, ...handlers: RequestFunction[]): Router; + + put(name: string, ...handlers: RequestFunction[]): Router; + + put(name: RegExp, ...handlers: RequestFunction[]): Router; + + del(name: string, ...handlers: RequestFunction[]): Router; + + del(name: RegExp, ...handlers: RequestFunction[]): Router; + + patch(name: string, ...handlers: RequestFunction[]): Router; + + patch(name: RegExp, ...handlers: RequestFunction[]): Router; } export interface Handler { @@ -1135,9 +1209,6 @@ declare module Express { response: Response; } - } - interface Static { - (): Express.Static.Express; /** * Body parser: @@ -1166,7 +1237,7 @@ declare module Express { * * @param options */ - bodyParser(options?: any): Express.Static.Handler; + export function bodyParser(options?: any): Handler; /** * Error handler: @@ -1189,7 +1260,7 @@ declare module Express { * * When accepted connect will output a nice html stack trace. */ - errorHandler(opts?: any): Express.Static.Handler; + export function errorHandler(opts?: any): Handler; /** * Method Override: @@ -1202,7 +1273,7 @@ declare module Express { * * @param key */ - methodOverride(key?: string): Express.Static.Handler; + export function methodOverride(key?: string): Handler; /** * Cookie parser: @@ -1223,7 +1294,7 @@ declare module Express { * * @param secret */ - cookieParser(secret?: string): Express.Static.Handler; + export function cookieParser(secret?: string): Handler; /** * Session: @@ -1360,7 +1431,7 @@ declare module Express { * * @param options */ - session(options?: any): Express.Static.Handler; + export function session(options?: any): Handler; /** * Hash the given `sess` object omitting changes @@ -1368,7 +1439,7 @@ declare module Express { * * @param sess */ - hash(sess: string): string; + export function hash(sess: string): string; /** * Static: @@ -1394,7 +1465,7 @@ declare module Express { * @param root * @param options */ - static(root: string, options?: any): Express.Static.Handler; + export function static(root: string, options?: any): Handler; /** * Basic Auth: @@ -1426,11 +1497,11 @@ declare module Express { * @param callback or username * @param realm */ - basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Express.Static.Handler; + export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Express.Static.Handler; + export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - basicAuth(user: string, pass: string, realm?: string): Express.Static.Handler; + export function basicAuth(user: string, pass: string, realm?: string): Handler; /** * Compress: @@ -1459,7 +1530,7 @@ declare module Express { * * @param options */ - compress(options?: any): Express.Static.Handler; + export function compress(options?: any): Handler; /** * Cookie Session: @@ -1486,7 +1557,7 @@ declare module Express { * * @param options */ - cookieSession(options?: any): Express.Static.Handler; + export function cookieSession(options?: any): Handler; /** * Anti CSRF: @@ -1511,7 +1582,7 @@ declare module Express { * * @param options */ - csrf(options?: {value?: Function}): Express.Static.Handler; + export function csrf(options?: {value?: Function}): Handler; /** * Directory: @@ -1527,7 +1598,7 @@ declare module Express { * @param root * @param options */ - directory(root: string, options?: any): Express.Static.Handler; + export function directory(root: string, options?: any): Handler; /** * Favicon: @@ -1560,7 +1631,7 @@ declare module Express { * @param path * @param options */ - favicon(path?: string, options?: any): Express.Static.Handler; + export function favicon(path?: string, options?: any): Handler; /** * JSON: @@ -1576,7 +1647,7 @@ declare module Express { * * @param options */ - json(options?: any): Express.Static.Handler; + export function json(options?: any): Handler; /** * Limit: @@ -1590,9 +1661,9 @@ declare module Express { * .use(connect.limit('5.5mb')) * .use(handleImageUpload) */ - limit(bytes: number): Express.Static.Handler; + export function limit(bytes: number): Handler; - limit(bytes: string): Express.Static.Handler; + export function limit(bytes: string): Handler; /** * Logger: @@ -1653,18 +1724,18 @@ declare module Express { * * connect.logger.format('name', 'string or function') */ - logger(options: string): Express.Static.Handler; + export function logger(options: string): Handler; - logger(options: Function): Express.Static.Handler; + export function logger(options: Function): Handler; - logger(options?: any): Express.Static.Handler; + export function logger(options?: any): Handler; /** * Compile `fmt` into a function. * * @param fmt */ - compile(fmt: string): Express.Static.Handler; + export function compile(fmt: string): Handler; /** * Define a token function with the given `name`, @@ -1673,14 +1744,14 @@ declare module Express { * @param name * @param fn */ - token(name: string, fn: Function): any; + export function token(name: string, fn: Function): any; /** * Define a `fmt` with the given `name`. */ - format(name: string, str: string): any; + export function format(name: string, str: string): any; - format(name: string, str: Function): any; + export function format(name: string, str: Function): any; /** * Query: @@ -1698,7 +1769,7 @@ declare module Express { * * The `options` passed are provided to qs.parse function. */ - query(options: any): Express.Static.Handler; + export function query(options: any): Handler; /** * Reponse time: @@ -1706,7 +1777,7 @@ declare module Express { * Adds the `X-Response-Time` header displaying the response * duration in milliseconds. */ - responseTime(): Express.Static.Handler; + export function responseTime(): Handler; /** * Static cache: @@ -1738,7 +1809,7 @@ declare module Express { * - `maxObjects` max cache objects [128] * - `maxLength` max cache object length 256kb */ - staticCache(options: any): Express.Static.Handler; + export function staticCache(options: any): Handler; /** * Timeout: @@ -1751,7 +1822,7 @@ declare module Express { * the response behaviour. This error has the `.timeout` property as * well as `.status == 408`. */ - timeout(ms: number): Express.Static.Handler; + export function timeout(ms: number): Handler; /** * Vhost: @@ -1769,10 +1840,10 @@ declare module Express { * @param hostname * @param server */ - vhost(hostname: string, server: any): Express.Static.Handler; + export function vhost(hostname: string, server: any): Handler; - urlencoded(): any; + export function urlencoded(): any; - multipart(): any; + export function multipart(): any; } } diff --git a/node/node.d.ts b/node/node.d.ts index f98400c46..edeecf9fa 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -273,15 +273,15 @@ declare module NodeJs { // ---------- "events" module ---------- - export var Events: Events; export interface Events { - EventEmitter: Events.EventEmitterStatic; + EventEmitter: { + (): any // Correctly reflect the fact that this is a (constructor) function, without suggesting that instances can be obtained this way + listenerCount(emitter: Events.EventEmitter, event: string): number; + } } export module Events { - export interface EventEmitterStatic { - listenerCount(emitter: EventEmitter, event: string): number; - } - export interface EventEmitter extends NodeEventEmitter { + export class EventEmitter implements NodeEventEmitter { + 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; @@ -386,8 +386,10 @@ declare module NodeJs { // ---------- "cluster" module ---------- - export var Cluster: Cluster; export interface Cluster { + // NB: This is necessary duplicataion of the definitions in the Cluster module below. It is required + // so that type information is available both through pure types (eg NodeJs.Cluster), + // as well as through typed variables (eg var cluster) settings: Cluster.ClusterSettings; isMaster: boolean; isWorker: boolean; @@ -406,14 +408,37 @@ declare module NodeJs { setMaxListeners(n: number): void; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + + Worker: { + (): any // Correctly reflect the fact that this is a (constructor) function, without suggesting that instances can be obtained this way + } } export module Cluster { + export var settings: Cluster.ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: Cluster.ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): 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; + export interface ClusterSettings { exec?: string; args?: string[]; silent?: boolean; } - export interface Worker extends Events.EventEmitter { + export class Worker extends Events.EventEmitter { id: string; process: ChildProcess.ChildProcess; suicide: boolean; @@ -1149,7 +1174,6 @@ declare module NodeJs { // ---------- "stream" module ---------- - export var Stream: Stream; export interface Stream { Readable: new(opts?: Stream.ReadableOptions) => Stream.Readable; Writable: new(opts?: Stream.WritableOptions) => Stream.Writable; @@ -1162,7 +1186,8 @@ declare module NodeJs { encoding?: string; objectMode?: boolean; } - export interface Readable extends Events.EventEmitter, ReadableStream { + export class Readable extends Events.EventEmitter implements ReadableStream { + constructor(opts?: ReadableOptions); readable: boolean; _read(size: number): void; read(size?: number): any; @@ -1180,7 +1205,8 @@ declare module NodeJs { highWaterMark?: number; decodeStrings?: boolean; } - export interface Writable extends Events.EventEmitter, WritableStream { + export class Writable extends Events.EventEmitter implements WritableStream { + constructor(opts?: WritableOptions); writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1197,7 +1223,8 @@ declare module NodeJs { } // Note: Duplex extends both Readable and Writable. - export interface Duplex extends Readable, ReadWriteStream { + export class Duplex extends Readable implements ReadWriteStream { + constructor(opts?: DuplexOptions); writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1212,7 +1239,8 @@ declare module NodeJs { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export interface Transform extends Events.EventEmitter, ReadWriteStream { + export class Transform extends Events.EventEmitter implements ReadWriteStream { + constructor(opts?: TransformOptions); readable: boolean; writable: boolean; _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; @@ -1236,7 +1264,7 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export interface PassThrough extends Transform {} + export class PassThrough extends Transform {} } @@ -1268,7 +1296,6 @@ declare module NodeJs { // ---------- "assert" module ---------- - export var Assert: Assert; export interface Assert { (value: any, message?: string): void; AssertionError: new(options?: Assert.AssertionErrorOptions) => Assert.AssertionError; @@ -1303,8 +1330,8 @@ declare module NodeJs { operator?: string; stackStartFunction?: Function } - export interface AssertionError extends Error { - new(options?: AssertionErrorOptions): AssertionError; + export class AssertionError implements Error { + constructor(options?: AssertionErrorOptions); name: string; message: string; actual: any; @@ -1335,13 +1362,12 @@ declare module NodeJs { // ---------- "domain" module ---------- - export var Domain: Domain; export interface Domain { Domain: new() => Domain.Domain; create(): Domain.Domain; } export module Domain { - export interface Domain extends Events.EventEmitter { + export class Domain extends Events.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; remove(emitter: NodeEventEmitter): void; From c2b67de6aa0241be340ae0873210dbbcadf9a945 Mon Sep 17 00:00:00 2001 From: Troy Gerwien Date: Sun, 30 Mar 2014 21:56:50 +0800 Subject: [PATCH 09/13] Fixed assert, added comments, rechecked all - Added comments explaining the rationale/method of exposing into both 'type' and 'member' declaration spaces (see TLR 2.3) with example - Made the pattern consistent in both definition files - Fixed "assert" by adding 'export function Assert...' - Triple-checked with DT tests and additional tests --- express/express.d.ts | 15 +++++++- node/node.d.ts | 87 +++++++++++++++++++++++++++++--------------- 2 files changed, 71 insertions(+), 31 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index f88df016b..dc18cc58e 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -17,7 +17,19 @@ declare module "express" { export = _; } declare module Express { - export function Static(): Static.Express; + // NB: All typings in Express.Static are exposed in dual declaration spaces + // (i.e. as 'types' and as 'members' - see TypeScript Language Spec section 2.3) + // so that type information is available in both of the following scenarios: + // + // // Normal import: + // import express = require('express'); + // var app = express(); + // app.use(express.urlencoded()); + // + // // Typed variable: + // var express: Express.Static = someExpr() // a wrapped, mocked or otherwise obtained ref + // var app = express(); + // app.use(express.urlencoded()); export interface Static { (): Static.Express; Route: new (method: string, path: string, callbacks: Function[], options: any) => Static.Route; @@ -55,6 +67,7 @@ declare module Express { urlencoded(): any; multipart(): any; } + export function Static(): Static.Express; export module Static { interface IRoute { diff --git a/node/node.d.ts b/node/node.d.ts index edeecf9fa..b84ef7912 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -259,23 +259,34 @@ declare module "domain" { import _ = NodeJs.Domain; export = _; ************************************************/ declare module NodeJs { + // NB: All typings in this namespace are exposed in dual declaration spaces + // (i.e. as 'types' and as 'members' - see TypeScript Language Spec section 2.3) + // so that type information is available in both of the following scenarios: + // + // // Normal import: + // import http = require('http'); + // http.createServer((req, res) => {...}) + // + // // Typed variable: + // var http: NodeJs.Http = someExpr() // a wrapped, mocked or otherwise obtained ref + // http.createServer((req, res) => {...}) // ---------- "querystring" module ---------- - export var QueryString: QueryString; export interface QueryString { stringify(obj: any, sep?: string, eq?: string): string; parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; escape(): any; unescape(): any; } - export module QueryString { } + export var QueryString: QueryString; // ---------- "events" module ---------- export interface Events { EventEmitter: { - (): any // Correctly reflect the fact that this is a (constructor) function, without suggesting that instances can be obtained this way + (): any // Correctly reflect the fact that this is a (constructor) function, + // without suggesting that instances can be obtained this way listenerCount(emitter: Events.EventEmitter, event: string): number; } } @@ -295,7 +306,6 @@ declare module NodeJs { // ---------- "http" module ---------- - export var Http: Http; export interface Http { STATUS_CODES: any; createServer(requestListener?: (request: Http.ServerRequest, response: Http.ServerResponse) =>void ): Http.Server; @@ -304,6 +314,7 @@ declare module NodeJs { get(options: any, callback?: Function): Http.ClientRequest; globalAgent: Http.Agent; } + export var Http: Http; export module Http { export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; @@ -387,9 +398,6 @@ declare module NodeJs { // ---------- "cluster" module ---------- export interface Cluster { - // NB: This is necessary duplicataion of the definitions in the Cluster module below. It is required - // so that type information is available both through pure types (eg NodeJs.Cluster), - // as well as through typed variables (eg var cluster) settings: Cluster.ClusterSettings; isMaster: boolean; isWorker: boolean; @@ -451,7 +459,6 @@ declare module NodeJs { // ---------- "zlib" module ---------- - export var Zlib: Zlib; export interface Zlib { createGzip(options?: Zlib.ZlibOptions): Zlib.Gzip; createGunzip(options?: Zlib.ZlibOptions): Zlib.Gunzip; @@ -502,6 +509,7 @@ declare module NodeJs { Z_DEFLATED: number; Z_NULL: number; } + export var Zlib: Zlib; export module Zlib { export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends ReadWriteStream { } @@ -515,7 +523,6 @@ declare module NodeJs { // ---------- "os" module ---------- - export var Os: Os; export interface Os { tmpDir(): string; hostname(): string; @@ -531,11 +538,10 @@ declare module NodeJs { networkInterfaces(): any; EOL: string; } - export module Os { } + export var Os: Os; // ---------- "https" module ---------- - export var Https: Https; export interface Https { Agent: new(options?: Https.RequestOptions) => Https.Agent; @@ -544,6 +550,7 @@ declare module NodeJs { get(options: Https.RequestOptions, callback?: (res: NodeEventEmitter) => void): Http.ClientRequest; globalAgent: Https.Agent; } + export var Https: Https; export module Https { export interface ServerOptions { pfx?: any; @@ -586,7 +593,6 @@ declare module NodeJs { // ---------- "punycode" module ---------- - export var PunyCode: PunyCode; export interface PunyCode { decode(string: string): string; encode(string: string): string; @@ -598,14 +604,14 @@ declare module NodeJs { } version: any; } - export module PunyCode { } + export var PunyCode: PunyCode; // ---------- "repl" module ---------- - export var Repl: Repl; export interface Repl { start(options: Repl.ReplOptions): NodeEventEmitter; } + export var Repl: Repl; export module Repl { export interface ReplOptions { prompt?: string; @@ -622,10 +628,10 @@ declare module NodeJs { // ---------- "readline" module ---------- - export var ReadLine: ReadLine; export interface ReadLine { createInterface(options: ReadLine.ReadLineOptions): ReadLine.ReadLine; } + export var ReadLine: ReadLine; export module ReadLine { export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; @@ -646,7 +652,6 @@ declare module NodeJs { // ---------- "vm" module ---------- - export var Vm: Vm; export interface Vm { runInThisContext(code: string, filename?: string): void; runInNewContext(code: string, sandbox?: Vm.Context, filename?: string): void; @@ -654,6 +659,7 @@ declare module NodeJs { createContext(initSandbox?: Vm.Context): Vm.Context; createScript(code: string, filename?: string): Vm.Script; } + export var Vm: Vm; export module Vm { export interface Context { } export interface Script { @@ -664,7 +670,6 @@ declare module NodeJs { // ---------- "child_process" module ---------- - export var ChildProcess: ChildProcess; export interface ChildProcess { spawn(command: string, args?: string[], options?: { cwd?: string; @@ -700,6 +705,7 @@ declare module NodeJs { encoding?: string; }): ChildProcess.ChildProcess; } + export var ChildProcess: ChildProcess; export module ChildProcess { export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; @@ -714,12 +720,12 @@ declare module NodeJs { // ---------- "url" module ---------- - export var Url: Url; export interface Url { parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url.Url; format(url: Url.UrlOptions): string; resolve(from: string, to: string): string; } + export var Url: Url; export module Url { export interface Url { href: string; @@ -747,7 +753,6 @@ declare module NodeJs { // ---------- "dns" module ---------- - export var Dns: Dns; export interface Dns { lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; @@ -762,11 +767,10 @@ declare module NodeJs { resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } - export module Dns { } + export var Dns: Dns; // ---------- "net" module ---------- - export var Net: Net; export interface Net { Socket: new(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }) => Net.Socket; @@ -782,6 +786,7 @@ declare module NodeJs { isIPv4(input: string): boolean; isIPv6(input: string): boolean; } + export var Net: Net; export module Net { export interface Socket extends ReadWriteStream { @@ -829,10 +834,10 @@ declare module NodeJs { // ---------- "dgram" module ---------- - export var Dgram: Dgram; export interface Dgram { createSocket(type: string, callback?: Function): Dgram.Socket; } + export var Dgram: Dgram; export module Dgram { interface Socket extends NodeEventEmitter { send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; @@ -849,7 +854,6 @@ declare module NodeJs { // ---------- "fs" module ---------- - export var Fs: Fs; export interface Fs { rename(oldPath: string, newPath: string, callback?: (err?: ErrnoException) => void): void; renameSync(oldPath: string, newPath: string): void; @@ -964,6 +968,7 @@ declare module NodeJs { string?: string; }): Fs.WriteStream; } + export var Fs: Fs; export module Fs { export interface Stats { isFile(): boolean; @@ -996,7 +1001,6 @@ declare module NodeJs { // ---------- "path" module ---------- - export var Path: Path; export interface Path { normalize(p: string): string; join(...paths: any[]): string; @@ -1007,14 +1011,14 @@ declare module NodeJs { extname(p: string): string; sep: string; } - export module Path { } + export var Path: Path; // ---------- "string_decoder" module ---------- - export var StringDecoder: StringDecoder; export interface StringDecoder { StringDecoder: new(encoding: string) => StringDecoder.StringDecoder; } + export var StringDecoder: StringDecoder; export module StringDecoder { export interface StringDecoder { write(buffer: NodeBuffer): string; @@ -1024,7 +1028,6 @@ declare module NodeJs { // ---------- "tls" module ---------- - export var Tls: Tls; export interface Tls { CLIENT_RENEG_LIMIT: number; CLIENT_RENEG_WINDOW: number; @@ -1034,6 +1037,7 @@ declare module NodeJs { connect(port: number, options?: Tls.ConnectionOptions, secureConnectListener?: () =>void ): Tls.ClearTextStream; createSecurePair(credentials?: Crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): Tls.SecurePair; } + export var Tls: Tls; export module Tls { export interface TlsOptions { pfx?: any; //string or buffer @@ -1103,7 +1107,6 @@ declare module NodeJs { // ---------- "crypto" module ---------- - export var Crypto: Crypto; export interface Crypto { createCredentials(details: Crypto.CredentialDetails): Crypto.Credentials; createHash(algorithm: string): Crypto.Hash; @@ -1121,6 +1124,7 @@ declare module NodeJs { pseudoRandomBytes(size: number): NodeBuffer; pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; } + export var Crypto: Crypto; export module Crypto { export interface CredentialDetails { pfx: string; @@ -1269,7 +1273,6 @@ declare module NodeJs { // ---------- "util" module ---------- - export var Util: Util; export interface Util { format(format: any, ...param: any[]): string; debug(string: string): void; @@ -1285,6 +1288,7 @@ declare module NodeJs { isError(object: any): boolean; inherits(constructor: any, superConstructor: any): void; } + export var Util: Util; export module Util { export interface InspectOptions { showHidden?: boolean; @@ -1322,7 +1326,30 @@ declare module NodeJs { } ifError(value: any): void; } + export function Assert(value: any, message?: string): void; export module Assert { + 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 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 interface AssertionErrorOptions { message?: string; actual?: any; @@ -1343,12 +1370,12 @@ declare module NodeJs { // ---------- "tty" module ---------- - export var Tty: Tty; export interface Tty { ReadStream: new() => Tty.ReadStream; WriteStream: new() => Tty.WriteStream; isatty(fd: number): boolean; } + export var Tty: Tty; export module Tty { export interface ReadStream extends Net.Socket { isRaw: boolean; From 6a320ef21154df84894960f1a155ef733a9e04da Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 31 Mar 2014 11:10:37 +0800 Subject: [PATCH 10/13] EventEmitter can be new()d --- node/node.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index b84ef7912..25e6c45f2 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -285,8 +285,7 @@ declare module NodeJs { // ---------- "events" module ---------- export interface Events { EventEmitter: { - (): any // Correctly reflect the fact that this is a (constructor) function, - // without suggesting that instances can be obtained this way + new(): Events.EventEmitter; listenerCount(emitter: Events.EventEmitter, event: string): number; } } @@ -418,7 +417,8 @@ declare module NodeJs { emit(event: string, ...args: any[]): boolean; Worker: { - (): any // Correctly reflect the fact that this is a (constructor) function, without suggesting that instances can be obtained this way + (): any; // Correctly reflect the fact that this is a (constructor) function, + // without suggesting that instances can be obtained this way } } export module Cluster { From 69bd32f4c1cadfa49e2a223373c72c6c59a9c37c Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 31 Mar 2014 15:18:53 +0800 Subject: [PATCH 11/13] pure internal modules + external shim - The top-level modules Express and NodeJs are now 'pure' ie non-instantiated, due to removal of all vars, functions, and classes - Where the above change breaks existing typings which access types via external module references, a shim has been added to make this continue working unchanged - A single namespace _ExternalShim_ is added but this can be reused across all typings that need shimming --- express/express.d.ts | 3517 +++++++++++++++++++++--------------------- node/node.d.ts | 218 ++- 2 files changed, 1863 insertions(+), 1872 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index dc18cc58e..2f1bdeee2 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -12,1851 +12,1854 @@ /// + +/************************************************ +* * +* EXTERNAL MODULE * +* * +************************************************/ + declare module "express" { - import _ = Express.Static; - export = _; + import M = _ExternalShim_._Express_; + export = M; } + + +/************************************************ +* * +* EXTERNAL - INTERNAL SHIM * +* * +************************************************/ + +// NB: This module exists so that 'pure' (ie non-instantiated) internal modules may +// be declared in parallel with external modules, without breaking code that relies +// on certain behaviours of external modules. It's a shim to support type definitions +// that are already out there which use the pattern exemplified below: +// +// declare module "mymodule" { +// import express = require('express'); +// ... +// request?: express.Request; +// +// Note that the type 'Request' is accessed via the variable 'express', meaning that +// Request must be not just a type, but also a property on 'express'. The 'pure' typings +// declared in the Express module below don't support this usage. With the _ExternalTypes_ +// shim, the above code will continue working unchanged. New type definitions should +// prefer something like: +// +// declare module "mymodule" { +// ... +// request?: Express.Request; +// +// If all typings switch to using the pure internal types in Express, this shim can be removed. +declare module _ExternalShim_ { + export var _Express_: Express; + export module _Express_ { + export interface Request extends Express.Request { } + export interface Response extends Express.Response { } + export interface Express extends Express.Express { } + export interface Application extends Express.Application { } + } +} + + +/************************************************ +* * +* INTERNAL MODULE * +* * +************************************************/ + declare module Express { - // NB: All typings in Express.Static are exposed in dual declaration spaces - // (i.e. as 'types' and as 'members' - see TypeScript Language Spec section 2.3) - // so that type information is available in both of the following scenarios: - // - // // Normal import: - // import express = require('express'); - // var app = express(); - // app.use(express.urlencoded()); - // - // // Typed variable: - // var express: Express.Static = someExpr() // a wrapped, mocked or otherwise obtained ref - // var app = express(); - // app.use(express.urlencoded()); - export interface Static { - (): Static.Express; - Route: new (method: string, path: string, callbacks: Function[], options: any) => Static.Route; - Router: new (options?: any) => Static.Router; - bodyParser(options?: any): Static.Handler; - errorHandler(opts?: any): Static.Handler; - methodOverride(key?: string): Static.Handler; - cookieParser(secret?: string): Static.Handler; - session(options?: any): Static.Handler; - hash(sess: string): string; - static(root: string, options?: any): Static.Handler; - basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Static.Handler; - basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Static.Handler; - basicAuth(user: string, pass: string, realm?: string): Static.Handler; - compress(options?: any): Static.Handler; - cookieSession(options?: any): Static.Handler; - csrf(options?: {value?: Function}): Static.Handler; - directory(root: string, options?: any): Static.Handler; - favicon(path?: string, options?: any): Static.Handler; - json(options?: any): Static.Handler; - limit(bytes: number): Static.Handler; - limit(bytes: string): Static.Handler; - logger(options: string): Static.Handler; - logger(options: Function): Static.Handler; - logger(options?: any): Static.Handler; - compile(fmt: string): Static.Handler; - token(name: string, fn: Function): any; - format(name: string, str: string): any; - format(name: string, str: Function): any; - query(options: any): Static.Handler; - responseTime(): Static.Handler; - staticCache(options: any): Static.Handler; - timeout(ms: number): Static.Handler; - vhost(hostname: string, server: any): Static.Handler; - urlencoded(): any; - multipart(): any; + + export interface IRoute { + path: string; + + method: string; + + callbacks: Function[]; + + regexp: any; + + /** + * Check if this route matches `path`, if so + * populate `.params`. + */ + match(path: string): boolean; } - export function Static(): Static.Express; - export module Static { - interface IRoute { - path: string; + export interface Route extends IRoute { + path: string; - method: string; + method: string; - callbacks: Function[]; + callbacks: Function[]; - regexp: any; + regexp: any; + match(path: string): boolean; + } - /** - * Check if this route matches `path`, if so - * populate `.params`. + export interface IRouter { + /** + * 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 */ - match(path: string): boolean; - } + param(name: string, fn: Function): T; - class Route implements IRoute { - path: string; + param(name: string[], fn: Function): T; - method: string; + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; - callbacks: Function[]; + all(path: string, ...callbacks: Function[]): void; - regexp: any; - match(path: string): boolean; + get(name: string, ...handlers: RequestFunction[]): T; - /** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param method - * @param path - * @param callbacks - * @param options - */ - constructor (method: string, path: string, callbacks: Function[], options: any); - } + get(name: RegExp, ...handlers: RequestFunction[]): T; - interface IRouter { - /** - * 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, fn: Function): T; + post(name: string, ...handlers: RequestFunction[]): T; - param(name: string[], fn: Function): T; + post(name: RegExp, ...handlers: RequestFunction[]): T; - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): T; + put(name: string, ...handlers: RequestFunction[]): T; - all(path: string, ...callbacks: Function[]): void; + put(name: RegExp, ...handlers: RequestFunction[]): T; - get(name: string, ...handlers: RequestFunction[]): T; + del(name: string, ...handlers: RequestFunction[]): T; - get(name: RegExp, ...handlers: RequestFunction[]): T; - - post(name: string, ...handlers: RequestFunction[]): T; - - post(name: RegExp, ...handlers: RequestFunction[]): T; - - put(name: string, ...handlers: RequestFunction[]): T; - - put(name: RegExp, ...handlers: RequestFunction[]): T; - - del(name: string, ...handlers: RequestFunction[]): T; - - del(name: RegExp, ...handlers: RequestFunction[]): T; + del(name: RegExp, ...handlers: RequestFunction[]): T; - patch(name: string, ...handlers: RequestFunction[]): T; + patch(name: string, ...handlers: RequestFunction[]): T; - patch(name: RegExp, ...handlers: RequestFunction[]): T; - } + patch(name: RegExp, ...handlers: RequestFunction[]): T; + } - export class Router implements IRouter { - constructor (options?: any); + export interface Router extends IRouter { + middleware (): any; - middleware (): any; + param(name: string, fn: Function): Router; - param(name: string, fn: Function): Router; + param(name: any[], fn: Function): Router; - param(name: any[], fn: Function): Router; + all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; - all(path: string, fn?: (req: Request, res: Response, next: Function) => any): Router; + all(path: string, ...callbacks: Function[]): void; - all(path: string, ...callbacks: Function[]): void; + get(name: string, ...handlers: RequestFunction[]): Router; - get(name: string, ...handlers: RequestFunction[]): Router; + get(name: RegExp, ...handlers: RequestFunction[]): Router; - get(name: RegExp, ...handlers: RequestFunction[]): Router; + post(name: string, ...handlers: RequestFunction[]): Router; - post(name: string, ...handlers: RequestFunction[]): Router; + post(name: RegExp, ...handlers: RequestFunction[]): Router; - post(name: RegExp, ...handlers: RequestFunction[]): Router; + put(name: string, ...handlers: RequestFunction[]): Router; - put(name: string, ...handlers: RequestFunction[]): Router; + put(name: RegExp, ...handlers: RequestFunction[]): Router; - put(name: RegExp, ...handlers: RequestFunction[]): Router; + del(name: string, ...handlers: RequestFunction[]): Router; - del(name: string, ...handlers: RequestFunction[]): Router; - - del(name: RegExp, ...handlers: RequestFunction[]): Router; + del(name: RegExp, ...handlers: RequestFunction[]): Router; - patch(name: string, ...handlers: RequestFunction[]): Router; + patch(name: string, ...handlers: RequestFunction[]): Router; - patch(name: RegExp, ...handlers: RequestFunction[]): Router; - } - - export interface Handler { - (req: Request, res: Response, next?: Function): void; - } - - export interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - export interface Errback { (err: Error): void; } - - export interface Session { - /** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - touch(): Session; - - /** - * Reset `.maxAge` to `.originalMaxAge`. - */ - resetMaxAge(): Session; - - /** - * Save the session data with optional callback `fn(err)`. - */ - save(fn: Function): Session; - - /** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - */ - reload(fn: Function): Session; - - /** - * Destroy `this` session. - */ - destroy(fn: Function): Session; - - /** - * Regenerate this request's session. - */ - regenerate(fn: Function): Session; - - user: any; - - error: string; - - success: string; - - views: any; - - count: number; - } - - export interface Request { - - session: Session; - - /** - * 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: 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 basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - */ - auth: any; - - /** - * 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. - */ - 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; - - /** - * Used to generate an anti-CSRF token. - * Placed by the CSRF protection middleware. - */ - csrfToken(): string; - - 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; - } - - export interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - export interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - export interface Response extends NodeJs.Http.ServerResponse { - /** - * Set status `code`. - * - * @param code - */ - status(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 - * - `root` root directory for relative filenames - * - * 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.'); - * } - * }); - * }); - */ - sendfile(path: string): void; - - sendfile(path: string, options: any): void; - - sendfile(path: string, fn: Errback): void; - - 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; - - /** - * 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; - } - - export interface RequestFunction { - (req: Request, res: Response, next: Function): any; - } - - export interface Application extends IRouter { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Proxy `connect#use()` to apply settings to - * mounted applications. - **/ - use(route: string, callback?: Function): Application; - - use(route: string, server: Application): Application; - - use(callback: Function): Application; - - use(server: Application): Application; - - /** - * 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; - - param(name: string, fn: Function): Application; - - param(name: string[], fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set (setting: string, val: string): 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(env: 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; - - configure(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): void; - - listen(port: number, hostname: string, callback?: Function): void; - - listen(port: number, callback?: Function): void; - - listen(path: string, callback?: Function): void; - - listen(handle: any, listeningListener?: Function): void; - - route: Route; - - 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; - } - - export interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. + patch(name: RegExp, ...handlers: RequestFunction[]): Router; + } + + export interface Handler { + (req: Request, res: Response, next?: Function): void; + } + + export interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + export interface Errback { (err: Error): void; } + + export interface Session { + /** + * Update reset `.cookie.maxAge` to prevent + * the cookie from expiring when the + * session is still active. + * + * @return {Session} for chaining + * @api public */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } + touch(): Session; /** - * Body parser: - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * @param options - */ - export function bodyParser(options?: any): Handler; + * Reset `.maxAge` to `.originalMaxAge`. + */ + resetMaxAge(): Session; /** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - */ - export function errorHandler(opts?: any): Handler; + * Save the session data with optional callback `fn(err)`. + */ + save(fn: Function): Session; /** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, othewise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param key - */ - export function methodOverride(key?: string): Handler; + * Re-loads the session data _without_ altering + * the maxAge properties. Invokes the callback `fn(err)`, + * after which time if no exception has occurred the + * `req.session` property will be a new `Session` object, + * although representing the same session. + */ + reload(fn: Function): Session; /** - * Cookie parser: - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param secret - */ - export function cookieParser(secret?: string): Handler; + * Destroy `this` session. + */ + destroy(fn: Function): Session; /** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

views: ' + sess.views + '

'); - * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param options - */ - export function session(options?: any): Handler; + * Regenerate this request's session. + */ + regenerate(fn: Function): Session; + + user: any; + + error: string; + + success: string; + + views: any; + + count: number; + } + + export interface Request { + + session: Session; /** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param sess - */ - export function hash(sess: string): string; + * 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: string[]; /** - * 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 - */ - export function static(root: string, options?: any): Handler; + * 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; /** - * Basic Auth: - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user & 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param callback or username - * @param realm - */ - export function basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Handler; - - export function basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Handler; - - export function basicAuth(user: string, pass: string, realm?: string): Handler; + * Check if the given `charset` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param charset + */ + acceptsCharset(charset: string): boolean; /** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param options - */ - export function compress(options?: any): Handler; + * Check if the given `lang` is acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param lang + */ + acceptsLanguage(lang: string): boolean; /** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * @param options - */ - export function cookieSession(options?: any): Handler; + * 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[]; /** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param options - */ - export function csrf(options?: {value?: Function}): Handler; + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; /** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param root - * @param options - */ - export function directory(root: string, options?: any): Handler; + * 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[]; /** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico)) - * - * @param path - * @param options - */ - export function favicon(path?: string, options?: any): Handler; + * 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[]; /** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit disabled by default - * - * @param options - */ - export function json(options?: any): Handler; + * 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; /** - * Limit: - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - */ - export function limit(bytes: number): Handler; - - export function limit(bytes: string): Handler; + * 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; /** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - */ - export function logger(options: string): Handler; - - export function logger(options: Function): Handler; - - export function logger(options?: any): Handler; + * 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; /** - * Compile `fmt` into a function. - * - * @param fmt - */ - export function compile(fmt: string): Handler; + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; /** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param name - * @param fn - */ - export function token(name: string, fn: Function): any; + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; /** - * Define a `fmt` with the given `name`. - */ - export function format(name: string, str: string): any; - - export function format(name: string, str: Function): any; + * 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[]; /** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object. - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - */ - export function query(options: any): Handler; + * Return basic auth credentials. + * + * Examples: + * + * // http://tobi:hello@example.com + * req.auth + * // => { username: 'tobi', password: 'hello' } + */ + auth: any; /** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - */ - export function responseTime(): Handler; + * 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[]; /** - * Static cache: - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - */ - export function staticCache(options: any): Handler; + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; /** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 408`. - */ - export function timeout(ms: number): Handler; + * Parse the "Host" header field hostname. + */ + host: string; /** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param hostname - * @param server - */ - export function vhost(hostname: string, server: any): Handler; + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; - export function urlencoded(): any; + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; - export function multipart(): any; + /** + * 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; + + /** + * Used to generate an anti-CSRF token. + * Placed by the CSRF protection middleware. + */ + csrfToken(): string; + + 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; + } + + export interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + export interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + export interface Response extends NodeJs.Http.ServerResponse { + /** + * Set status `code`. + * + * @param code + */ + status(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 + * - `root` root directory for relative filenames + * + * 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.'); + * } + * }); + * }); + */ + sendfile(path: string): void; + + sendfile(path: string, options: any): void; + + sendfile(path: string, fn: Errback): void; + + 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; + + /** + * 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; + } + + export interface RequestFunction { + (req: Request, res: Response, next: Function): any; + } + + export interface Application extends IRouter { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Proxy `connect#use()` to apply settings to + * mounted applications. + **/ + use(route: string, callback?: Function): Application; + + use(route: string, server: Application): Application; + + use(callback: Function): Application; + + use(server: Application): Application; + + /** + * 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; + + param(name: string, fn: Function): Application; + + param(name: string[], fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set (setting: string, val: string): 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(env: 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; + + configure(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): void; + + listen(port: number, hostname: string, callback?: Function): void; + + listen(port: number, callback?: Function): void; + + listen(path: string, callback?: Function): void; + + listen(handle: any, listeningListener?: Function): void; + + route: Route; + + 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; + } + + export 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; } } +interface Express { + (): Express.Express; + + /** + * Initialize `Route` with the given HTTP `method`, `path`, + * and an array of `callbacks` and `options`. + * + * Options: + * + * - `sensitive` enable case-sensitive routes + * - `strict` enable strict matching for trailing slashes + * + * @param method + * @param path + * @param callbacks + * @param options + */ + Route: new (method: string, path: string, callbacks: Function[], options: any) => Express.Route; + + Router: new (options?: any) => Express.Router; + + /** + * Body parser: + * + * Parse request bodies, supports _application/json_, + * _application/x-www-form-urlencoded_, and _multipart/form-data_. + * + * This is equivalent to: + * + * app.use(connect.json()); + * app.use(connect.urlencoded()); + * app.use(connect.multipart()); + * + * Examples: + * + * connect() + * .use(connect.bodyParser()) + * .use(function(req, res) { + * res.end('viewing user ' + req.body.user.name); + * }); + * + * $ curl -d 'user[name]=tj' http://local/ + * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ + * + * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. + * + * @param options + */ + bodyParser(options?: any): Express.Handler; + + /** + * Error handler: + * + * Development error handler, providing stack traces + * and error message responses for requests accepting text, html, + * or json. + * + * Text: + * + * By default, and when _text/plain_ is accepted a simple stack trace + * or error message will be returned. + * + * JSON: + * + * When _application/json_ is accepted, connect will respond with + * an object in the form of `{ "error": error }`. + * + * HTML: + * + * When accepted connect will output a nice html stack trace. + */ + errorHandler(opts?: any): Express.Handler; + + /** + * Method Override: + * + * Provides faux HTTP method support. + * + * Pass an optional `key` to use when checking for + * a method override, othewise defaults to _\_method_. + * The original method is available via `req.originalMethod`. + * + * @param key + */ + methodOverride(key?: string): Express.Handler; + + /** + * Cookie parser: + * + * Parse _Cookie_ header and populate `req.cookies` + * with an object keyed by the cookie names. Optionally + * you may enabled signed cookie support by passing + * a `secret` string, which assigns `req.secret` so + * it may be used by other middleware. + * + * Examples: + * + * connect() + * .use(connect.cookieParser('optional secret string')) + * .use(function(req, res, next){ + * res.end(JSON.stringify(req.cookies)); + * }) + * + * @param secret + */ + cookieParser(secret?: string): Express.Handler; + + /** + * Session: + * + * Setup session store with the given `options`. + * + * Session data is _not_ saved in the cookie itself, however + * cookies are used, so we must use the [cookieParser()](cookieParser.html) + * middleware _before_ `session()`. + * + * Examples: + * + * connect() + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) + * + * Options: + * + * - `key` cookie name defaulting to `connect.sid` + * - `store` session store instance + * - `secret` session cookie is signed with this secret to prevent tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Cookie option: + * + * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set + * so the cookie becomes a browser-session cookie. When the user closes the + * browser the cookie (and session) will be removed. + * + * ## req.session + * + * To store or access session data, simply use the request property `req.session`, + * which is (generally) serialized as JSON by the store, so nested objects + * are typically fine. For example below is a user-specific view counter: + * + * connect() + * .use(connect.favicon()) + * .use(connect.cookieParser()) + * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) + * .use(function(req, res, next){ + * var sess = req.session; + * if (sess.views) { + * res.setHeader('Content-Type', 'text/html'); + * res.write('

views: ' + sess.views + '

'); + * res.write('

expires in: ' + (sess.cookie.maxAge / 1000) + 's

'); + * res.end(); + * sess.views++; + * } else { + * sess.views = 1; + * res.end('welcome to the session demo. refresh!'); + * } + * } + * )).listen(3000); + * + * ## Session#regenerate() + * + * To regenerate the session simply invoke the method, once complete + * a new SID and `Session` instance will be initialized at `req.session`. + * + * req.session.regenerate(function(err){ + * // will have a new session here + * }); + * + * ## Session#destroy() + * + * Destroys the session, removing `req.session`, will be re-generated next request. + * + * req.session.destroy(function(err){ + * // cannot access session here + * }); + * + * ## Session#reload() + * + * Reloads the session data. + * + * req.session.reload(function(err){ + * // session updated + * }); + * + * ## Session#save() + * + * Save the session. + * + * req.session.save(function(err){ + * // session saved + * }); + * + * ## Session#touch() + * + * Updates the `.maxAge` property. Typically this is + * not necessary to call, as the session middleware does this for you. + * + * ## Session#cookie + * + * Each session has a unique cookie object accompany it. This allows + * you to alter the session cookie per visitor. For example we can + * set `req.session.cookie.expires` to `false` to enable the cookie + * to remain for only the duration of the user-agent. + * + * ## Session#maxAge + * + * Alternatively `req.session.cookie.maxAge` will return the time + * remaining in milliseconds, which we may also re-assign a new value + * to adjust the `.expires` property appropriately. The following + * are essentially equivalent + * + * var hour = 3600000; + * req.session.cookie.expires = new Date(Date.now() + hour); + * req.session.cookie.maxAge = hour; + * + * For example when `maxAge` is set to `60000` (one minute), and 30 seconds + * has elapsed it will return `30000` until the current request has completed, + * at which time `req.session.touch()` is called to reset `req.session.maxAge` + * to its original value. + * + * req.session.cookie.maxAge; + * // => 30000 + * + * Session Store Implementation: + * + * Every session store _must_ implement the following methods + * + * - `.get(sid, callback)` + * - `.set(sid, session, callback)` + * - `.destroy(sid, callback)` + * + * Recommended methods include, but are not limited to: + * + * - `.length(callback)` + * - `.clear(callback)` + * + * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. + * + * @param options + */ + session(options?: any): Express.Handler; + + /** + * Hash the given `sess` object omitting changes + * to `.cookie`. + * + * @param sess + */ + hash(sess: string): string; + + /** + * 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 + */ + static(root: string, options?: any): Express.Handler; + + /** + * Basic Auth: + * + * Enfore basic authentication by providing a `callback(user, pass)`, + * which must return `true` in order to gain access. Alternatively an async + * method is provided as well, invoking `callback(user, pass, callback)`. Populates + * `req.user`. The final alternative is simply passing username / password + * strings. + * + * Simple username and password + * + * connect(connect.basicAuth('username', 'password')); + * + * Callback verification + * + * connect() + * .use(connect.basicAuth(function(user, pass){ + * return 'tj' == user & 'wahoo' == pass; + * })) + * + * Async callback verification, accepting `fn(err, user)`. + * + * connect() + * .use(connect.basicAuth(function(user, pass, fn){ + * User.authenticate({ user: user, pass: pass }, fn); + * })) + * + * @param callback or username + * @param realm + */ + basicAuth(callback: (user: string, pass: string, fn : Function) => void, realm?: string): Express.Handler; + + basicAuth(callback: (user: string, pass: string) => boolean, realm?: string): Express.Handler; + + basicAuth(user: string, pass: string, realm?: string): Express.Handler; + + /** + * Compress: + * + * Compress response data with gzip/deflate. + * + * Filter: + * + * A `filter` callback function may be passed to + * replace the default logic of: + * + * exports.filter = function(req, res){ + * return /json|text|javascript/.test(res.getHeader('Content-Type')); + * }; + * + * Options: + * + * All remaining options are passed to the gzip/deflate + * creation functions. Consult node's docs for additional details. + * + * - `chunkSize` (default: 16*1024) + * - `windowBits` + * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression + * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more + * - `strategy`: compression strategy + * + * @param options + */ + compress(options?: any): Express.Handler; + + /** + * Cookie Session: + * + * Cookie session middleware. + * + * var app = connect(); + * app.use(connect.cookieParser()); + * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); + * + * Options: + * + * - `key` cookie name defaulting to `connect.sess` + * - `secret` prevents cookie tampering + * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` + * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") + * + * Clearing sessions: + * + * To clear the session simply set its value to `null`, + * `cookieSession()` will then respond with a 1970 Set-Cookie. + * + * req.session = null; + * + * @param options + */ + cookieSession(options?: any): Express.Handler; + + /** + * Anti CSRF: + * + * CSRF protection middleware. + * + * This middleware adds a `req.csrfToken()` function to make a token + * which should be added to requests which mutate + * state, within a hidden form field, query-string etc. This + * token is validated against the visitor's session. + * + * The default `value` function checks `req.body` generated + * by the `bodyParser()` middleware, `req.query` generated + * by `query()`, and the "X-CSRF-Token" header field. + * + * This middleware requires session support, thus should be added + * somewhere _below_ `session()` and `cookieParser()`. + * + * Options: + * + * - `value` a function accepting the request, returning the token + * + * @param options + */ + csrf(options?: {value?: Function}): Express.Handler; + + /** + * Directory: + * + * Serve directory listings with the given `root` path. + * + * Options: + * + * - `hidden` display hidden (dot) files. Defaults to false. + * - `icons` display icons. Defaults to false. + * - `filter` Apply this filter function to files. Defaults to false. + * + * @param root + * @param options + */ + directory(root: string, options?: any): Express.Handler; + + /** + * Favicon: + * + * By default serves the connect favicon, or the favicon + * located by the given `path`. + * + * Options: + * + * - `maxAge` cache-control max-age directive, defaulting to 1 day + * + * Examples: + * + * Serve default favicon: + * + * connect() + * .use(connect.favicon()) + * + * Serve favicon before logging for brevity: + * + * connect() + * .use(connect.favicon()) + * .use(connect.logger('dev')) + * + * Serve custom favicon: + * + * connect() + * .use(connect.favicon('public/favicon.ico)) + * + * @param path + * @param options + */ + favicon(path?: string, options?: any): Express.Handler; + + /** + * JSON: + * + * Parse JSON request bodies, providing the + * parsed object as `req.body`. + * + * Options: + * + * - `strict` when `false` anything `JSON.parse()` accepts will be parsed + * - `reviver` used as the second "reviver" argument for JSON.parse + * - `limit` byte limit disabled by default + * + * @param options + */ + json(options?: any): Express.Handler; + + /** + * Limit: + * + * Limit request bodies to the given size in `bytes`. + * + * A string representation of the bytesize may also be passed, + * for example "5mb", "200kb", "1gb", etc. + * + * connect() + * .use(connect.limit('5.5mb')) + * .use(handleImageUpload) + */ + limit(bytes: number): Express.Handler; + + limit(bytes: string): Express.Handler; + + /** + * Logger: + * + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `stream` Output stream, defaults to _stdout_ + * - `buffer` Buffer duration, defaults to 1000ms when _true_ + * - `immediate` Write log line on request instead of response (for response times) + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * Formats: + * + * Pre-defined formats that ship with connect: + * + * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' + * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' + * - `tiny` ':method :url :status :res[content-length] - :response-time ms' + * - `dev` concise output colored by response status for development use + * + * Examples: + * + * connect.logger() // default + * connect.logger('short') + * connect.logger('tiny') + * connect.logger({ immediate: true, format: 'dev' }) + * connect.logger(':method :url - :referrer') + * connect.logger(':req[content-type] -> :res[content-type]') + * connect.logger(function(tokens, req, res){ return 'some format string' }) + * + * Defining Tokens: + * + * To define a token, simply invoke `connect.logger.token()` with the + * name and a callback function. The value returned is then available + * as ":type" in this case. + * + * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) + * + * Defining Formats: + * + * All default formats are defined this way, however it's public API as well: + * + * connect.logger.format('name', 'string or function') + */ + logger(options: string): Express.Handler; + + logger(options: Function): Express.Handler; + + logger(options?: any): Express.Handler; + + /** + * Compile `fmt` into a function. + * + * @param fmt + */ + compile(fmt: string): Express.Handler; + + /** + * Define a token function with the given `name`, + * and callback `fn(req, res)`. + * + * @param name + * @param fn + */ + token(name: string, fn: Function): any; + + /** + * Define a `fmt` with the given `name`. + */ + format(name: string, str: string): any; + + format(name: string, str: Function): any; + + /** + * Query: + * + * Automatically parse the query-string when available, + * populating the `req.query` object. + * + * Examples: + * + * connect() + * .use(connect.query()) + * .use(function(req, res){ + * res.end(JSON.stringify(req.query)); + * }); + * + * The `options` passed are provided to qs.parse function. + */ + query(options: any): Express.Handler; + + /** + * Reponse time: + * + * Adds the `X-Response-Time` header displaying the response + * duration in milliseconds. + */ + responseTime(): Express.Handler; + + /** + * Static cache: + * + * Enables a memory cache layer on top of + * the `static()` middleware, serving popular + * static files. + * + * By default a maximum of 128 objects are + * held in cache, with a max of 256k each, + * totalling ~32mb. + * + * A Least-Recently-Used (LRU) cache algo + * is implemented through the `Cache` object, + * simply rotating cache objects as they are + * hit. This means that increasingly popular + * objects maintain their positions while + * others get shoved out of the stack and + * garbage collected. + * + * Benchmarks: + * + * static(): 2700 rps + * node-static: 5300 rps + * static() + staticCache(): 7500 rps + * + * Options: + * + * - `maxObjects` max cache objects [128] + * - `maxLength` max cache object length 256kb + */ + staticCache(options: any): Express.Handler; + + /** + * Timeout: + * + * Times out the request in `ms`, defaulting to `5000`. The + * method `req.clearTimeout()` is added to revert this behaviour + * programmatically within your application's middleware, routes, etc. + * + * The timeout error is passed to `next()` so that you may customize + * the response behaviour. This error has the `.timeout` property as + * well as `.status == 408`. + */ + timeout(ms: number): Express.Handler; + + /** + * Vhost: + * + * Setup vhost for the given `hostname` and `server`. + * + * connect() + * .use(connect.vhost('foo.com', fooApp)) + * .use(connect.vhost('bar.com', barApp)) + * .use(connect.vhost('*.com', mainApp)) + * + * The `server` may be a Connect server or + * a regular Node `http.Server`. + * + * @param hostname + * @param server + */ + vhost(hostname: string, server: any): Express.Handler; + + urlencoded(): any; + + multipart(): any; +} diff --git a/node/node.d.ts b/node/node.d.ts index 25e6c45f2..bb70b7d01 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -219,38 +219,106 @@ interface NodeTimer { unref() : void; } + /************************************************ * * * MODULES - EXTERNAL * * * ************************************************/ -declare module "querystring" { import _ = NodeJs.QueryString; export = _; } -declare module "events" { import _ = NodeJs.Events; export = _; } -declare module "http" { import _ = NodeJs.Http; export = _; } -declare module "cluster" { import _ = NodeJs.Cluster; export = _; } -declare module "zlib" { import _ = NodeJs.Zlib; export = _; } -declare module "os" { import _ = NodeJs.Os; export = _; } -declare module "https" { import _ = NodeJs.Https; export = _; } -declare module "punycode" { import _ = NodeJs.PunyCode; export = _; } -declare module "repl" { import _ = NodeJs.Repl; export = _; } -declare module "readline" { import _ = NodeJs.ReadLine; export = _; } -declare module "vm" { import _ = NodeJs.Vm; export = _; } -declare module "child_process" { import _ = NodeJs.ChildProcess; export = _; } -declare module "url" { import _ = NodeJs.Url; export = _; } -declare module "dns" { import _ = NodeJs.Dns; export = _; } -declare module "net" { import _ = NodeJs.Net; export = _; } -declare module "dgram" { import _ = NodeJs.Dgram; export = _; } -declare module "fs" { import _ = NodeJs.Fs; export = _; } -declare module "path" { import _ = NodeJs.Path; export = _; } -declare module "string_decoder" { import _ = NodeJs.StringDecoder; export = _; } -declare module "tls" { import _ = NodeJs.Tls; export = _; } -declare module "crypto" { import _ = NodeJs.Crypto; export = _; } -declare module "stream" { import _ = NodeJs.Stream; export = _; } -declare module "util" { import _ = NodeJs.Util; export = _; } -declare module "assert" { import _ = NodeJs.Assert; export = _; } -declare module "tty" { import _ = NodeJs.Tty; export = _; } -declare module "domain" { import _ = NodeJs.Domain; export = _; } +declare module "events" { import M = _ExternalShim_._NodeJs_.Events; export = M; } +declare module "http" { import M = _ExternalShim_._NodeJs_.Http; export = M; } +declare module "url" { import M = _ExternalShim_._NodeJs_.Url; export = M; } +declare module "net" { import M = _ExternalShim_._NodeJs_.Net; export = M; } +declare module "querystring" { var M: NodeJs.QueryString; export = M; } +declare module "cluster" { var M: NodeJs.Cluster; export = M; } +declare module "zlib" { var M: NodeJs.Zlib; export = M; } +declare module "os" { var M: NodeJs.Os; export = M; } +declare module "https" { var M: NodeJs.Https; export = M; } +declare module "punycode" { var M: NodeJs.PunyCode; export = M; } +declare module "repl" { var M: NodeJs.Repl; export = M; } +declare module "readline" { var M: NodeJs.ReadLine; export = M; } +declare module "vm" { var M: NodeJs.Vm; export = M; } +declare module "child_process" { var M: NodeJs.ChildProcess; export = M; } +declare module "dns" { var M: NodeJs.Dns; export = M; } +declare module "dgram" { var M: NodeJs.Dgram; export = M; } +declare module "fs" { var M: NodeJs.Fs; export = M; } +declare module "path" { var M: NodeJs.Path; export = M; } +declare module "string_decoder" { var M: NodeJs.StringDecoder; export = M; } +declare module "tls" { var M: NodeJs.Tls; export = M; } +declare module "crypto" { var M: NodeJs.Crypto; export = M; } +declare module "stream" { var M: NodeJs.Stream; export = M; } +declare module "util" { var M: NodeJs.Util; export = M; } +declare module "assert" { var M: NodeJs.Assert; export = M; } +declare module "tty" { var M: NodeJs.Tty; export = M; } +declare module "domain" { var M: NodeJs.Domain; export = M; } + + +/************************************************ +* * +* EXTERNAL - INTERNAL SHIM * +* * +************************************************/ + +// NB: This module exists so that 'pure' (ie non-instantiated) internal modules may +// be declared in parallel with external modules, without breaking code that relies +// on certain behaviours of external modules. It's a shim to support type definitions +// that are already out there which use the pattern exemplified below: +// +// declare module "mymodule" { +// import http = require('http'); +// ... +// server?: http.Server; +// +// Note that the type 'Server' is accessed via the variable 'http', meaning that +// Server must be not just a type, but also a property on 'http'. The 'pure' typings +// declared in the NodeJs module below don't support this usage. With the _ExternalTypes_ +// shim, the above code will continue working unchanged. New type definitions should +// prefer something like: +// +// declare module "mymodule" { +// ... +// server?: NodeJs.Http.Server; +// +// If all typings switch to using the pure internal types in NodeJs, this shim can be removed. + +declare module _ExternalShim_ { + export module _NodeJs_ { + export module Events { + export class EventEmitter implements NodeEventEmitter { + 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; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + } + export var Http: NodeJs.Http; + export module Http { + export interface Server extends NodeJs.Http.Server { } + export interface ServerRequest extends NodeJs.Http.ServerRequest { } + export interface ServerResponse extends NodeJs.Http.ServerResponse { } + export interface ClientRequest extends NodeJs.Http.ClientRequest { } + export interface ClientResponse extends NodeJs.Http.ClientResponse { } + export interface Agent extends NodeJs.Http.Agent { } + } + export var Net: NodeJs.Net; + export module Net { + export interface Socket extends NodeJs.Net.Socket { } + export interface Server extends NodeJs.Net.Server { } + } + export var Url: NodeJs.Url; + export module Url { + export interface Url extends NodeJs.Url.Url { } + export interface UrlOptions extends NodeJs.Url.UrlOptions { } + } + } +} + /************************************************ * * @@ -259,17 +327,6 @@ declare module "domain" { import _ = NodeJs.Domain; export = _; ************************************************/ declare module NodeJs { - // NB: All typings in this namespace are exposed in dual declaration spaces - // (i.e. as 'types' and as 'members' - see TypeScript Language Spec section 2.3) - // so that type information is available in both of the following scenarios: - // - // // Normal import: - // import http = require('http'); - // http.createServer((req, res) => {...}) - // - // // Typed variable: - // var http: NodeJs.Http = someExpr() // a wrapped, mocked or otherwise obtained ref - // http.createServer((req, res) => {...}) // ---------- "querystring" module ---------- @@ -279,7 +336,6 @@ declare module NodeJs { escape(): any; unescape(): any; } - export var QueryString: QueryString; // ---------- "events" module ---------- @@ -290,8 +346,7 @@ declare module NodeJs { } } export module Events { - export class EventEmitter implements NodeEventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; + export interface EventEmitter extends NodeEventEmitter { addListener(event: string, listener: Function): EventEmitter; on(event: string, listener: Function): EventEmitter; once(event: string, listener: Function): EventEmitter; @@ -313,7 +368,6 @@ declare module NodeJs { get(options: any, callback?: Function): Http.ClientRequest; globalAgent: Http.Agent; } - export var Http: Http; export module Http { export interface Server extends NodeEventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): void; @@ -422,31 +476,12 @@ declare module NodeJs { } } export module Cluster { - export var settings: Cluster.ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: Cluster.ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): 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; - export interface ClusterSettings { exec?: string; args?: string[]; silent?: boolean; } - export class Worker extends Events.EventEmitter { + export interface Worker extends Events.EventEmitter { id: string; process: ChildProcess.ChildProcess; suicide: boolean; @@ -509,7 +544,6 @@ declare module NodeJs { Z_DEFLATED: number; Z_NULL: number; } - export var Zlib: Zlib; export module Zlib { export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends ReadWriteStream { } @@ -538,7 +572,6 @@ declare module NodeJs { networkInterfaces(): any; EOL: string; } - export var Os: Os; // ---------- "https" module ---------- @@ -550,7 +583,6 @@ declare module NodeJs { get(options: Https.RequestOptions, callback?: (res: NodeEventEmitter) => void): Http.ClientRequest; globalAgent: Https.Agent; } - export var Https: Https; export module Https { export interface ServerOptions { pfx?: any; @@ -604,14 +636,12 @@ declare module NodeJs { } version: any; } - export var PunyCode: PunyCode; // ---------- "repl" module ---------- export interface Repl { start(options: Repl.ReplOptions): NodeEventEmitter; } - export var Repl: Repl; export module Repl { export interface ReplOptions { prompt?: string; @@ -631,7 +661,6 @@ declare module NodeJs { export interface ReadLine { createInterface(options: ReadLine.ReadLineOptions): ReadLine.ReadLine; } - export var ReadLine: ReadLine; export module ReadLine { export interface ReadLine extends NodeEventEmitter { setPrompt(prompt: string, length: number): void; @@ -659,7 +688,6 @@ declare module NodeJs { createContext(initSandbox?: Vm.Context): Vm.Context; createScript(code: string, filename?: string): Vm.Script; } - export var Vm: Vm; export module Vm { export interface Context { } export interface Script { @@ -705,7 +733,6 @@ declare module NodeJs { encoding?: string; }): ChildProcess.ChildProcess; } - export var ChildProcess: ChildProcess; export module ChildProcess { export interface ChildProcess extends NodeEventEmitter { stdin: WritableStream; @@ -725,7 +752,6 @@ declare module NodeJs { format(url: Url.UrlOptions): string; resolve(from: string, to: string): string; } - export var Url: Url; export module Url { export interface Url { href: string; @@ -767,7 +793,6 @@ declare module NodeJs { resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } - export var Dns: Dns; // ---------- "net" module ---------- @@ -786,7 +811,6 @@ declare module NodeJs { isIPv4(input: string): boolean; isIPv6(input: string): boolean; } - export var Net: Net; export module Net { export interface Socket extends ReadWriteStream { @@ -837,7 +861,6 @@ declare module NodeJs { export interface Dgram { createSocket(type: string, callback?: Function): Dgram.Socket; } - export var Dgram: Dgram; export module Dgram { interface Socket extends NodeEventEmitter { send(buf: NodeBuffer, offset: number, length: number, port: number, address: string, callback?: Function): void; @@ -968,7 +991,6 @@ declare module NodeJs { string?: string; }): Fs.WriteStream; } - export var Fs: Fs; export module Fs { export interface Stats { isFile(): boolean; @@ -1011,14 +1033,12 @@ declare module NodeJs { extname(p: string): string; sep: string; } - export var Path: Path; // ---------- "string_decoder" module ---------- export interface StringDecoder { StringDecoder: new(encoding: string) => StringDecoder.StringDecoder; } - export var StringDecoder: StringDecoder; export module StringDecoder { export interface StringDecoder { write(buffer: NodeBuffer): string; @@ -1037,7 +1057,6 @@ declare module NodeJs { connect(port: number, options?: Tls.ConnectionOptions, secureConnectListener?: () =>void ): Tls.ClearTextStream; createSecurePair(credentials?: Crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): Tls.SecurePair; } - export var Tls: Tls; export module Tls { export interface TlsOptions { pfx?: any; //string or buffer @@ -1124,7 +1143,6 @@ declare module NodeJs { pseudoRandomBytes(size: number): NodeBuffer; pseudoRandomBytes(size: number, callback: (err: Error, buf: NodeBuffer) =>void ): void; } - export var Crypto: Crypto; export module Crypto { export interface CredentialDetails { pfx: string; @@ -1190,8 +1208,7 @@ declare module NodeJs { encoding?: string; objectMode?: boolean; } - export class Readable extends Events.EventEmitter implements ReadableStream { - constructor(opts?: ReadableOptions); + export interface Readable extends Events.EventEmitter, ReadableStream { readable: boolean; _read(size: number): void; read(size?: number): any; @@ -1209,8 +1226,7 @@ declare module NodeJs { highWaterMark?: number; decodeStrings?: boolean; } - export class Writable extends Events.EventEmitter implements WritableStream { - constructor(opts?: WritableOptions); + export interface Writable extends Events.EventEmitter, WritableStream { writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1227,8 +1243,7 @@ declare module NodeJs { } // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements ReadWriteStream { - constructor(opts?: DuplexOptions); + export interface Duplex extends Readable, ReadWriteStream { writable: boolean; _write(data: NodeBuffer, encoding: string, callback: Function): void; _write(data: string, encoding: string, callback: Function): void; @@ -1243,8 +1258,7 @@ declare module NodeJs { export interface TransformOptions extends ReadableOptions, WritableOptions {} // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends Events.EventEmitter implements ReadWriteStream { - constructor(opts?: TransformOptions); + export interface Transform extends Events.EventEmitter, ReadWriteStream { readable: boolean; writable: boolean; _transform(chunk: NodeBuffer, encoding: string, callback: Function): void; @@ -1268,7 +1282,7 @@ declare module NodeJs { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; } - export class PassThrough extends Transform {} + export interface PassThrough extends Transform {} } @@ -1288,7 +1302,6 @@ declare module NodeJs { isError(object: any): boolean; inherits(constructor: any, superConstructor: any): void; } - export var Util: Util; export module Util { export interface InspectOptions { showHidden?: boolean; @@ -1326,30 +1339,7 @@ declare module NodeJs { } ifError(value: any): void; } - export function Assert(value: any, message?: string): void; export module Assert { - 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 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 interface AssertionErrorOptions { message?: string; actual?: any; @@ -1357,8 +1347,7 @@ declare module NodeJs { operator?: string; stackStartFunction?: Function } - export class AssertionError implements Error { - constructor(options?: AssertionErrorOptions); + export interface AssertionError extends Error { name: string; message: string; actual: any; @@ -1375,7 +1364,6 @@ declare module NodeJs { WriteStream: new() => Tty.WriteStream; isatty(fd: number): boolean; } - export var Tty: Tty; export module Tty { export interface ReadStream extends Net.Socket { isRaw: boolean; @@ -1394,7 +1382,7 @@ declare module NodeJs { create(): Domain.Domain; } export module Domain { - export class Domain extends Events.EventEmitter { + export interface Domain extends Events.EventEmitter { run(fn: Function): void; add(emitter: NodeEventEmitter): void; remove(emitter: NodeEventEmitter): void; From daa12d74b1c2f4e711500fcdd8943726a928cf85 Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 31 Mar 2014 16:04:21 +0800 Subject: [PATCH 12/13] Re-added get(string):string to express --- express/express.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/express/express.d.ts b/express/express.d.ts index 2f1bdeee2..674975da8 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -143,6 +143,8 @@ declare module Express { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): T; get(name: RegExp, ...handlers: RequestFunction[]): T; @@ -175,6 +177,8 @@ declare module Express { all(path: string, ...callbacks: Function[]): void; + get(name: string): string; + get(name: string, ...handlers: RequestFunction[]): Router; get(name: RegExp, ...handlers: RequestFunction[]): Router; From 4e315942f51e8156a6d141b16d4e030286943333 Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 31 Mar 2014 16:37:41 +0800 Subject: [PATCH 13/13] Moved get(string)=>sting to Application --- express/express.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/express/express.d.ts b/express/express.d.ts index 674975da8..d5fbbdaac 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -143,8 +143,6 @@ declare module Express { all(path: string, ...callbacks: Function[]): void; - get(name: string): string; - get(name: string, ...handlers: RequestFunction[]): T; get(name: RegExp, ...handlers: RequestFunction[]): T; @@ -177,8 +175,6 @@ declare module Express { all(path: string, ...callbacks: Function[]): void; - get(name: string): string; - get(name: string, ...handlers: RequestFunction[]): Router; get(name: RegExp, ...handlers: RequestFunction[]): Router; @@ -1006,6 +1002,12 @@ declare module Express { */ set (setting: string, val: string): Application; + get(name: string): string; + + get(name: string, ...handlers: RequestFunction[]): Application; + + get(name: RegExp, ...handlers: RequestFunction[]): Application; + /** * Return the app's absolute pathname * based on the parent(s) that have