// Generated by typings
// Source: https://raw.githubusercontent.com/types/env-node/088b6275167df0e4bec9bee3205c703253ef4ace/6.0/node.d.ts
interface NodeError {
  /**
   * Returns a string describing the point in the code at which the Error was instantiated.
   *
   * For example:
   *
   * ```
   * Error: Things keep happening!
   *    at /home/gbusey/file.js:525:2
   *    at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
   *    at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
   *    at increaseSynergy (/home/gbusey/actors.js:701:6)
   * ```
   *
   * The first line is formatted as <error class name>: <error message>, and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses.
   */
  stack?: string;

  /**
   * Returns the string description of error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace.
   *
   * ```
   * const err = new Error('The message');
   * console.log(err.message);
   * // Prints: The message
   * ```
   */
  message: string;
}

interface Error extends NodeError { }

interface ErrorConstructor {
  /**
   * Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()`` was called.
   *
   * ```js
   * const myObject = {};
   * Error.captureStackTrace(myObject);
   * myObject.stack  // similar to `new Error().stack`
   * ```
   *
   * The first line of the trace, instead of being prefixed with `ErrorType : message`, will be the result of calling `targetObject.toString()``.
   *
   * The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.
   *
   * The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance:
   *
   * ```js
   * function MyError() {
   *   Error.captureStackTrace(this, MyError);
   * }
   *
   * // Without passing MyError to captureStackTrace, the MyError
   * // frame would should up in the .stack property. by passing
   * // the constructor, we omit that frame and all frames above it.
   * new MyError().stack
   * ```
   */
  captureStackTrace<T extends { stack?: string }>(targetObject: T, constructorOpt?: new () => T): void;

  /**
   * The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj))``.
   *
   * The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.
   *
   * If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
   */
  stackTraceLimit: number;
}

// ES2015 collection types
interface NodeCollection {
  size: number;
}

interface NodeWeakCollection {}

interface IterableIterator<T> {}

interface NodeCollectionConstructor<T> {
  prototype: T;
}

interface Map<K, V> extends NodeCollection {
  clear(): void;
  delete(key: K): boolean;
  entries(): Array<[K, V]>;
  forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
  get(key: K): V;
  has(key: K): boolean;
  keys(): Array<K>;
  set(key: K, value?: V): Map<K, V>;
  values(): Array<V>;
  // [Symbol.iterator]():Array<[K,V]>;
  // [Symbol.toStringTag]: "Map";
}

interface MapConstructor extends NodeCollectionConstructor<Map<any, any>> {
  new (): Map<any, any>;
  new <K, V>(): Map<K, V>;
}

declare var Map: MapConstructor;

interface WeakMap<K, V> extends NodeWeakCollection {
  clear(): void;
  delete(key: K): boolean;
  get(key: K): V | void;
  has(key: K): boolean;
  set(key: K, value?: V): WeakMap<K, V>;
}

interface WeakMapConstructor extends NodeCollectionConstructor<WeakMap<any, any>> {
  new (): WeakMap<any, any>;
  new <K, V>(): WeakMap<K, V>;
}

declare var WeakMap: WeakMapConstructor;

interface Set<T> extends NodeCollection {
  add(value: T): Set<T>;
  clear(): void;
  delete(value: T): boolean;
  entries(): Array<[T, T]>;
  forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
  has(value: T): boolean;
  keys(): Array<T>;
  values(): Array<T>;
  // [Symbol.iterator]():Array<T>;
  // [Symbol.toStringTag]: "Set";
}

interface SetConstructor extends NodeCollectionConstructor<Set<any>> {
  new (): Set<any>;
  new <T>(): Set<T>;
  new <T>(iterable: Array<T>): Set<T>;
}

declare var Set: SetConstructor;

interface WeakSet<T> extends NodeWeakCollection {
  add(value: T): WeakSet<T>;
  clear(): void;
  delete(value: T): boolean;
  has(value: T): boolean;
  // [Symbol.toStringTag]: "WeakSet";
}

interface WeakSetConstructor extends NodeCollectionConstructor<WeakSet<any>> {
  new (): WeakSet<any>;
  new <T>(): WeakSet<T>;
  new <T>(iterable: Array<T>): WeakSet<T>;
}

declare var WeakSet: WeakSetConstructor;

/************************************************
*                                               *
*                   GLOBAL                      *
*                                               *
************************************************/
declare var process: NodeJS.Process;
declare var global: NodeJS.Global;

declare var __filename: string;
declare var __dirname: string;

declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearTimeout(timeoutId: NodeJS.Timer): void;
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
declare function clearInterval(intervalId: NodeJS.Timer): void;
declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;
declare function clearImmediate(immediateId: any): void;

interface NodeRequireFunction {
  (id: string): any;
}

interface NodeRequire extends NodeRequireFunction {
  resolve(id: string): string;
  cache: { [filename: string]: NodeModule };
  extensions: NodeExtensions;
  main: any;
}

interface NodeExtensions {
  '.js': (m: NodeModule, filename: string) => any;
  '.json': (m: NodeModule, filename: string) => any;
  '.node': (m: NodeModule, filename: string) => any;
  [ext: string]: (m: NodeModule, filename: string) => any;
}

declare var require: NodeRequire;

declare class NodeModule {
  static runMain(): void;
  static wrap(code: string): string;
  static _nodeModulePaths(path: string): string[];
  static _load(request: string, parent?: NodeModule, isMain?: boolean): any;
  static _resolveFilename(request: string, parent?: NodeModule, isMain?: boolean): string;
  static _extensions: NodeExtensions;

  constructor(filename: string);
  _compile(code: string, filename: string): string;

  id: string;
  parent: NodeModule;
  filename: string;
  paths: string[];
  children: NodeModule[];
  exports: any;
  loaded: boolean;
  require: NodeRequireFunction;
}

declare var module: NodeModule;

// Same as module.exports
declare var exports: any;
declare var SlowBuffer: {
  new (str: string, encoding?: string): Buffer;
  new (size: number): Buffer;
  new (size: Uint8Array): Buffer;
  new (array: any[]): Buffer;
  prototype: Buffer;
  isBuffer(obj: any): boolean;
  byteLength(string: string, encoding?: string): number;
  concat(list: Buffer[], totalLength?: number): Buffer;
};

// Console class (compatible with TypeScript `lib.d.ts`).
declare interface Console {
  log(msg: any, ...params: any[]): void;
  info(msg: any, ...params: any[]): void;
  warn(msg: any, ...params: any[]): void;
  error(msg: any, ...params: any[]): void;
  dir(value: any, ...params: any[]): void;
  time(timerName?: string): void;
  timeEnd(timerName?: string): void;
  trace(msg: any, ...params: any[]): void;
  assert(test?: boolean, msg?: string, ...params: any[]): void;

  Console: new (stdout: NodeJS.WritableStream) => Console;
}

declare var console: Console;

declare class Buffer extends Uint8Array {
  [index: number]: number;
  /**
   * Allocates a new buffer containing the given {str}.
   *
   * @param str String to store in buffer.
   * @param encoding encoding to use, optional.  Default is 'utf8'
   */
  constructor(str: string, encoding?: string);
  /**
   * Allocates a new buffer of {size} octets.
   *
   * @param size count of octets to allocate.
   */
  constructor(size: number);
  /**
   * Allocates a new buffer containing the given {array} of octets.
   *
   * @param array The octets to store.
   */
  constructor(array: Uint8Array);
  /**
   * Produces a Buffer backed by the same allocated memory as
   * the given {ArrayBuffer}.
   *
   *
   * @param arrayBuffer The ArrayBuffer with which to share memory.
   */
  constructor(arrayBuffer: ArrayBuffer);
  /**
   * Allocates a new buffer containing the given {array} of octets.
   *
   * @param array The octets to store.
   */
  constructor(array: any[]);
  /**
   * Copies the passed {buffer} data onto a new {Buffer} instance.
   *
   * @param buffer The buffer to copy.
   */
  constructor(buffer: Buffer);
  /**
   * Allocates a new Buffer using an {array} of octets.
   *
   * @param array
   */
  static from(array: any[]): Buffer;
  /**
   * When passed a reference to the .buffer property of a TypedArray instance,
   * the newly created Buffer will share the same allocated memory as the TypedArray.
   * The optional {byteOffset} and {length} arguments specify a memory range
   * within the {arrayBuffer} that will be shared by the Buffer.
   *
   * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
   * @param byteOffset
   * @param length
   */
  static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
  /**
   * Copies the passed {buffer} data onto a new Buffer instance.
   *
   * @param buffer
   */
  static from(buffer: Buffer): Buffer;
  /**
   * Creates a new Buffer containing the given JavaScript string {str}.
   * If provided, the {encoding} parameter identifies the character encoding.
   * If not provided, {encoding} defaults to 'utf8'.
   *
   * @param str
   */
  static from(str: string, encoding?: string): Buffer;
  /**
   * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be _zero-filled_.
   *
   * @param size The desired length of the new `Buffer`
   * @param fill A value to pre-fill the new `Buffer` with. Default: `0`
   * @param encoding If `fill` is a string, this is its encoding. Default: `'utf8'`
   */
  static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
  /**
   * Allocates a new _non-zero-filled_ `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `buffer.kMaxLength`. Otherwise, a `RangeError` is thrown. A zero-length `Buffer` will be created if `size <= 0`.
   *
   * The underlying memory for `Buffer` instances created in this way is not initialized. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize such `Buffer` instances to zeroes.
   *
   * @param size The desired length of the new `Buffer`
   */
  static allocUnsafe(size: number): Buffer;
  /**
   * Returns `true` if `obj` is a Buffer, `false` otherwise.
   */
  static isBuffer(obj: any): obj is Buffer;
  /**
   * Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise.
   *
   * @param encoding A character encoding name to check.
   */
  static isEncoding(encoding: string): boolean;
  /**
   * Gives the actual byte length of a string. encoding defaults to 'utf8'.
   * This is not the same as String.prototype.length since that returns the number of characters in a string.
   *
   * @param string string to test.
   * @param encoding encoding used to evaluate (defaults to 'utf8')
   */
  static byteLength(string: string, encoding?: string): number;
  /**
   * Returns a buffer which is the result of concatenating all the buffers in the list together.
   *
   * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
   * If the list has exactly one item, then the first item of the list is returned.
   * If the list has more than one item, then a new Buffer is created.
   *
   * @param list An array of Buffer objects to concatenate
   * @param totalLength Total length of the buffers when concatenated.
   *   If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
   */
  static concat(list: Buffer[], totalLength?: number): Buffer;
  /**
   * The same as buf1.compare(buf2).
   */
  compare(buf1: Buffer, buf2: Buffer): number;
  write(string: string, offset?: number, length?: number, encoding?: string): number;
  toString(encoding?: string, start?: number, end?: number): string;
  toJSON(): any;
  equals(otherBuffer: Buffer): boolean;
  compare(otherBuffer: Buffer): number;
  copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
  slice(start?: number, end?: number): Buffer;
  writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
  readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
  readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
  readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
  readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
  readUInt8(offset: number, noAssert?: boolean): number;
  readUInt16LE(offset: number, noAssert?: boolean): number;
  readUInt16BE(offset: number, noAssert?: boolean): number;
  readUInt32LE(offset: number, noAssert?: boolean): number;
  readUInt32BE(offset: number, noAssert?: boolean): number;
  readInt8(offset: number, noAssert?: boolean): number;
  readInt16LE(offset: number, noAssert?: boolean): number;
  readInt16BE(offset: number, noAssert?: boolean): number;
  readInt32LE(offset: number, noAssert?: boolean): number;
  readInt32BE(offset: number, noAssert?: boolean): number;
  readFloatLE(offset: number, noAssert?: boolean): number;
  readFloatBE(offset: number, noAssert?: boolean): number;
  readDoubleLE(offset: number, noAssert?: boolean): number;
  readDoubleBE(offset: number, noAssert?: boolean): number;
  writeUInt8(value: number, offset: number, noAssert?: boolean): number;
  writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
  writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
  writeInt8(value: number, offset: number, noAssert?: boolean): number;
  writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
  writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
  writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
  writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
  writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
  writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
  writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
  writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
  fill(value: any, offset?: number, end?: number): this;
  indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
  lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
  swap16(): this;
  swap32(): this;
  swap64(): this;
  includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
  entries(): IterableIterator<[number, number]>;
  keys(): IterableIterator<number>;
  values(): IterableIterator<number>;
}

/************************************************
*                                               *
*               GLOBAL INTERFACES               *
*                                               *
************************************************/
declare namespace NodeJS {
  export interface ErrnoException extends Error {
    errno?: number;
    code?: string;
    path?: string;
    syscall?: string;
    stack?: string;
  }

  export interface EventEmitter {
    addListener(event: string, listener: Function): this;
    on(event: string, listener: Function): this;
    once(event: string, listener: Function): this;
    prependListener(event: string, listener: Function): this;
    prependOnceListener(event: string, listener: Function): this;
    removeListener(event: string, listener: Function): this;
    removeAllListeners(event?: string): this;
    setMaxListeners(n: number): this;
    getMaxListeners(): number;
    listeners(event: string): Function[];
    emit(event: string, ...args: any[]): boolean;
    eventNames(): string[];
    listenerCount(type: string): number;
  }

  export interface ReadableStream extends EventEmitter {
    readable: boolean;
    read(size?: number): string | Buffer;
    setEncoding(encoding: string): this;
    isPaused(): boolean;
    pause(): this;
    resume(): this;
    pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;
    unpipe<T extends WritableStream>(destination?: T): void;
    unshift(chunk: string): void;
    unshift(chunk: Buffer): void;
    wrap(oldStream: ReadableStream): ReadableStream;
  }

  export interface WritableStream extends EventEmitter {
    writable: boolean;
    setDefaultEncoding(encoding: string): this;
    write(buffer: Buffer | string, cb?: Function): boolean;
    write(str: string, encoding?: string, cb?: Function): boolean;
    end(): void;
    end(buffer: Buffer, cb?: Function): void;
    end(str: string, cb?: Function): void;
    end(str: string, encoding?: string, cb?: Function): void;
  }

  export interface ReadWriteStream extends ReadableStream, WritableStream { }

  export interface Events extends EventEmitter { }

  export interface Domain extends Events {
    run(fn: Function): void;
    add(emitter: Events): void;
    remove(emitter: Events): void;
    bind(cb: (err: Error, data: any) => any): any;
    intercept(cb: (data: any) => any): any;
    dispose(): void;

    addListener(event: string, listener: Function): this;
    on(event: string, listener: Function): this;
    once(event: string, listener: Function): this;
    removeListener(event: string, listener: Function): this;
    removeAllListeners(event?: string): this;
  }

  export interface MemoryUsage {
    rss: number;
    heapTotal: number;
    heapUsed: number;
  }

  export interface Env {
    PATH: string;
    [key: string]: string;
  }

  export interface Versions {
    http_parser: string;
    node: string;
    v8: string;
    ares: string;
    uv: string;
    zlib: string;
    modules: string;
    openssl: string;
  }

  export interface Process extends EventEmitter {
    stdout: WritableStream;
    stderr: WritableStream;
    stdin: ReadableStream;
    argv: string[];
    argv0: string;
    /**
     * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.
     */
    execArgv: string[];
    execPath: string;
    abort(): void;
    chdir(directory: string): void;
    cwd(): string;
    env: Env;
    exit(code?: number): void;
    exitCode?: number;
    getgid(): number;
    setgid(id: number): void;
    setgid(id: string): void;
    getuid(): number;
    setuid(id: number): void;
    setuid(id: string): void;
    version: string;
    versions: Versions;
    config: {
      target_defaults: {
        cflags: any[];
        default_configuration: string;
        defines: string[];
        include_dirs: string[];
        libraries: string[];
      };
      variables: {
        clang: number;
        host_arch: string;
        node_install_npm: boolean;
        node_install_waf: boolean;
        node_prefix: string;
        node_shared_openssl: boolean;
        node_shared_v8: boolean;
        node_shared_zlib: boolean;
        node_use_dtrace: boolean;
        node_use_etw: boolean;
        node_use_openssl: boolean;
        target_arch: string;
        v8_no_strict_aliasing: number;
        v8_use_snapshot: boolean;
        visibility: string;
      };
    };
    kill(pid: number, signal?: string | number): void;
    pid: number;
    title: string;
    arch: string;
    platform: string;
    memoryUsage(): MemoryUsage;
    nextTick(callback: Function): void;
    umask(mask?: number): number;
    uptime(): number;
    hrtime(time?: number[]): number[];
    domain: Domain;

    // Worker
    send?(message: any, sendHandle?: any): void;
    disconnect(): void;
    connected: boolean;
  }

  export interface Global {
    Array: typeof Array;
    ArrayBuffer: typeof ArrayBuffer;
    Boolean: typeof Boolean;
    Buffer: typeof Buffer;
    DataView: typeof DataView;
    Date: typeof Date;
    Error: typeof Error;
    EvalError: typeof EvalError;
    Float32Array: typeof Float32Array;
    Float64Array: typeof Float64Array;
    Function: typeof Function;
    GLOBAL: Global;
    Infinity: typeof Infinity;
    Int16Array: typeof Int16Array;
    Int32Array: typeof Int32Array;
    Int8Array: typeof Int8Array;
    Intl: typeof Intl;
    JSON: typeof JSON;
    Map: MapConstructor;
    Math: typeof Math;
    NaN: typeof NaN;
    Number: typeof Number;
    Object: typeof Object;
    Promise: Function;
    RangeError: typeof RangeError;
    ReferenceError: typeof ReferenceError;
    RegExp: typeof RegExp;
    Set: SetConstructor;
    String: typeof String;
    Symbol: Function;
    SyntaxError: typeof SyntaxError;
    TypeError: typeof TypeError;
    URIError: typeof URIError;
    Uint16Array: typeof Uint16Array;
    Uint32Array: typeof Uint32Array;
    Uint8Array: typeof Uint8Array;
    Uint8ClampedArray: Function;
    WeakMap: WeakMapConstructor;
    WeakSet: WeakSetConstructor;
    clearImmediate: (immediateId: any) => void;
    clearInterval: (intervalId: NodeJS.Timer) => void;
    clearTimeout: (timeoutId: NodeJS.Timer) => void;
    console: typeof console;
    decodeURI: typeof decodeURI;
    decodeURIComponent: typeof decodeURIComponent;
    encodeURI: typeof encodeURI;
    encodeURIComponent: typeof encodeURIComponent;
    escape: (str: string) => string;
    eval: typeof eval;
    global: Global;
    isFinite: typeof isFinite;
    isNaN: typeof isNaN;
    parseFloat: typeof parseFloat;
    parseInt: typeof parseInt;
    process: Process;
    root: Global;
    setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;
    setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
    setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;
    undefined: typeof undefined;
    unescape: (str: string) => string;
    gc: () => void;
    v8debug?: any;
  }

  export interface Timer {
    ref(): void;
    unref(): void;
    _called: boolean;
    _onTimeout: Function;
    _timerArgs?: any[];
  }

  export interface Immediate {
    _argv?: any[];
    _callback: Function;
    _onImmediate: Function;
  }
}

/************************************************
*                                               *
*                   MODULES                     *
*                                               *
************************************************/
declare module "buffer" {
  export var INSPECT_MAX_BYTES: number;
  export var kMaxLength: number;

  export type Encoding = "ascii" | "latin1" | "binary" | "utf8" | "utf-8" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "hex" | "base64";

  var BuffType: typeof Buffer;
  var SlowBuffType: typeof SlowBuffer;

  export { BuffType as Buffer, SlowBuffType as SlowBuffer };
}

declare module "querystring" {
  export interface StringifyOptions {
    encodeURIComponent?: Function;
  }

  export interface ParseOptions {
    maxKeys?: number;
    decodeURIComponent?: Function;
  }

  export function stringify<T>(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string;
  export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any;
  export function parse<T extends { [key: string]: string | string[] }>(str: string, sep?: string, eq?: string, options?: ParseOptions): T;
  export function escape(str: string): string;
  export function unescape(str: string): string;
}

declare module "events" {
  export class EventEmitter implements NodeJS.EventEmitter {
    static EventEmitter: EventEmitter;
    static listenerCount(emitter: EventEmitter, event: string): number; // deprecated
    static defaultMaxListeners: number;

    addListener(event: string, listener: (...args: any[]) => void): this;
    on(event: string, listener: (...args: any[]) => void): this;
    once(event: string, listener: (...args: any[]) => void): this;
    prependListener(event: string, listener: (...args: any[]) => void): this;
    prependOnceListener(event: string, listener: (...args: any[]) => void): this;
    removeListener(event: string, listener: (...args: any[]) => void): this;
    removeAllListeners(event?: string): this;
    setMaxListeners(n: number): this;
    getMaxListeners(): number;
    listeners(event: string): Array<(...args: any[]) => void>;
    listenerCount(event: string): number;
    emit(event: string, ...args: any[]): boolean;
    eventNames(): string[];
  }

  export interface Listener<E extends string, L extends Function> {
    on(event: E, listener: L): this;
    once(event: E, listener: L): this;
    addListener(event: E, listener: L): this;
    removeListener(event: E, listener: L): this;
    listeners(event: E): L[];
  }
}

declare module "http" {
  import * as events from "events";
  import * as net from "net";
  import * as stream from "stream";

  export interface OutgoingHeaders {
    [header: string]: number | string | string[];
  }

  export interface IncomingHeaders {
    [header: string]: string | string[];
  }

  export interface RequestOptions {
    protocol?: string;
    host?: string;
    hostname?: string;
    family?: number;
    port?: number | string;
    localAddress?: string;
    socketPath?: string;
    method?: string;
    path?: string;
    headers?: OutgoingHeaders;
    auth?: string;
    agent?: Agent | boolean;
  }

  export class Server extends net.Server {
    setTimeout(msecs: number, callback: Function): void;
    maxHeadersCount: number;
    timeout: number;
    listening: boolean;
  }

  export class ServerResponse extends stream.Writable {
    finished: boolean;
    headersSent: boolean;
    statusCode: number;
    statusMessage: string;
    sendDate: boolean;

    // Extended base methods
    write(buffer: Buffer): boolean;
    write(buffer: Buffer, cb?: Function): boolean;
    write(str: string, cb?: Function): boolean;
    write(str: string, encoding?: string, cb?: Function): boolean;
    write(str: string, encoding?: string, fd?: string): boolean;

    writeContinue(): void;
    writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void;
    writeHead(statusCode: number, headers?: OutgoingHeaders): void;
    setHeader(name: string, value: string | string[]): void;
    setTimeout(msecs: number, callback: () => void): this;
    getHeader(name: string): string;
    removeHeader(name: string): void;
    write(chunk: any, encoding?: string): any;
    addTrailers(headers: OutgoingHeaders): void;

    // Extended base methods
    end(): void;
    end(buffer: Buffer, cb?: Function): void;
    end(str: string, cb?: Function): void;
    end(str: string, encoding?: string, cb?: Function): void;
  }

  export class ClientRequest extends stream.Writable {
    // Extended base methods
    write(buffer: Buffer): boolean;
    write(buffer: Buffer, cb?: Function): boolean;
    write(str: string, cb?: Function): boolean;
    write(str: string, encoding?: string, cb?: Function): boolean;
    write(str: string, encoding?: string, fd?: string): boolean;

    write(chunk: any, encoding?: string): void;
    abort(): void;
    setTimeout(timeout: number, callback?: Function): void;
    setNoDelay(noDelay?: boolean): void;
    setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;

    setHeader(name: string, value: string | string[]): void;
    getHeader(name: string): string;
    removeHeader(name: string): void;
    addTrailers(headers: any): void;

    // Extended base methods
    end(): void;
    end(buffer: Buffer, cb?: Function): void;
    end(str: string, cb?: Function): void;
    end(str: string, encoding?: string, cb?: Function): void;
    end(data?: any, encoding?: string): void;
  }

  export class IncomingMessage extends stream.Readable {
    httpVersion: string;
    headers: IncomingHeaders;
    rawHeaders: string[];
    trailers: IncomingHeaders;
    rawTrailers: string[];
    setTimeout(msecs: number, callback: Function): NodeJS.Timer;
    destroy(error?: Error): void;
    /**
     * Only valid for request obtained from http.Server.
     */
    method?: string;
    /**
     * Only valid for request obtained from http.Server.
     */
    url?: string;
    /**
     * Only valid for response obtained from http.ClientRequest.
     */
    statusCode?: number;
    /**
     * Only valid for response obtained from http.ClientRequest.
     */
    statusMessage?: string;
    socket: net.Socket;
  }

  export interface AgentOptions {
    /**
     * Keep sockets around in a pool to be used by other requests in the future. Default = false
     */
    keepAlive?: boolean;
    /**
     * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
     * Only relevant if keepAlive is set to true.
     */
    keepAliveMsecs?: number;
    /**
     * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
     */
    maxSockets?: number;
    /**
     * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
     */
    maxFreeSockets?: number;
  }

  export class Agent {
    maxSockets: number;
    sockets: any;
    requests: any;

    constructor(opts?: AgentOptions);

    /**
     * Destroy any sockets that are currently in use by the agent.
     * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,
     * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,
     * sockets may hang open for quite a long time before the server terminates them.
     */
    destroy(): void;
  }

  export var METHODS: string[];

  export var STATUS_CODES: {
    [errorCode: number]: string;
    [errorCode: string]: string;
  };

  export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server;
  export function createClient(port?: number, host?: string): any;
  export function request(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
  export function get(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;
  export var globalAgent: Agent;
}

declare module "cluster" {
  import * as child from "child_process";
  import * as events from "events";

  export interface ClusterSettings {
    exec?: string;
    args?: string[];
    silent?: boolean;
  }

  export interface Address {
    address: string;
    port: number;
    addressType: string;
  }

  export class Worker extends events.EventEmitter {
    id: string;
    process: child.ChildProcess;
    suicide: boolean;
    send(message: any, sendHandle?: any): boolean;
    kill(signal?: string): void;
    destroy(signal?: string): void;
    disconnect(): void;
    isConnected(): boolean;
    isDead(): boolean;
  }

  export var settings: ClusterSettings;
  export var isMaster: boolean;
  export var isWorker: boolean;
  export function setupMaster(settings?: ClusterSettings): void;
  export function fork(env?: any): Worker;
  export function disconnect(callback?: Function): void;
  export var worker: Worker;
  export var workers: {
    [index: string]: Worker
  };

  // Event emitter
  export function addListener(event: string, listener: Function): void;
  export function on(event: "disconnect", listener: (worker: Worker) => void): void;
  export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void;
  export function on(event: "fork", listener: (worker: Worker) => void): void;
  export function on(event: "listening", listener: (worker: Worker, address: any) => void): void;
  export function on(event: "message", listener: (worker: Worker, message: any) => void): void;
  export function on(event: "online", listener: (worker: Worker) => void): void;
  export function on(event: "setup", listener: (settings: any) => void): void;
  export function on(event: string, listener: Function): any;
  export function once(event: string, listener: Function): void;
  export function removeListener(event: string, listener: Function): void;
  export function removeAllListeners(event?: string): void;
  export function setMaxListeners(n: number): void;
  export function listeners(event: string): Function[];
  export function emit(event: string, ...args: any[]): boolean;
}

declare module "zlib" {
  import * as stream from "stream";

  export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }
  export interface ZlibCallback { (error: Error, result: any): void }

  export interface Gzip extends stream.Transform { }
  export interface Gunzip extends stream.Transform { }
  export interface Deflate extends stream.Transform { }
  export interface Inflate extends stream.Transform { }
  export interface DeflateRaw extends stream.Transform { }
  export interface InflateRaw extends stream.Transform { }
  export interface Unzip extends stream.Transform { }

  export function createGzip(options?: ZlibOptions): Gzip;
  export function createGunzip(options?: ZlibOptions): Gunzip;
  export function createDeflate(options?: ZlibOptions): Deflate;
  export function createInflate(options?: ZlibOptions): Inflate;
  export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;
  export function createInflateRaw(options?: ZlibOptions): InflateRaw;
  export function createUnzip(options?: ZlibOptions): Unzip;

  export function deflate(buf: Buffer | string, callback?: ZlibCallback): void;
  export function deflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function deflateSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function deflateRaw(buf: Buffer | string, callback?: ZlibCallback): void;
  export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function gzip(buf: Buffer | string, callback?: ZlibCallback): void;
  export function gzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function gzipSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function gunzip(buf: Buffer | string, callback?: ZlibCallback): void;
  export function gunzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function inflate(buf: Buffer | string, callback?: ZlibCallback): void;
  export function inflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function inflateSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function inflateRaw(buf: Buffer | string, callback?: ZlibCallback): void;
  export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): any;
  export function unzip(buf: Buffer | string, callback?: ZlibCallback): void;
  export function unzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void;
  export function unzipSync(buf: Buffer | string, options?: ZlibOptions): any;

  // Constants
  export var Z_NO_FLUSH: number;
  export var Z_PARTIAL_FLUSH: number;
  export var Z_SYNC_FLUSH: number;
  export var Z_FULL_FLUSH: number;
  export var Z_FINISH: number;
  export var Z_BLOCK: number;
  export var Z_TREES: number;
  export var Z_OK: number;
  export var Z_STREAM_END: number;
  export var Z_NEED_DICT: number;
  export var Z_ERRNO: number;
  export var Z_STREAM_ERROR: number;
  export var Z_DATA_ERROR: number;
  export var Z_MEM_ERROR: number;
  export var Z_BUF_ERROR: number;
  export var Z_VERSION_ERROR: number;
  export var Z_NO_COMPRESSION: number;
  export var Z_BEST_SPEED: number;
  export var Z_BEST_COMPRESSION: number;
  export var Z_DEFAULT_COMPRESSION: number;
  export var Z_FILTERED: number;
  export var Z_HUFFMAN_ONLY: number;
  export var Z_RLE: number;
  export var Z_FIXED: number;
  export var Z_DEFAULT_STRATEGY: number;
  export var Z_BINARY: number;
  export var Z_TEXT: number;
  export var Z_ASCII: number;
  export var Z_UNKNOWN: number;
  export var Z_DEFLATED: number;
  export var Z_NULL: number;
}

declare module "os" {
  export interface CpuInfo {
    model: string;
    speed: number;
    times: {
      user: number;
      nice: number;
      sys: number;
      idle: number;
      irq: number;
    };
  }

  export interface NetworkInterfaceInfo {
    address: string;
    netmask: string;
    family: string;
    mac: string;
    internal: boolean;
  }

  export function tmpdir(): string;
  export function homedir(): string;
  export function endianness(): "BE" | "LE";
  export function hostname(): string;
  export function type(): string;
  export function platform(): string;
  export function arch(): string;
  export function release(): string;
  export function uptime(): number;
  export function loadavg(): number[];
  export function totalmem(): number;
  export function freemem(): number;
  export function cpus(): CpuInfo[];
  export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] };
  export function userInfo(options?: { encoding: 'buffer' }): { username: Buffer, uid: number, gid: number, shell: Buffer | null, homedir: Buffer }
  export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: string | null, homedir: string }
  export var EOL: string;
}

declare module "https" {
  import * as tls from "tls";
  import * as events from "events";
  import * as http from "http";

  export interface ServerOptions {
    pfx?: any;
    key?: any;
    passphrase?: string;
    cert?: any;
    ca?: any;
    crl?: any;
    ciphers?: string;
    honorCipherOrder?: boolean;
    requestCert?: boolean;
    rejectUnauthorized?: boolean;
    NPNProtocols?: any;
    SNICallback?: (servername: string) => any;
  }

  export interface RequestOptions extends http.RequestOptions {
    pfx?: string | Buffer;
    key?: string | Buffer;
    passphrase?: string;
    cert?: string | Buffer;
    ca?: string | Buffer | string[] | Buffer[];
    ciphers?: string;
    rejectUnauthorized?: boolean;
    secureProtocol?: string;
  }

  export interface AgentOptions extends http.AgentOptions {
    /**
     * Certificate, Private key and CA certificates to use for SSL. Default `null`.
     */
    pfx?: string | Buffer;
    /**
     * Private key to use for SSL. Default `null`.
     */
    key?: string | Buffer | string[] | Buffer[];
    /**
     * A string of passphrase for the private key or pfx. Default `null`.
     */
    passphrase?: string;
    /**
     * Public x509 certificate to use. Default `null`.
     */
    cert?: string | Buffer | string[] | Buffer[];
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
     */
    ca?: string | Buffer | string[] | Buffer[];
    /**
     * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format.
     */
    ciphers?: string;
    /**
     * If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default `true`.
     */
    rejectUnauthorized?: boolean;
    /**
     * Servername for SNI (Server Name Indication) TLS extension.
     */
    servername?: string;
    /**
     * The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
     */
    secureProtocol?: string;
    maxCachedSessions?: number;
  }

  export class Agent extends http.Agent {
    constructor(options?: AgentOptions);
  }

  export class Server extends tls.Server { }

  export function createServer(options: ServerOptions, requestListener?: Function): Server;
  export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
  export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest;
  export var globalAgent: Agent;
}

declare module "punycode" {
  export function decode(string: string): string;
  export function encode(string: string): string;
  export function toUnicode(domain: string): string;
  export function toASCII(domain: string): string;
  export var ucs2: ucs2;
  interface ucs2 {
    decode(string: string): number[];
    encode(codePoints: number[]): string;
  }
  export var version: any;
}

declare module "repl" {
  import { EventEmitter } from "events";
  import { Interface } from "readline";

  export interface ReplOptions {
    prompt?: string;
    input?: NodeJS.ReadableStream;
    output?: NodeJS.WritableStream;
    terminal?: boolean;
    eval?: Function;
    useColors?: boolean;
    useGlobal?: boolean;
    ignoreUndefined?: boolean;
    writer?: Function;
    completer?: Function;
    replMode?: symbol;
    breakEvalOnSigint?: boolean;
  }

  export function start(options: ReplOptions): REPLServer;

  export type REPLCommand = (this: REPLServer, rest: string) => void;

  export class REPLServer extends Interface {
    inputStream: NodeJS.ReadableStream;
    outputStream: NodeJS.WritableStream;
    useColors: boolean;
    commands: {
      [command: string]: REPLCommand;
    };
    defineCommand(keyword: string, cmd: REPLCommand | { help: string, action: REPLCommand }): void;
    displayPrompt(preserveCursor?: boolean): void;
    setPrompt(prompt: string): void;
    turnOffEditorMode(): void;
  }

  export class Recoverable extends SyntaxError {
    err: Error;
    constructor(err: Error);
  }
}

declare module "readline" {
  import * as events from "events";
  import * as stream from "stream";

  export interface Key {
    sequence?: string;
    name?: string;
    ctrl?: boolean;
    meta?: boolean;
    shift?: boolean;
  }

  export class Interface extends events.EventEmitter {
    setPrompt(prompt: string): void;
    prompt(preserveCursor?: boolean): void;
    question(query: string, callback: (answer: string) => void): void;
    pause(): this;
    resume(): this;
    close(): void;
    write(data: string | Buffer, key?: Key): void;
  }

  export interface Completer {
    (line: string): CompleterResult;
    (line: string, callback: (err: any, result: CompleterResult) => void): any;
  }

  export interface CompleterResult {
    completions: string[];
    line: string;
  }

  export interface InterfaceOptions {
    input: NodeJS.ReadableStream;
    output?: NodeJS.WritableStream;
    completer?: Completer;
    terminal?: boolean;
    historySize?: number;
  }

  export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface;
  export function createInterface(options: InterfaceOptions): Interface;

  export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void;
  export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void;
  export function clearLine(stream: NodeJS.WritableStream, dir: number): void;
  export function clearScreenDown(stream: NodeJS.WritableStream): void;
}

declare module "vm" {
  export interface Context { }

  export interface ScriptOptions {
    filename?: string;
    lineOffset?: number;
    columnOffset?: number;
    displayErrors?: boolean;
    timeout?: number;
    cachedData?: Buffer;
    produceCachedData?: boolean;
  }

  export interface RunInNewContextOptions {
    filename?: string;
    lineOffset?: number;
    columnOffset?: number;
    displayErrors?: boolean;
    timeout?: number;
  }

  export interface RunInContextOptions extends RunInNewContextOptions {
    breakOnSigint?: boolean;
  }

  export class Script {
    constructor(code: string, options?: string | ScriptOptions);
    runInContext(contextifiedSandbox: Context, options?: RunInContextOptions): any;
    runInNewContext(sandbox?: Context, options?: RunInNewContextOptions): any;
    runInThisContext(options?: RunInNewContextOptions): any;
  }

  export function createContext(sandbox?: Context): Context;
  export function isContext(sandbox: Context): boolean;
  export function runInContext(code: string, contextifiedSandbox: Context, options?: string | RunInNewContextOptions): any;
  export function runInDebugContext(code: string): any;
  export function runInNewContext(code: string, sandbox?: Context, options?: string | RunInNewContextOptions): any;
  export function runInThisContext(code: string, options?: string | RunInNewContextOptions): any;
  /**
   * @deprecated
   */
  export function createScript(code: string, options?: string | ScriptOptions): Script;
}

declare module "child_process" {
  import * as events from "events";
  import * as stream from "stream";
  import * as buffer from "buffer";
  import * as net from "net";

  export class ChildProcess extends events.EventEmitter implements
    events.Listener<'close', (code: number, signal: string) => void>,
    events.Listener<'error', (error: Error) => void>,
    events.Listener<'exit', ((code: number, signal: string | null) => void) | ((code: number | null, signal: string) => void)>,
    events.Listener<'message', (message: any, sendHandle?: net.Socket | net.Server) => void>,
    events.Listener<'disconnect', () => void> {
    stdin: stream.Writable;
    stdout: stream.Readable;
    stderr: stream.Readable;
    stdio: [stream.Writable, stream.Readable, stream.Readable];
    pid: number;
    kill(signal?: string): void;
    send(message: any, sendHandle?: any): boolean;
    connected: boolean;
    disconnect(): void;
    unref(): void;
  }

  export interface SpawnOptions {
    cwd?: string;
    env?: any;
    stdio?: any;
    detached?: boolean;
    uid?: number;
    gid?: number;
    shell?: boolean | string;
  }

  export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess;

  export interface ExecOptions {
    cwd?: string;
    env?: any;
    shell?: string;
    timeout?: number;
    maxBuffer?: number;
    killSignal?: string;
    uid?: number;
    gid?: number;
    encoding?: buffer.Encoding | 'buffer';
  }

  export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;
  export function exec(command: string, options: ExecOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
  export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;

  export interface ExecFileOptions {
    cwd?: string;
    env?: any;
    timeout?: number;
    maxBuffer?: number;
    killSignal?: string;
    uid?: number;
    gid?: number;
    encoding?: buffer.Encoding | 'buffer';
  }

  export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;
  export function execFile(file: string, options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
  export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;
  export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;
  export function execFile(file: string, args?: string[], options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
  export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess;

  export interface ForkOptions {
    cwd?: string;
    env?: any;
    execPath?: string;
    execArgv?: string[];
    silent?: boolean;
    uid?: number;
    gid?: number;
  }

  export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess;

  export interface SpawnSyncOptions {
    cwd?: string;
    input?: string | Buffer;
    stdio?: any;
    env?: any;
    uid?: number;
    gid?: number;
    timeout?: number;
    killSignal?: string;
    maxBuffer?: number;
    shell?: boolean | string;
    encoding?: buffer.Encoding | 'buffer';
  }

  export interface SpawnSyncReturns<T> {
    pid: number;
    output: string[];
    stdout: T;
    stderr: T;
    status: number;
    signal: string;
    error: Error;
  }
  export function spawnSync(command: string): SpawnSyncReturns<Buffer>;
  export function spawnSync(command: string, options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns<Buffer>;
  export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;
  export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns<Buffer>;
  export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;

  export interface ExecSyncOptions {
    cwd?: string;
    input?: string | Buffer;
    stdio?: any;
    env?: any;
    shell?: string;
    uid?: number;
    gid?: number;
    timeout?: number;
    killSignal?: string;
    maxBuffer?: number;
    encoding?: buffer.Encoding | 'buffer';
  }

  export function execSync(command: string): Buffer;
  export function execSync(command: string, options?: ExecSyncOptions & { encoding: 'buffer' }): Buffer;
  export function execSync(command: string, options?: ExecSyncOptions): Buffer;

  export interface ExecFileSyncOptions {
    cwd?: string;
    input?: string | Buffer;
    stdio?: any;
    env?: any;
    uid?: number;
    gid?: number;
    timeout?: number;
    killSignal?: string;
    maxBuffer?: number;
    encoding?: buffer.Encoding | 'buffer';
  }

  export function execFileSync(command: string): Buffer;
  export function execFileSync(command: string, options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer;
  export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer;
  export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer;
  export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer;
}

declare module "url" {
  export interface Url {
    href?: string;
    protocol?: string;
    auth?: string;
    hostname?: string;
    port?: string;
    host?: string;
    pathname?: string;
    search?: string;
    query?: string | any;
    slashes?: boolean;
    hash?: string;
    path?: string;
  }

  export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url;
  export function format(url: Url | string): string;
  export function resolve(from: string, to: string): string;
}

declare module "dns" {
  export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string;
  export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string;
  export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[];
  export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[];

  export const NODATA: 'ENODATA';
  export const FORMERR: 'EFORMERR';
  export const SERVFAIL: 'ESERVFAIL';
  export const NOTFOUND: 'ENOTFOUND';
  export const NOTIMP: 'ENOTIMP';
  export const REFUSED: 'EREFUSED';
  export const BADQUERY: 'EBADQUERY';
  export const BADNAME: 'EBADNAME';
  export const BADFAMILY: 'EBADFAMILY';
  export const BADRESP: 'EBADRESP';
  export const CONNREFUSED: 'ECONNREFUSED';
  export const TIMEOUT: 'ETIMEOUT';
  export const EOF: 'EOF';
  export const FILE: 'EFILE';
  export const NOMEM: 'ENOMEM';
  export const DESTRUCTION: 'EDESTRUCTION';
  export const BADSTR: 'EBADSTR';
  export const BADFLAGS: 'EBADFLAGS';
  export const NONAME: 'ENONAME';
  export const BADHINTS: 'EBADHINTS';
  export const NOTINITIALIZED: 'ENOTINITIALIZED';
  export const LOADIPHLPAPI: 'ELOADIPHLPAPI';
  export const ADDRGETNETWORKPARAMS: 'EADDRGETNETWORKPARAMS';
  export const CANCELLED: 'ECANCELLED';
}

declare module "net" {
  import * as stream from "stream";

  export class Socket extends stream.Duplex {
    constructor(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; });

    // Extended base methods
    write(buffer: Buffer): boolean;
    write(buffer: Buffer, cb?: Function): boolean;
    write(str: string, cb?: Function): boolean;
    write(str: string, encoding?: string, cb?: Function): boolean;
    write(str: string, encoding?: string, fd?: string): boolean;

    connect(port: number, host?: string, connectionListener?: Function): void;
    connect(path: string, connectionListener?: Function): void;
    bufferSize: number;
    write(data: any, encoding?: string, callback?: Function): void;
    destroy(): void;
    setTimeout(timeout: number, callback?: Function): void;
    setNoDelay(noDelay?: boolean): void;
    setKeepAlive(enable?: boolean, initialDelay?: number): void;
    address(): { port: number; family: string; address: string; };
    unref(): void;
    ref(): void;

    remoteAddress: string;
    remoteFamily: string;
    remotePort: number;
    localAddress: string;
    localPort: number;
    bytesRead: number;
    bytesWritten: number;

    // Extended base methods
    end(): void;
    end(buffer: Buffer, cb?: Function): void;
    end(str: string, cb?: Function): void;
    end(str: string, encoding?: string, cb?: Function): void;
    end(data?: any, encoding?: string): void;
  }

  export interface ListenOptions {
    port?: number;
    host?: string;
    backlog?: number;
    path?: string;
    exclusive?: boolean;
  }

  export class Server extends Socket {
    listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): this;
    listen(port: number, hostname?: string, listeningListener?: Function): this;
    listen(port: number, backlog?: number, listeningListener?: Function): this;
    listen(port: number, listeningListener?: Function): this;
    listen(path: string, backlog?: number, listeningListener?: Function): this;
    listen(path: string, listeningListener?: Function): this;
    listen(handle: any, backlog?: number, listeningListener?: Function): this;
    listen(handle: any, listeningListener?: Function): this;
    listen(options: ListenOptions, listeningListener?: Function): this;
    close(callback?: () => void): this;
    address(): { port: number; family: string; address: string; };
    getConnections(cb: (error: Error, count: number) => void): void;
    ref(): this;
    unref(): this;
    maxConnections: number;
    connections: number;
  }

  export function createServer(connectionListener?: (socket: Socket) => void): Server;
  export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server;
  export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
  export function connect(port: number, host?: string, connectionListener?: Function): Socket;
  export function connect(path: string, connectionListener?: Function): Socket;
  export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;
  export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;
  export function createConnection(path: string, connectionListener?: Function): Socket;
  export function isIP(input: string): number;
  export function isIPv4(input: string): boolean;
  export function isIPv6(input: string): boolean;
}

declare module "dgram" {
  import * as events from "events";

  export interface RemoteInfo {
    address: string;
    port: number;
    size: number;
  }

  export interface AddressInfo {
    address: string;
    family: string;
    port: number;
  }

  export interface BindOptions {
    port: number;
    address?: string;
    exclusive?: boolean;
  }

  export interface SocketOptions {
    type: string;
    reuseAddr?: boolean;
  }

  export function createSocket(type: string | SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;

  export class Socket extends events.EventEmitter {
    send(msg: Buffer | string | Array<Buffer | string>, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;
    send(msg: Buffer | string | Array<Buffer | string>, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;
    bind(port: number, address?: string, callback?: () => void): void;
    bind(options: BindOptions, callback?: () => void): void;
    close(callback?: () => void): void;
    setTTL(ttl: number): void;
    address(): AddressInfo;
    setBroadcast(flag: boolean): void;
    setMulticastTTL(ttl: number): void;
    setMulticastLoopback(flag: boolean): void;
    addMembership(multicastAddress: string, multicastInterface?: string): void;
    dropMembership(multicastAddress: string, multicastInterface?: string): void;
    ref(): void;
    unref(): void;
  }
}

declare module "fs" {
  import * as stream from "stream";
  import * as events from "events";
  import * as buffer from "buffer";

  /**
   * Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type.
   */
  export class Stats {
    isFile(): boolean;
    isDirectory(): boolean;
    isBlockDevice(): boolean;
    isCharacterDevice(): boolean;
    isSymbolicLink(): boolean;
    isFIFO(): boolean;
    isSocket(): boolean;
    dev: number;
    ino: number;
    mode: number;
    nlink: number;
    uid: number;
    gid: number;
    rdev: number;
    size: number;
    blksize: number;
    blocks: number;
    /**
     * "Access Time" - Time when file data last accessed. Changed by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls.
     */
    atime: Date;
    /**
     * "Modified Time" - Time when file data last modified. Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls.
     */
    mtime: Date;
    /**
     * "Change Time" - Time when file status was last changed (inode data modification). Changed by the `chmod(2)`, `chown(2)`, `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`,` utimes(2)`, `read(2)`, and `write(2)` system calls.
     */
    ctime: Date;
    /**
     * "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the `utimes(2)` system call.
     */
    birthtime: Date;
  }

  export type WatchListener = (eventType: string, filename?: string | Buffer) => void;

  /**
   * Objects returned from fs.watch() are of this type.
   */
  export class FSWatcher extends events.EventEmitter implements
    events.Listener<'change', WatchListener> {
    close(): void;
  }

  export class ReadStream extends stream.Readable implements
    events.Listener<'open', (fd: number) => void>,
    events.Listener<'close', () => void> {
    bytesRead: number;
    path: string | Buffer;
    close(): void;
    destroy(): void;
  }

  export class WriteStream extends stream.Writable implements
    events.Listener<'open', (fd: number) => void>,
    events.Listener<'close', () => void> {
    close(): void;
    bytesWritten: number;
    path: string | Buffer;
  }

  export const F_OK: number;
  export const R_OK: number;
  export const W_OK: number;
  export const X_OK: number;

  export const constants: {
    O_RDONLY: number;
    O_WRONLY: number;
    O_RDWR: number;
    S_IFMT: number;
    S_IFREG: number;
    S_IFDIR: number;
    S_IFCHR: number;
    S_IFBLK: number;
    S_IFIFO: number;
    S_IFLNK: number;
    S_IFSOCK: number;
    O_CREAT: number;
    O_EXCL: number;
    O_NOCTTY: number;
    O_TRUNC: number;
    O_APPEND: number;
    O_DIRECTORY: number;
    O_NOFOLLOW: number;
    O_SYNC: number;
    O_SYMLINK: number;
    O_NONBLOCK: number;
    S_IRWXU: number;
    S_IRUSR: number;
    S_IWUSR: number;
    S_IXUSR: number;
    S_IRWXG: number;
    S_IRGRP: number;
    S_IWGRP: number;
    S_IXGRP: number;
    S_IRWXO: number;
    S_IROTH: number;
    S_IWOTH: number;
    S_IXOTH: number;
    F_OK: number;
    R_OK: number;
    W_OK: number;
    X_OK: number;
    [key: string]: number;
  }

  /**
   * Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of `mode`. It is possible to create a mask consisting of the bitwise OR of two or more values.
   */
  export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;
  export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous version of `fs.access()`. This throws if any accessibility checks fail, and does nothing otherwise.
   */
  export function accessSync(path: string | Buffer, mode?: number): void;

  export interface AppendFileOptions {
    encoding?: buffer.Encoding;
    mode?: number;
    flag?: string;
  }

  /**
   * Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a buffer.
   */
  export function appendFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;
  export function appendFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | AppendFileOptions, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * The synchronous version of `fs.appendFile()`.
   */
  export function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: AppendFileOptions): void;

  /**
   * Asynchronous chmod(2).
   */
  export function chmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous chmod(2).
   */
  export function chmodSync(path: string | Buffer, mode: number): void;

  /**
   * Asynchronous chown(2).
   */
  export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous chown(2).
   */
  export function chownSync(path: string | Buffer, uid: number, gid: number): void;

  /**
   * Asynchronous close(2).
   */
  export function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous close(2).
   */
  export function closeSync(fd: number): void;

  export interface ReadStreamOptions {
    flags?: string;
    encoding?: buffer.Encoding;
    fd?: number;
    mode?: number;
    autoClose?: boolean;
    start?: number;
    end?: number;
  }

  /**
   * Returns a new ReadStream object.
   *
   * Be aware that, unlike the default value set for `highWaterMark` on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter.
   */
  export function createReadStream(path: string | Buffer, options?: ReadStreamOptions): ReadStream;

  export interface WriteStreamOptions {
    flags?: string;
    defaultEncoding?: buffer.Encoding;
    fd?: number;
    mode?: number;
    autoClose?: boolean;
    start: number;
    end: number;
  }

  /**
   * Returns a new WriteStream object.
   */
  export function createWriteStream(path: string | Buffer, options?: WriteStreamOptions): WriteStream;

  /**
   * Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false.
   *
   * @deprecated
   */
  export function exists(path: string | Buffer, callback: (exists: boolean) => void): void;

  /**
   * Synchronous version of `fs.exists()`. Returns true if the file exists, false otherwise.
   */
  export function existsSync(path: string | Buffer): boolean;

  /**
   * Asynchronous fchmod(2).
   */
  export function fchmod(fd: number, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous fchmod(2).
   */
  export function fchmodSync(fd: number, mode: number): void;

  /**
   * Asynchronous fchown(2).
   */
  export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous fchown(2).
   */
  export function fchownSync(fd: number, uid: number, gid: number): void;

  /**
   * Asynchronous fdatasync(2).
   */
  export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous fdatasync(2).
   */
  export function fdatasyncSync(fd: number): void;

  /**
   * Asynchronous fstat(2).
   */
  export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;

  /**
   * Synchronous fstat(2).
   */
  export function fstatSync(fd: number): Stats;

  /**
   * Asynchronous fsync(2).
   */
  export function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous fsync(2).
   */
  export function fsyncSync(fd: number): void;

  /**
   * Asynchronous ftruncate(2).
   *
   * If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file.
   *
   * If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes ('\0').
   */
  export function ftruncate(fd: number, len: number | null | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous ftruncate(2).
   */
  export function ftruncateSync(fd: number, len?: number | null): void;

  /**
   * Change the file timestamps of a file referenced by the supplied file descriptor.
   */
  export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous version of `fs.futimes()`.
   */
  export function futimesSync(fd: number, atime: number, mtime: number): void;

  /**
   * Asynchronous lchmod(2).
   *
   * Only available on Mac OS X.
   *
   * @deprecated
   */
  export function lchmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous lchmod(2).
   *
   * @deprecated
   */
  export function lchmodSync(path: string | Buffer, mode: number): void;

  /**
   * Asynchronous lchown(2).
   *
   * @deprecated
   */
  export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous lchown(2).
   *
   * @deprecated
   */
  export function lchownSync(path: string | Buffer, uid: number, gid: number): void;

  /**
   * Asynchronous link(2).
   */
  export function link(existingPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous link(2).
   */
  export function linkSync(existingPath: string | Buffer, newPath: string | Buffer): void;

  /**
   * Asynchronous lstat(2). `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
   */
  export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;

  /**
   * Synchronous lstat(2).
   */
  export function lstatSync(path: string | Buffer): Stats;

  /**
   * Asynchronous mkdir(2). `mode` defaults to `0o777`.
   */
  export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;
  export function mkdir(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous mkdir(2).
   */
  export function mkdirSync(path: string | Buffer, mode?: number): void;

  export interface MkdtempOptions {
    encoding: buffer.Encoding;
  }

  /**
   * Creates a unique temporary directory.
   *
   * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
   *
   * The created folder path is passed as a string to the callback's second parameter.
   */
  export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void;
  export function mkdtemp(prefix: string, options: buffer.Encoding | MkdtempOptions, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void;

  /**
   * The synchronous version of fs.mkdtemp(). Returns the created folder path.
   */
  export function mkdtempSync(prefix: string, options?: buffer.Encoding | MkdtempOptions): string;

  /**
   * Asynchronous file open. See open(2). `flags` can be:
   *
   * 'r' - Open file for reading. An exception occurs if the file does not exist.
   *
   * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist.
   *
   * 'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.
   *
   * This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it.
   *
   * Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()`
   *
   * 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
   *
   * 'wx' - Like `'w'` but fails if `path` exists.
   *
   * 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
   *
   * 'wx+' - Like `'w+'` but fails if `path` exists.
   *
   * 'a' - Open file for appending. The file is created if it does not exist.
   *
   * 'ax' - Like 'a' but fails if `path` exists.
   *
   * 'a+' - Open file for reading and appending. The file is created if it does not exist.
   *
   * 'ax+' - Like 'a+' but fails if `path` exists.
   *
   * `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writable.
   */
  export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void;
  export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void;

  /**
   * Synchronous version of `fs.open()`.
   */
  export function openSync(path: string | Buffer, flags: string | number, mode?: number): number;

  /**
   * Read data from the file specified by fd.
   *
   * @param buffer is the buffer that the data will be written to.
   * @param offset is the offset in the buffer to start writing at.
   * @param length is an integer specifying the number of bytes to read.
   * @param position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.
   */
  export function read(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void;

  export interface ReaddirOptions {
    encoding?: buffer.Encoding | 'buffer';
  }

  /**
   * Asynchronous readdir(3). Reads the contents of a directory.
   *
   * @param files is an array of the names of the files in the directory excluding '.' and '..'.
   */
  export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void;
  export function readdir(path: string | Buffer, options: 'buffer' | (ReadFileOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void;
  export function readdir(path: string | Buffer, options: buffer.Encoding | ReaddirOptions, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void;

  /**
   * Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'.
   */
  export function readdirSync(path: string | Buffer): string[];
  export function readdirSync(path: string | Buffer, options: 'buffer' | (ReaddirOptions & { encoding: 'buffer' })): Buffer[];
  export function readdirSync(path: string | Buffer, options: buffer.Encoding | ReaddirOptions): string[];

  export interface ReadFileOptions {
    encoding?: buffer.Encoding | 'buffer';
    flag?: string;
  }

  /**
   * Asynchronously reads the entire contents of a file.
   */
  export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void;
  export function readFile(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding }), callback: (err: NodeJS.ErrnoException | null, data: string) => void): void;
  export function readFile(file: string | Buffer | number, options: 'buffer' | ReadFileOptions, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void;

  /**
   * Synchronous version of `fs.readFile`.
   */
  export function readFileSync(file: string | Buffer | number): Buffer;
  export function readFileSync(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding })): string;
  export function readFileSync(file: string | Buffer | number, options: 'buffer' | ReadFileOptions): Buffer;

  export interface ReadlinkOptions {
    encoding?: buffer.Encoding | 'buffer';
  }

  /**
   * Asynchronous readlink(2).
   */
  export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void;
  export function readlink(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void;
  export function readlink(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void;

  /**
   * Synchronous readlink(2).
   */
  export function readlinkSync(path: string | Buffer): string;
  export function readlinkSync(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' })): Buffer;
  export function readlinkSync(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions): string;

  /**
   * Synchronous version of `fs.read()`.
   */
  export function readSync(fd: number, buffer: string | Buffer, offset: number, length: number, position: number): number;

  export interface RealpathOptions {
    encoding?: buffer.Encoding | 'buffer';
  }

  /**
   * Asynchronous realpath(3). May use `process.cwd` to resolve relative paths.
   *
   * Only paths that can be converted to UTF8 strings are supported.
   */
  export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void;
  export function realpath(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void;
  export function realpath(path: string | Buffer, options: buffer.Encoding | RealpathOptions, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void;

  /**
   * Synchronous realpath(3). Returns the resolved path.
   *
   * Only paths that can be converted to UTF8 strings are supported.
   */
  export function realpathSync(path: string | Buffer): string;
  export function realpathSync(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' })): Buffer;
  export function realpathSync(path: string | Buffer, options: buffer.Encoding | RealpathOptions): string;

  /**
   * Asynchronous rename(2).
   */
  export function rename(oldPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous rename(2).
   */
  export function renameSync(oldPath: string | Buffer, newPath: string | Buffer): void;

  /**
   * Asynchronous rmdir(2).
   */
  export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous rmdir(2).
   */
  export function rmdirSync(path: string | Buffer): void;

  /**
   * Asynchronous stat(2).
   *
   * In case of an error, the `err.code` will be one of Common System Errors.
   *
   * Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
   *
   * To check if a file exists without manipulating it afterwards, `fs.access()` is recommended.
   */
  export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;

  /**
   * Synchronous stat(2).
   */
  export function statSync(path: string | Buffer): Stats;

  /**
   * Asynchronous symlink(2). The type argument is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the target argument will automatically be normalized to absolute path.
   */
  export function symlink(target: string | Buffer, path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;
  export function symlink(target: string | Buffer, path: string | Buffer, type: 'dir' | 'file' | 'junction', callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous symlink(2).
   */
  export function symlinkSync(target: string | Buffer, path: string | Buffer, type?: 'dir' | 'file' | 'junction'): void;

  /**
   * Asynchronous truncate(2).
   */
  export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous truncate(2).
   */
  export function truncateSync(path: string | Buffer, len?: number): void;

  /**
   * Asynchronous unlink(2).
   */
  export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous unlink(2).
   */
  export function unlinkSync(path: string | Buffer): void;

  /**
   * Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed and you have effectively stopped watching `filename`.
   *
   * Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error.
   *
   * Note: `fs.watch()` is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible.
   */
  export function unwatchFile(filename: string | Buffer, listener?: WatchListener): void;

  /**
   * Change file timestamps of the file referenced by the supplied path.
   *
   * Note: the arguments `atime` and `mtime` of the following related functions follow these rules:
   *
   * - The value should be a Unix timestamp in seconds. For example, `Date.now()` returns milliseconds, so it should be divided by 1000 before passing it in.
   * If the value is a numeric string like `'123456789'`, the value will get converted to the corresponding number.
   * If the value is `NaN` or `Infinity`, the value will get converted to `Date.now() / 1000`.
   */
  export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * Synchronous version of `fs.utimes()`.
   */
  export function utimesSync(path: string | Buffer, atime: number, mtime: number): void;

  export interface WatchOptions {
    /**
     * Indicates whether the process should continue to run as long as files are being watched. default = `true`.
     */
    persistent?: boolean;
    /**
     * Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See Caveats). default = `false`.
     */
    recursive?: boolean;
    /**
     * Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`.
     */
    encoding?: buffer.Encoding;
  }

  /**
   * Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a `fs.FSWatcher`.
   *
   * Please note the listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but they are not the same thing.
   */
  export function watch(filename: string | Buffer): FSWatcher;
  export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions): FSWatcher;
  export function watch(filename: string | Buffer, listener: WatchListener): FSWatcher;
  export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions, listener: WatchListener): FSWatcher;

  export interface WatchFileOptions {
    /**
     * Indicates whether the process should continue to run as long as files are being watched
     */
    persistent: boolean;
    /**
     * Indicates how often the target should be polled in milliseconds. The default is `5007`.
     */
    interval: number;
  }

  /**
   * Watch for changes on filename. The callback listener will be called each time the file is accessed.
   *
   * Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects.
   *
   * Note: `fs.watch()` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible.
   */
  export function watchFile(filename: string | Buffer, listener: (curr: Stats, prev: Stats) => void): void;
  export function watchFile(filename: string | Buffer, options: WatchFileOptions, listener: (curr: Stats, prev: Stats) => void): void;

  /**
   * Write `buffer` to the file specified by `fd`.
   *
   * `offset` and `length` determine the part of the buffer to be written.
   *
   * `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2).
   *
   * Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended.
   *
   * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
   */
  export function write(fd: number, buffer: string | Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void;
  export function write(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void;
  export function write(fd: number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void;
  export function write(fd: number, data: string | Buffer, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void;
  export function write(fd: number, data: string | Buffer, position: number, encoding: buffer.Encoding, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void;

  export interface WriteFileOptions {
    encoding?: buffer.Encoding;
    mode?: number;
    flag?: string;
  }

  /**
   * Asynchronously writes data to a file, replacing the file if it already exists.
   *
   * Note that it is unsafe to use `fs.writeFile` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended.
   *
   * Note: If a file descriptor is specified as the `file`, it will not be closed automatically.
   */
  export function writeFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void;
  export function writeFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | WriteFileOptions, callback: (err: NodeJS.ErrnoException | null) => void): void;

  /**
   * The synchronous version of `fs.writeFile()`.
   */
  export function writeFileSync(file: string | Buffer | number, data: string | Buffer, options?: buffer.Encoding | WriteFileOptions): void;

  /**
   * Synchronous `fs.write`.
   */
  export function writeSync(fd: number, buffer: string | Buffer, offset: number, length: number, position?: number): void;
  export function writeSync(fd: number, data: string | Buffer, position?: number, encoding?: buffer.Encoding): void;
}

declare module "path" {

  /**
   * A parsed path object generated by path.parse() or consumed by path.format().
   */
  export interface ParsedPath {
    /**
     * The root of the path such as '/' or 'c:\'
     */
    root: string;
    /**
     * The full directory path such as '/home/user/dir' or 'c:\path\dir'
     */
    dir: string;
    /**
     * The file name including extension (if any) such as 'index.html'
     */
    base: string;
    /**
     * The file extension (if any) such as '.html'
     */
    ext: string;
    /**
     * The file name without extension (if any) such as 'index'
     */
    name: string;
  }

  /**
   * Normalize a string path, reducing '..' and '.' parts.
   * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
   *
   * @param p string path to normalize.
   */
  export function normalize(p: string): string;
  /**
   * Join all arguments together and normalize the resulting path.
   * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.
   *
   * @param paths string paths to join.
   */
  export function join(...paths: string[]): string;
  /**
   * The right-most parameter is considered {to}.  Other parameters are considered an array of {from}.
   *
   * Starting from leftmost {from} paramter, resolves {to} to an absolute path.
   *
   * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.
   *
   * @param pathSegments string paths to join.  Non-string arguments are ignored.
   */
  export function resolve(...pathSegments: string[]): string;
  /**
   * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
   *
   * @param path path to test.
   */
  export function isAbsolute(path: string): boolean;
  /**
   * Solve the relative path from {from} to {to}.
   * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
   *
   * @param from
   * @param to
   */
  export function relative(from: string, to: string): string;
  /**
   * Return the directory name of a path. Similar to the Unix dirname command.
   *
   * @param p the path to evaluate.
   */
  export function dirname(p: string): string;
  /**
   * Return the last portion of a path. Similar to the Unix basename command.
   * Often used to extract the file name from a fully qualified path.
   *
   * @param p the path to evaluate.
   * @param ext optionally, an extension to remove from the result.
   */
  export function basename(p: string, ext?: string): string;
  /**
   * Return the extension of the path, from the last '.' to end of string in the last portion of the path.
   * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
   *
   * @param p the path to evaluate.
   */
  export function extname(p: string): string;
  /**
   * The platform-specific file separator. '\\' or '/'.
   */
  export var sep: string;
  /**
   * The platform-specific file delimiter. ';' or ':'.
   */
  export var delimiter: string;
  /**
   * Returns an object from a path string - the opposite of format().
   *
   * @param pathString path to evaluate.
   */
  export function parse(pathString: string): ParsedPath;
  /**
   * Returns a path string from an object - the opposite of parse().
   *
   * @param pathString path to evaluate.
   */
  export function format(pathObject: ParsedPath): string;

  export module posix {
    export function normalize(p: string): string;
    export function join(...paths: string[]): string;
    export function resolve(...pathSegments: string[]): string;
    export function isAbsolute(p: string): boolean;
    export function relative(from: string, to: string): string;
    export function dirname(p: string): string;
    export function basename(p: string, ext?: string): string;
    export function extname(p: string): string;
    export var sep: string;
    export var delimiter: string;
    export function parse(p: string): ParsedPath;
    export function format(pP: ParsedPath): string;
  }

  export module win32 {
    export function normalize(p: string): string;
    export function join(...paths: string[]): string;
    export function resolve(...pathSegments: string[]): string;
    export function isAbsolute(p: string): boolean;
    export function relative(from: string, to: string): string;
    export function dirname(p: string): string;
    export function basename(p: string, ext?: string): string;
    export function extname(p: string): string;
    export var sep: string;
    export var delimiter: string;
    export function parse(p: string): ParsedPath;
    export function format(pP: ParsedPath): string;
  }
}

declare module "string_decoder" {
  import * as buffer from "buffer";

  export class StringDecoder {
    /**
     * @param encoding The character encoding the `StringDecoder` will use. Defaults to `'utf8'`.
     */
    constructor(encoding?: buffer.Encoding);
    /**
     * Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`.
     *
     * @param buffer A `Buffer` containing the bytes to decode.
     */
    write(buffer: Buffer): string;
    /**
     * Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding.
     *
     * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input.
     *
     * @param buffer A `Buffer` containing the bytes to decode.
     */
    end(buffer?: Buffer): string;
  }
}

declare module "tls" {
  import * as crypto from "crypto";
  import * as net from "net";
  import * as stream from "stream";

  export var CLIENT_RENEG_LIMIT: number;
  export var CLIENT_RENEG_WINDOW: number;
  export var SLAB_BUFFER_SIZE: number;
  export var DEFAULT_CIPHERS: string;
  export var DEFAULT_ECDH_CURVE: string;

  export class Server extends net.Server {
    /**
     * The `server.addContext()` method adds a secure context that will be used if the client request's SNS hostname matches the supplied `hostname` (or wildcard).
     *
     * @param hostname A SNI hostname or wildcard (e.g. `'*'`)
     * @param options An object containing any of the possible properties from the `tls.createSecureContext()` options arguments
     */
    addContext(hostName: string, options: SecureContextOptions): void;
    /**
     * Returns a `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets.
     */
    getTicketKeys(): Buffer;
    /**
     * Updates the keys for encryption/decryption of the TLS Session Tickets.
     *
     * Note: The key's Buffer should be 48 bytes long. See ticketKeys option in tls.createServer for more information on how it is used.
     *
     * Note: Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys.
     */
    setTicketKeys(keys: Buffer): void;
    /**
     * Returns the current number of concurrent connections on the server.
     */
    connections: number;
  }

  export interface Certificate {
    /**
     * Country code.
     */
    C: string;
    /**
     * Street.
     */
    ST: string;
    /**
     * Locality.
     */
    L: string;
    /**
     * Organization.
     */
    O: string;
    /**
     * Organizational unit.
     */
    OU: string;
    /**
     * Common name.
     */
    CN: string;
  }

  export interface Cipher {
    /**
     * The cipher name.
     */
    name: string;
    /**
     * SSL/TLS protocol version.
     */
    version: string;
  }

  export interface EphemeralKeyInfo {
    type: 'DH' | 'ECDH';
    name?: string;
    size: number;
  }

  export interface PeerCertificate {
    subject: Certificate;
    issuerInfo: Certificate;
    issuer: Certificate;
    raw: Buffer;
    valid_from: string;
    valid_to: string;
    fingerprint: string;
    serialNumber: string;
  }

  export interface TLSSocketOptions {
    /**
     * An optional TLS context object from `tls.createSecureContext()`.
     */
    secureContext?: SecureContext;
    /**
     * If true the TLS socket will be instantiated in server-mode. Defaults to `false`.
     */
    isServer?: boolean;
    /**
     * An optional net.Server instance.
     */
    server?: net.Server;
    /**
     * Optional, see `tls.createServer()`.
     */
    requestCert?: boolean;
    /**
     * Optional, see `tls.createServer()`.
     */
    rejectUnauthorized?: boolean;
    /**
     * Optional, see `tls.createServer()`.
     */
    NPNProtocols?: string[] | Buffer;
    /**
     * Optional, see `tls.createServer()`.
     */
    ALPNProtocols?: string[] | Buffer;
    /**
     * Optional, see `tls.createServer()`.
     */
    SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void;
    /**
     * An optional Buffer instance containing a TLS session.
     */
    session?: Buffer;
    /**
     * If `true`, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication
     */
    requestOCSP?: boolean;
  }

  export interface RenegotiateOptions {
    rejectUnauthorized?: boolean;
    requestCert?: boolean;
  }

  export class TLSSocket extends net.Socket {
    /**
     * Construct a new `tls.TLSSocket` object from an existing TCP socket.
     */
    constructor(socket: net.Socket, options?: TLSSocketOptions);
    /**
     * Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`.
     */
    authorized: boolean;
    /**
     * Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`.
     */
    authorizationError?: Error;
    /**
     * Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances.
     */
    encrypted: true;
    /**
     * Returns an object representing the cipher name and the SSL/TLS protocol version that first defined the cipher.
     */
    getCipher(): Cipher;
    /**
     * Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in Perfect Forward Secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`.
     */
    getEphemeralKeyInfo(): EphemeralKeyInfo;
    /**
     * Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate.
     *
     * @param detailed Specify `true` to request that the full certificate chain with the `issuer` property be returned; false to return only the top certificate without the `issuer` property.
     */
    getPeerCertificate(detailed?: boolean): PeerCertificate;
    /**
     * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. The value `null` will be returned for server sockets or disconnected client sockets.
     */
    getProtocol(): string | null;
    /**
     * Returns the ASN.1 encoded TLS session or `undefined` if no session was negotiated. Can be used to speed up handshake establishment when reconnecting to the server.
     */
    getSession(): Buffer | undefined;
    /**
     * Returns the TLS session ticket or `undefined` if no session was negotiated.
     *
     * Note: This only works with client TLS sockets. Useful only for debugging, for session reuse `provide` session option to `tls.connect()`.
     */
    getTLSTicket(): Buffer | undefined;
    /**
     * Returns the string representation of the local IP address.
     */
    localAddress: string;
    /**
     * Returns the numeric representation of the local port.
     */
    localPort: number;
    /**
     * Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`.
     */
    remoteAddress: string;
    /**
     * Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
     */
    remoteFamily: string;
    /**
     * The numeric representation of the remote port. For example, 443.
     */
    remotePort: number;
    /**
     * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process.
     *
     * Note: This method can be used to request a peer's certificate after the secure connection has been established.
     *
     * Note: When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout.
     */
    renegotiate(options: RenegotiateOptions, callback: (err: Error | null) => any): any;
    /**
     * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. Returns `true` if setting the limit succeeded; false otherwise.
     *
     * Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.
     *
     * @param size The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`.
     */
    setMaxSendFragment(size: number): boolean;
  }

  export interface ConnectOptions {
    /**
     * Host the client should connect to.
     */
    host?: string;
    /**
     * Port the client should connect to.
     */
    port?: number | string;
    /**
     * Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored.
     */
    socket?: net.Socket;
    /**
     * Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
     */
    path?: string;
    /**
     * A `string` or `Buffer` containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format.
     */
    pfx?: string | Buffer;
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s containing the private key of the client in PEM format.
     */
    key?: string | Buffer | string[] | Buffer[];
    /**
     * A string containing the passphrase for the private key or pfx.
     */
    passphrase?: string;
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s containing the certificate key of the client in PEM format.
     */
    cert?: string | Buffer | string[] | Buffer[];
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
     */
    ca?: string | Buffer | string[] | Buffer[];
    /**
     * A string describing the ciphers to use or exclude, separated by `:`. Uses the same default cipher suite as `tls.createServer()`.
     */
    ciphers?: string;
    /**
     * If true, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`.
     */
    rejectUnauthorized?: boolean;
    /**
     * An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`.
     */
    NPNProtocols?: string[] | Buffer[];
    /**
     * An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.)
     */
    ALPNProtocols?: string[] | Buffer[];
    /**
     * Server name for the SNI (Server Name Indication) TLS extension.
     */
    servername?: string;
    /**
     * A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified.
     */
    checkServerIdentity?: (servername: string, cert: Buffer) => void;
    /**
     * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS.
     */
    secureProtocol?: string;
    /**
     * An optional TLS context object as returned by from `tls.createSecureContext( ... )`. It can be used for caching client certificates, keys, and CA certificates.
     */
    secureContext?: SecureContext;
    /**
     * A `Buffer` instance, containing TLS session.
     */
    session?: Buffer;
    /**
     * Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`.
     */
    minDHSize?: number;
  }

  export interface SecureContextOptions {
    /**
     * A string or `Buffer` holding the PFX or PKCS12 encoded private key, certificate, and CA certificates.
     */
    pfx?: string | Buffer;
    /**
     * The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as an array of key strings or as an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys.
     */
    key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>;
    /**
     * A string containing the passphrase for the private key or pfx.
     */
    passphrase?: string;
    /**
     * A string containing the PEM encoded certificate.
     */
    cert?: string | Buffer | string[] | Buffer[];
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
     */
    ca?: string | Buffer | string[] | Buffer[];
    /**
     * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List).
     */
    crl?: string | string[];
    /**
     * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format.
     */
    ciphers?: string;
    /**
     * If `true`, when a cipher is being selected, the server's preferences will be used instead of the client preferences.
     */
    honorCipherOrder?: boolean;
  }

  export interface CreateServerOptions {
    /**
     * A `string` or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert`, and `ca` options.)
     */
    pfx?: string | Buffer;
    /**
     * The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys.
     */
    key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>;
    /**
     * A string containing the passphrase for the private key or pfx.
     */
    passphrase?: string;
    /**
     * A string containing the PEM encoded certificate.
     */
    cert?: string | Buffer | string[] | Buffer[];
    /**
     * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections.
     */
    ca?: string | Buffer | string[] | Buffer[];
    /**
     * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List).
     */
    crl?: string | string[];
    /**
     * A string describing the ciphers to use or exclude, separated by `:`.
     */
    ciphers?: string;
    /**
     * A string describing a named curve to use for ECDH key agreement or false to disable ECDH. Defaults to `prime256v1` (NIST P-256). Use crypto.getCurves() to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve.
     */
    ecdhCurve?: string;
    /**
     * A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.
     */
    dhparam?: string | Buffer;
    /**
     * Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out.
     */
    handshakeTimeout?: number;
    /**
     * When choosing a cipher, use the server's preferences instead of the client preferences. Defaults to `true`.
     */
    honorCipherOrder?: boolean;
    /**
     * If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`.
     */
    requestCert?: boolean;
    /**
     * If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`.
     */
    rejectUnauthorized?: boolean;
    /**
     * An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.)
     */
    NPNProtocols?: string[] | Buffer;
    /**
     * An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client.
     */
    ALPNProtocols?: string[] | Buffer;
    /**
     * A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below).
     */
    SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void;
    /**
     * An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See SSL_CTX_set_timeout for more details.
     */
    sessionTimeout?: number;
    /**
     * A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. Note that this is automatically shared between `cluster` module workers.
     */
    ticketKeys?: Buffer;
    /**
     * A string containing an opaque identifier for session resumption. If `requestCert` is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided.
     */
    sessionIdContext?: string;
    /**
     * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS.
     */
    secureProtocol?: string;
  }

  export interface SecureContext {
    context: any;
  }

  /**
   * Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the `'secureConnection'` event.
   */
  export function createServer(options: CreateServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;

  /**
   * Creates a new client connection to the given `port` and `host` or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.)
   */
  export function connect(options: ConnectOptions, callback?: () => void): TLSSocket;
  export function connect(port: number, options?: ConnectOptions, callback?: () => void): TLSSocket;
  export function connect(port: number, host?: string, options?: ConnectOptions, callback?: () => void): TLSSocket;

  /**
   * The `tls.createSecureContext()` method creates a credentials object.
   *
   * If the `'ca'` option is not given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.
   */
  export function createSecureContext(options: SecureContextOptions): SecureContext;

  /**
   * Returns an array with the names of the supported SSL ciphers.
   */
  export function getCiphers(): string[];
}

declare module "crypto" {
  import * as stream from "stream";

  export var constants: {
    defaultCipherList: string;
    defaultCoreCipherList: string;
    [key: string]: string | number;
  }

  export function getCiphers(): string[];
  export function getCurves(): string[];
  export function getHashes(): string[];

  export class Certificate {
    constructor();
    exportChallenge(spkac: string | Buffer, encoding?: string): string;
    exportPublicKey(spkac: string | Buffer, encoding?: string): Buffer;
    verifySpkac(spkac: Buffer): boolean;
  }

  export function createHash(algorithm: string): Hash;

  export class Hash extends stream.Transform {
    update(data: string | Buffer, input_encoding?: string): Hash;
    digest(encoding: 'buffer'): Buffer;
    digest(encoding: string): string;
    digest(): Buffer;
  }

  export function createHmac(algorithm: string, key: string | Buffer): Hmac;

  export class Hmac extends stream.Transform {
    update(data: string | Buffer, input_encoding?: string): Hmac;
    digest(encoding: 'buffer'): Buffer;
    digest(encoding: string): string;
    digest(): Buffer;
  }

  export function createCipher(algorithm: string, password: string | Buffer): Cipher;
  export function createCipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Cipher;

  export class Cipher extends stream.Transform {
    update(data: Buffer): Buffer;
    update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1"): Buffer;
    update(data: Buffer, input_encoding: any, output_encoding: "binary" | "latin1" | "base64" | "hex"): string;
    update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1", output_encoding: "binary" | "latin1" | "base64" | "hex"): string;
    final(): Buffer;
    final(output_encoding: string): string;
    setAAD(buffer: Buffer): void;
    setAutoPadding(auto_padding: boolean): void;
    getAuthTag(): Buffer;
  }

  export function createDecipher(algorithm: string, password: string | Buffer): Decipher;
  export function createDecipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Decipher;

  export class Decipher extends stream.Transform {
    update(data: Buffer): Buffer;
    update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex"): Buffer;
    update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string;
    update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string;
    final(): Buffer;
    final(output_encoding: string): string;
    setAAD(buffer: Buffer): void;
    setAutoPadding(auto_padding: boolean): void;
    setAuthTag(tag: Buffer): void;
  }

  export function createSign(algorithm: string): Signer;

  export class Signer extends stream.Writable {
    update(data: string | Buffer): void;
    sign(private_key: string): Buffer;
    sign(private_key: string, output_format: string): string;
  }

  export function createVerify(algorith: string): Verify;

  export class Verify extends stream.Writable {
    update(data: string | Buffer): void;
    verify(object: string, signature: string, signature_format?: string): boolean;
  }

  export function createDiffieHellman(prime: number, prime_encoding?: string, generator?: number | string | Buffer, generator_encoding?: string): DiffieHellman;
  export function createDiffieHellman(prime_length: number, generator?: number | string | Buffer): DiffieHellman;
  export function getDiffieHellman(group_name: string): DiffieHellman;

  export class DiffieHellman {
    verifyError: number;
    computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;
    generateKeys(encoding?: string): string;
    getPrime(encoding?: string): string;
    getGenerator(encoding?: string): string;
    getPublicKey(encoding?: string): string;
    getPrivateKey(encoding?: string): string;
    setPublicKey(public_key: string, encoding?: string): void;
    setPrivateKey(public_key: string, encoding?: string): void;
  }

  export function createECDH(curve_name: string): ECDH;

  export class ECDH {
    computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;
    generateKeys(encoding?: string, format?: string): string;
    getPrivateKey(encoding?: string): string;
    getPublicKey(encoding?: string, format?: string): string;
    setPrivateKey(private_key: string, encoding?: string): void;
  }

  export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => void): void;
  export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => void): void;

  export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer;
  export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer;

  export function randomBytes(size: number): Buffer;
  export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void;

  export function pseudoRandomBytes(size: number): Buffer;
  export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void;

  export interface RsaKey {
    key: string;
    passphrase?: string,
    padding?: number;
  }

  export function timingSafeEqual(a: Buffer, b: Buffer): boolean;
  export function publicEncrypt(public_key: string | RsaKey, buffer: Buffer): Buffer;
  export function privateEncrypt(private_key: string | RsaKey, buffer: Buffer): Buffer;
  export function publicDecrypt(public_key: string | RsaKey, buffer: Buffer): Buffer;
  export function privateDecrypt(private_key: string | RsaKey, buffer: Buffer): Buffer;

  export function setEngine(engine: string, flags?: number): void;
}

declare module "stream" {
  import * as events from "events";

  export class Stream extends events.EventEmitter {
    pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
  }

  export interface ReadableOptions {
    highWaterMark?: number;
    encoding?: string;
    objectMode?: boolean;
    read?: (size?: number) => any;
  }

  export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {
    readable: boolean;
    constructor(opts?: ReadableOptions);
    _read(size: number): void;
    read(size?: number): any;
    isPaused(): boolean;
    setEncoding(encoding: string): this;
    pause(): this;
    resume(): this;
    pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
    unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
    unshift(chunk: any): void;
    wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
    push(chunk: any, encoding?: string): boolean;
  }

  export interface WritableOptions {
    highWaterMark?: number;
    decodeStrings?: boolean;
    objectMode?: boolean;
    write?: (chunk: string | Buffer, encoding: string, callback: Function) => any;
    writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any;
  }

  export class Writable extends events.EventEmitter implements NodeJS.WritableStream {
    writable: boolean;
    constructor(opts?: WritableOptions);
    setDefaultEncoding(encoding: string): this;
    _write(chunk: any, encoding: string, callback: Function): void;
    write(chunk: any, cb?: Function): boolean;
    write(chunk: any, encoding?: string, cb?: Function): boolean;
    end(): void;
    end(chunk: any, cb?: Function): void;
    end(chunk: any, encoding?: string, cb?: Function): void;
  }

  export interface DuplexOptions extends ReadableOptions, WritableOptions {
    allowHalfOpen?: boolean;
    readableObjectMode?: boolean;
    writableObjectMode?: boolean;
  }

  // Note: Duplex extends both Readable and Writable.
  export class Duplex extends Readable implements NodeJS.ReadWriteStream {
    writable: boolean;
    constructor(opts?: DuplexOptions);
    setDefaultEncoding(encoding: string): this;
    _write(chunk: any, encoding: string, callback: Function): void;
    write(chunk: any, cb?: Function): boolean;
    write(chunk: any, encoding?: string, cb?: Function): boolean;
    end(): void;
    end(chunk: any, cb?: Function): void;
    end(chunk: any, encoding?: string, cb?: Function): void;
  }

  export interface TransformOptions extends ReadableOptions, WritableOptions {
    write?: (chunk: string | Buffer, encoding: string, callback: Function) => any;
    writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any;
  }

  // Note: Transform lacks the _read and _write methods of Readable/Writable.
  export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {
    readable: boolean;
    writable: boolean;
    constructor(opts?: TransformOptions);
    _transform(chunk: any, encoding: string, callback: Function): void;
    _flush(callback: Function): void;
    read(size?: number): any;
    setEncoding(encoding: string): this;
    setDefaultEncoding(encoding: string): this;
    isPaused(): boolean;
    pause(): this;
    resume(): this;
    pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;
    unpipe<T extends NodeJS.WritableStream>(destination?: T): void;
    unshift(chunk: any): void;
    wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;
    push(chunk: any, encoding?: string): boolean;
    write(chunk: any, cb?: Function): boolean;
    write(chunk: any, encoding?: string, cb?: Function): boolean;
    end(): void;
    end(chunk: any, cb?: Function): void;
    end(chunk: any, encoding?: string, cb?: Function): void;
  }

  export class PassThrough extends Transform { }
}

declare module "util" {
  /**
   * The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` environment variable. If the `section` name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op.
   */
  export function debuglog(section: string): (msg: any, ...args: any[]) => void;

  export interface InspectOptions {
    /**
     * If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`.
     */
    showHidden?: boolean;
    /**
     * Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`.
     */
    depth?: number | null;
    /**
     * If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see "Customizing util.inspect colors".
     */
    colors?: boolean;
    /**
     * If `false`, then custom `inspect(depth, opts)` functions exported on the object being inspected will not be called. Defaults to `true`.
     */
    customInspect?: boolean;
    /**
     * If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`.
     */
    showProxy?: boolean;
    /**
     * Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements.
     */
    maxArrayLength?: number | null;
    /**
     * The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to `60` for legacy compatibility.
     */
    breakLength?: number;
  }

  /**
   * The `util.inspect()` method returns a string representation of object that is primarily useful for debugging.
   */
  export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string;
  export function inspect(object: any, options: InspectOptions): string;

  export namespace inspect {
    export var colors: {
      bold: [number, number];
      italic: [number, number];
      underline: [number, number];
      inverse: [number, number];
      white: [number, number];
      grey: [number, number];
      black: [number, number];
      blue: [number, number];
      cyan: [number, number];
      green: [number, number];
      magenta: [number, number];
      red: [number, number];
      yellow: [number, number];
    }

    export var styles: {
      special: string;
      number: string;
      boolean: string;
      undefined: string;
      null: string;
      string: string;
      symbol: string;
      date: string;
      regexp: string;
    };

    export var custom: symbol;
  }

  /**
   * The `util.deprecate()` method wraps the given function or class in such a way that it is marked as deprecated.
   */
  export function deprecate<T>(fn: T, string: string): T;

  /**
   * The `util.format()` method returns a formatted string using the first argument as a printf-like format.
   */
  export function format(format: any, ...param: any[]): string;

  /**
   * Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.
   */
  export function inherits(constructor: any, superConstructor: any): void;

  /**
   * Deprecated predecessor of `console.error`.
   *
   * @deprecated
   */
  export function debug(string: string): void;

  /**
   * Deprecated predecessor of `console.error`.
   *
   * @deprecated
   */
  export function error(...strings: string[]): void;

  /**
   * Internal alias for `Array.isArray`.
   *
   * @deprecated
   */
  export function isArray(object: any): object is any[];

  /**
   * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isBoolean(object: any): object is boolean;

  /**
   * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isBuffer(object: any): object is Buffer;

  /**
   * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isDate(object: any): object is Date;

  /**
   * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isError(object: any): object is Error;

  /**
   * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isFunction(object: any): object is Function;

  /**
   * Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isNull(object: any): object is null;

  /**
   * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isNullOrUndefined(object: any): object is null | undefined;

  /**
   * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isNumber(object: any): object is number;

  /**
   * Returns true if the given `object` is strictly an `Object` and not a `Function`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isObject(object: any): object is Object;

  /**
   * Returns true if the given `object` is a primitive type. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isPrimitive(object: any): object is string | number | boolean | null | undefined;

  /**
   * Returns true if the given `object` is a `RegExp`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isRegExp(object: any): object is RegExp;

  /**
   * Returns true if the given `object` is a `String`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isString(object: any): object is string;

  /**
   * Returns true if the given `object` is a `Symbol`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isSymbol(object: any): object is symbol;

  /**
   * Returns true if the given `object` is `undefined`. Otherwise, returns `false`.
   *
   * @deprecated
   */
  export function isUndefined(object: any): object is symbol;

  /**
   * The `util.log()` method prints the given `string` to `stdout` with an included timestamp.
   *
   * @deprecated
   */
  export function log(string: string): void;

  /**
   * Deprecated predecessor of `console.log`.
   *
   * @deprecated
   */
  export function print(strings: string[]): void;

  /**
   * Deprecated predecessor of `console.log`.
   *
   * @deprecated
   */
  export function puts(strings: string[]): void;

  /**
   * The `util._extend()` method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.
   *
   * It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through `Object.assign()`.
   *
   * @deprecated
   */
  export function _extend<T, U>(target: T, source: U): T & U;
}

declare module "assert" {
  function internal(value: any, message?: string): void;
  namespace internal {
    export class AssertionError implements Error {
      name: string;
      message: string;
      actual: any;
      expected: any;
      operator: string;
      generatedMessage: boolean;

      constructor(options?: {
        message?: string; actual?: any; expected?: any;
        operator?: string; stackStartFunction?: Function
      });
    }

    export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;
    export function ok(value: any, message?: string): void;
    export function equal(actual: any, expected: any, message?: string): void;
    export function notEqual(actual: any, expected: any, message?: string): void;
    export function deepEqual(actual: any, expected: any, message?: string): void;
    export function notDeepEqual(acutal: any, expected: any, message?: string): void;
    export function strictEqual(actual: any, expected: any, message?: string): void;
    export function notStrictEqual(actual: any, expected: any, message?: string): void;
    export function deepStrictEqual(actual: any, expected: any, message?: string): void;
    export function notDeepStrictEqual(actual: any, expected: any, message?: string): void;
    export var throws: {
      (block: Function, message?: string): void;
      (block: Function, error: Function, message?: string): void;
      (block: Function, error: RegExp, message?: string): void;
      (block: Function, error: (err: any) => boolean, message?: string): void;
    };

    export var doesNotThrow: {
      (block: Function, message?: string): void;
      (block: Function, error: Function, message?: string): void;
      (block: Function, error: RegExp, message?: string): void;
      (block: Function, error: (err: any) => boolean, message?: string): void;
    };

    export function ifError(value: any): void;
  }

  export = internal;
}

declare module "tty" {
  import * as net from "net";

  export function isatty(fd: number): boolean;
  export interface ReadStream extends net.Socket {
    isRaw: boolean;
    setRawMode(mode: boolean): void;
    isTTY: boolean;
  }
  export interface WriteStream extends net.Socket {
    columns: number;
    rows: number;
    isTTY: boolean;
  }
}

declare module "domain" {
  import * as events from "events";

  export class Domain extends events.EventEmitter implements NodeJS.Domain {
    run(fn: Function): void;
    add(emitter: events.EventEmitter): void;
    remove(emitter: events.EventEmitter): void;
    bind(cb: (err: Error, data: any) => any): any;
    intercept(cb: (data: any) => any): any;
    dispose(): void;
    members: any[];
    enter(): void;
    exit(): void;
  }

  export function create(): Domain;
}

declare module "constants" {
  export var E2BIG: number;
  export var EACCES: number;
  export var EADDRINUSE: number;
  export var EADDRNOTAVAIL: number;
  export var EAFNOSUPPORT: number;
  export var EAGAIN: number;
  export var EALREADY: number;
  export var EBADF: number;
  export var EBADMSG: number;
  export var EBUSY: number;
  export var ECANCELED: number;
  export var ECHILD: number;
  export var ECONNABORTED: number;
  export var ECONNREFUSED: number;
  export var ECONNRESET: number;
  export var EDEADLK: number;
  export var EDESTADDRREQ: number;
  export var EDOM: number;
  export var EEXIST: number;
  export var EFAULT: number;
  export var EFBIG: number;
  export var EHOSTUNREACH: number;
  export var EIDRM: number;
  export var EILSEQ: number;
  export var EINPROGRESS: number;
  export var EINTR: number;
  export var EINVAL: number;
  export var EIO: number;
  export var EISCONN: number;
  export var EISDIR: number;
  export var ELOOP: number;
  export var EMFILE: number;
  export var EMLINK: number;
  export var EMSGSIZE: number;
  export var ENAMETOOLONG: number;
  export var ENETDOWN: number;
  export var ENETRESET: number;
  export var ENETUNREACH: number;
  export var ENFILE: number;
  export var ENOBUFS: number;
  export var ENODATA: number;
  export var ENODEV: number;
  export var ENOENT: number;
  export var ENOEXEC: number;
  export var ENOLCK: number;
  export var ENOLINK: number;
  export var ENOMEM: number;
  export var ENOMSG: number;
  export var ENOPROTOOPT: number;
  export var ENOSPC: number;
  export var ENOSR: number;
  export var ENOSTR: number;
  export var ENOSYS: number;
  export var ENOTCONN: number;
  export var ENOTDIR: number;
  export var ENOTEMPTY: number;
  export var ENOTSOCK: number;
  export var ENOTSUP: number;
  export var ENOTTY: number;
  export var ENXIO: number;
  export var EOPNOTSUPP: number;
  export var EOVERFLOW: number;
  export var EPERM: number;
  export var EPIPE: number;
  export var EPROTO: number;
  export var EPROTONOSUPPORT: number;
  export var EPROTOTYPE: number;
  export var ERANGE: number;
  export var EROFS: number;
  export var ESPIPE: number;
  export var ESRCH: number;
  export var ETIME: number;
  export var ETIMEDOUT: number;
  export var ETXTBSY: number;
  export var EWOULDBLOCK: number;
  export var EXDEV: number;
  export var WSAEINTR: number;
  export var WSAEBADF: number;
  export var WSAEACCES: number;
  export var WSAEFAULT: number;
  export var WSAEINVAL: number;
  export var WSAEMFILE: number;
  export var WSAEWOULDBLOCK: number;
  export var WSAEINPROGRESS: number;
  export var WSAEALREADY: number;
  export var WSAENOTSOCK: number;
  export var WSAEDESTADDRREQ: number;
  export var WSAEMSGSIZE: number;
  export var WSAEPROTOTYPE: number;
  export var WSAENOPROTOOPT: number;
  export var WSAEPROTONOSUPPORT: number;
  export var WSAESOCKTNOSUPPORT: number;
  export var WSAEOPNOTSUPP: number;
  export var WSAEPFNOSUPPORT: number;
  export var WSAEAFNOSUPPORT: number;
  export var WSAEADDRINUSE: number;
  export var WSAEADDRNOTAVAIL: number;
  export var WSAENETDOWN: number;
  export var WSAENETUNREACH: number;
  export var WSAENETRESET: number;
  export var WSAECONNABORTED: number;
  export var WSAECONNRESET: number;
  export var WSAENOBUFS: number;
  export var WSAEISCONN: number;
  export var WSAENOTCONN: number;
  export var WSAESHUTDOWN: number;
  export var WSAETOOMANYREFS: number;
  export var WSAETIMEDOUT: number;
  export var WSAECONNREFUSED: number;
  export var WSAELOOP: number;
  export var WSAENAMETOOLONG: number;
  export var WSAEHOSTDOWN: number;
  export var WSAEHOSTUNREACH: number;
  export var WSAENOTEMPTY: number;
  export var WSAEPROCLIM: number;
  export var WSAEUSERS: number;
  export var WSAEDQUOT: number;
  export var WSAESTALE: number;
  export var WSAEREMOTE: number;
  export var WSASYSNOTREADY: number;
  export var WSAVERNOTSUPPORTED: number;
  export var WSANOTINITIALISED: number;
  export var WSAEDISCON: number;
  export var WSAENOMORE: number;
  export var WSAECANCELLED: number;
  export var WSAEINVALIDPROCTABLE: number;
  export var WSAEINVALIDPROVIDER: number;
  export var WSAEPROVIDERFAILEDINIT: number;
  export var WSASYSCALLFAILURE: number;
  export var WSASERVICE_NOT_FOUND: number;
  export var WSATYPE_NOT_FOUND: number;
  export var WSA_E_NO_MORE: number;
  export var WSA_E_CANCELLED: number;
  export var WSAEREFUSED: number;
  export var SIGHUP: number;
  export var SIGINT: number;
  export var SIGILL: number;
  export var SIGABRT: number;
  export var SIGFPE: number;
  export var SIGKILL: number;
  export var SIGSEGV: number;
  export var SIGTERM: number;
  export var SIGBREAK: number;
  export var SIGWINCH: number;
  export var SSL_OP_ALL: number;
  export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
  export var SSL_OP_CIPHER_SERVER_PREFERENCE: number;
  export var SSL_OP_CISCO_ANYCONNECT: number;
  export var SSL_OP_COOKIE_EXCHANGE: number;
  export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
  export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
  export var SSL_OP_EPHEMERAL_RSA: number;
  export var SSL_OP_LEGACY_SERVER_CONNECT: number;
  export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
  export var SSL_OP_MICROSOFT_SESS_ID_BUG: number;
  export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
  export var SSL_OP_NETSCAPE_CA_DN_BUG: number;
  export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
  export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
  export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
  export var SSL_OP_NO_COMPRESSION: number;
  export var SSL_OP_NO_QUERY_MTU: number;
  export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
  export var SSL_OP_NO_SSLv2: number;
  export var SSL_OP_NO_SSLv3: number;
  export var SSL_OP_NO_TICKET: number;
  export var SSL_OP_NO_TLSv1: number;
  export var SSL_OP_NO_TLSv1_1: number;
  export var SSL_OP_NO_TLSv1_2: number;
  export var SSL_OP_PKCS1_CHECK_1: number;
  export var SSL_OP_PKCS1_CHECK_2: number;
  export var SSL_OP_SINGLE_DH_USE: number;
  export var SSL_OP_SINGLE_ECDH_USE: number;
  export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
  export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
  export var SSL_OP_TLS_BLOCK_PADDING_BUG: number;
  export var SSL_OP_TLS_D5_BUG: number;
  export var SSL_OP_TLS_ROLLBACK_BUG: number;
  export var ENGINE_METHOD_DSA: number;
  export var ENGINE_METHOD_DH: number;
  export var ENGINE_METHOD_RAND: number;
  export var ENGINE_METHOD_ECDH: number;
  export var ENGINE_METHOD_ECDSA: number;
  export var ENGINE_METHOD_CIPHERS: number;
  export var ENGINE_METHOD_DIGESTS: number;
  export var ENGINE_METHOD_STORE: number;
  export var ENGINE_METHOD_PKEY_METHS: number;
  export var ENGINE_METHOD_PKEY_ASN1_METHS: number;
  export var ENGINE_METHOD_ALL: number;
  export var ENGINE_METHOD_NONE: number;
  export var DH_CHECK_P_NOT_SAFE_PRIME: number;
  export var DH_CHECK_P_NOT_PRIME: number;
  export var DH_UNABLE_TO_CHECK_GENERATOR: number;
  export var DH_NOT_SUITABLE_GENERATOR: number;
  export var NPN_ENABLED: number;
  export var RSA_PKCS1_PADDING: number;
  export var RSA_SSLV23_PADDING: number;
  export var RSA_NO_PADDING: number;
  export var RSA_PKCS1_OAEP_PADDING: number;
  export var RSA_X931_PADDING: number;
  export var RSA_PKCS1_PSS_PADDING: number;
  export var POINT_CONVERSION_COMPRESSED: number;
  export var POINT_CONVERSION_UNCOMPRESSED: number;
  export var POINT_CONVERSION_HYBRID: number;
  export var O_RDONLY: number;
  export var O_WRONLY: number;
  export var O_RDWR: number;
  export var S_IFMT: number;
  export var S_IFREG: number;
  export var S_IFDIR: number;
  export var S_IFCHR: number;
  export var S_IFBLK: number;
  export var S_IFIFO: number;
  export var S_IFSOCK: number;
  export var S_IRWXU: number;
  export var S_IRUSR: number;
  export var S_IWUSR: number;
  export var S_IXUSR: number;
  export var S_IRWXG: number;
  export var S_IRGRP: number;
  export var S_IWGRP: number;
  export var S_IXGRP: number;
  export var S_IRWXO: number;
  export var S_IROTH: number;
  export var S_IWOTH: number;
  export var S_IXOTH: number;
  export var S_IFLNK: number;
  export var O_CREAT: number;
  export var O_EXCL: number;
  export var O_NOCTTY: number;
  export var O_DIRECTORY: number;
  export var O_NOATIME: number;
  export var O_NOFOLLOW: number;
  export var O_SYNC: number;
  export var O_SYMLINK: number;
  export var O_DIRECT: number;
  export var O_NONBLOCK: number;
  export var O_TRUNC: number;
  export var O_APPEND: number;
  export var F_OK: number;
  export var R_OK: number;
  export var W_OK: number;
  export var X_OK: number;
  export var UV_UDP_REUSEADDR: number;
}

declare module "module" {
  export = NodeModule;
}

declare module "process" {
  export = process;
}

declare module "timers" {
  export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
  export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
  export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate;
  export function clearTimeout(timeoutId: NodeJS.Timer): void;
  export function clearInterval(intervalId: NodeJS.Timer): void;
  export function clearImmediate(immediateId: NodeJS.Immediate): void;
}
